From c26ac519134b2645b7ea455b1891b0a73425b778 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Tue, 18 Jun 2013 23:40:26 +0300 Subject: [PATCH] Update test runner for TypeScript 0.9 --- _infrastructure/tests/testRunner.ts | 2 +- .../{typescript_0.8.3 => typescript}/lib.d.ts | 1520 +- .../{typescript_0.8.2 => typescript}/tsc | 0 _infrastructure/tests/typescript/tsc.js | 56803 ++++++++++++++++ .../tests/typescript/typescript.js | 55609 +++++++++++++++ .../tests/typescript_0.8.2/lib.d.ts | 8236 --- _infrastructure/tests/typescript_0.8.2/tsc.js | 25756 ------- .../tests/typescript_0.8.2/typescript.js | 24654 ------- _infrastructure/tests/typescript_0.8.3/tsc | 2 - _infrastructure/tests/typescript_0.8.3/tsc.js | 24836 ------- .../tests/typescript_0.8.3/typescript.js | 23710 ------- 11 files changed, 113578 insertions(+), 107550 deletions(-) rename _infrastructure/tests/{typescript_0.8.3 => typescript}/lib.d.ts (72%) rename _infrastructure/tests/{typescript_0.8.2 => typescript}/tsc (100%) create mode 100644 _infrastructure/tests/typescript/tsc.js create mode 100644 _infrastructure/tests/typescript/typescript.js delete mode 100644 _infrastructure/tests/typescript_0.8.2/lib.d.ts delete mode 100644 _infrastructure/tests/typescript_0.8.2/tsc.js delete mode 100644 _infrastructure/tests/typescript_0.8.2/typescript.js delete mode 100644 _infrastructure/tests/typescript_0.8.3/tsc delete mode 100644 _infrastructure/tests/typescript_0.8.3/tsc.js delete mode 100644 _infrastructure/tests/typescript_0.8.3/typescript.js diff --git a/_infrastructure/tests/testRunner.ts b/_infrastructure/tests/testRunner.ts index 0fd9198d5..c70da8d3c 100644 --- a/_infrastructure/tests/testRunner.ts +++ b/_infrastructure/tests/testRunner.ts @@ -4,7 +4,7 @@ var cfg = { root: '.', pattern: /.\-tests\.ts/g, - tsc: 'node ./_infrastructure/tests/typescript_0.8.3/tsc.js ', + tsc: 'node ./_infrastructure/tests/typescript/tsc.js ', exclude: { '.git': true, '.gitignore': true, diff --git a/_infrastructure/tests/typescript_0.8.3/lib.d.ts b/_infrastructure/tests/typescript/lib.d.ts similarity index 72% rename from _infrastructure/tests/typescript_0.8.3/lib.d.ts rename to _infrastructure/tests/typescript/lib.d.ts index 5e51f9b06..95d15c1a2 100644 --- a/_infrastructure/tests/typescript_0.8.3/lib.d.ts +++ b/_infrastructure/tests/typescript/lib.d.ts @@ -47,13 +47,13 @@ declare function parseFloat(string: string): number; * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). * @param number A numeric value. */ -declare function isNaN(number: number): bool; +declare function isNaN(number: number): boolean; /** * Determines whether a supplied number is finite. * @param number Any numeric value. */ -declare function isFinite(number: number): bool; +declare function isFinite(number: number): boolean; /** * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). @@ -80,10 +80,10 @@ declare function encodeURI(uri: string): string; declare function encodeURIComponent(uriComponent: string): string; interface PropertyDescriptor { - configurable?: bool; - enumerable?: bool; + configurable?: boolean; + enumerable?: boolean; value?: any; - writable?: bool; + writable?: boolean; get?(): any; set?(v: any): void; } @@ -106,19 +106,19 @@ interface Object { * Determines whether an object has a property with the specified name. * @param v A property name. */ - hasOwnProperty(v: string): bool; + hasOwnProperty(v: string): boolean; /** * Determines whether an object exists in another object's prototype chain. * @param v Another object whose prototype chain is to be checked. */ - isPrototypeOf(v: Object): bool; + isPrototypeOf(v: Object): boolean; /** * Determines whether a specified property is enumerable. * @param v A property name. */ - propertyIsEnumerable(v: string): bool; + propertyIsEnumerable(v: string): boolean; [s: string]: any; } @@ -199,19 +199,19 @@ declare var Object: { * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. * @param o Object to test. */ - isSealed(o: any): bool; + isSealed(o: any): boolean; /** * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. * @param o Object to test. */ - isFrozen(o: any): bool; + isFrozen(o: any): boolean; /** * Returns a value that indicates whether new properties can be added to an object. * @param o Object to test. */ - isExtensible(o: any): bool; + isExtensible(o: any): boolean; /** * Returns the names of the enumerable properties and methods of an object. @@ -429,7 +429,7 @@ interface Boolean { } declare var Boolean: { new (value?: any): Boolean; - (value?: any): bool; + (value?: any): boolean; prototype: Boolean; } @@ -767,7 +767,7 @@ interface RegExpExecArray { toString(): string; toLocaleString(): string; concat(...items: string[][]): string[]; - join(seperator?: string): string; + join(separator?: string): string; pop(): string; push(...items: string[]): number; reverse(): string[]; @@ -780,11 +780,11 @@ interface RegExpExecArray { indexOf(searchElement: string, fromIndex?: number): number; lastIndexOf(searchElement: string, fromIndex?: number): number; - every(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; - some(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; + every(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg?: any): boolean; + some(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: string, index: number, array: string[]) => void , thisArg?: any): void; map(callbackfn: (value: string, index: number, array: string[]) => any, thisArg?: any): any[]; - filter(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): string[]; + filter(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg?: any): string[]; reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; } @@ -800,15 +800,15 @@ interface RegExp { * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. * @param string String on which to perform the search. */ - test(string: string): bool; + test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */ source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - global: bool; + global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - ignoreCase: bool; + ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - multiline: bool; + multiline: boolean; lastIndex: number; @@ -939,41 +939,47 @@ declare var JSON: JSON; /// ECMAScript Array API (specially handled by compiler) //////////////// -interface Array { +interface Array { toString(): string; toLocaleString(): string; - concat(...items: _element[][]): _element[]; - concat(...items: _element[]): _element[]; - join(seperator?: string): string; - pop(): _element; - push(...items: _element[]): number; - reverse(): _element[]; - shift(): _element; - slice(start: number, end?: number): _element[]; - sort(compareFn?: (a: _element, b: _element) => number): _element[]; - splice(start: number): _element[]; - splice(start: number, deleteCount: number, ...items: _element[]): _element[]; - unshift(...items: _element[]): number; + concat(...items: U[]): T[]; + concat(...items: T[]): T[]; + join(separator?: string): string; + pop(): T; + push(...items: T[]): number; + reverse(): T[]; + shift(): T; + slice(start: number, end?: number): T[]; + sort(compareFn?: (a: T, b: T) => number): T[]; + splice(start: number): T[]; + splice(start: number, deleteCount: number, ...items: T[]): T[]; + unshift(...items: T[]): number; - indexOf(searchElement: _element, fromIndex?: number): number; - lastIndexOf(searchElement: _element, fromIndex?: number): number; - every(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; - some(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; - forEach(callbackfn: (value: _element, index: number, array: _element[]) => void , thisArg?: any): void; - map(callbackfn: (value: _element, index: number, array: _element[]) => any, thisArg?: any): any[]; - filter(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): _element[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; + indexOf(searchElement: T, fromIndex?: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + forEach(callbackfn: (value: T, index: number, array: T[]) => void , thisArg?: any): void; + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; length: number; + } declare var Array: { - new (...items: any[]): any[]; - (...items: any[]): any[]; - isArray(arg: any): bool; - prototype: Array; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): boolean; + prototype: Array; } + //////////////// /// IE10 ECMAScript Extensions //////////////// @@ -1147,21 +1153,21 @@ declare var Float64Array: { interface DataView extends ArrayBufferView { getInt8(byteOffset: number): number; getUint8(byteOffset: number): number; - getInt16(byteOffset: number, littleEndian?: bool): number; - getUint16(byteOffset: number, littleEndian?: bool): number; - getInt32(byteOffset: number, littleEndian?: bool): number; - getUint32(byteOffset: number, littleEndian?: bool): number; - getFloat32(byteOffset: number, littleEndian?: bool): number; - getFloat64(byteOffset: number, littleEndian?: bool): number; + getInt16(byteOffset: number, littleEndian?: boolean): number; + getUint16(byteOffset: number, littleEndian?: boolean): number; + getInt32(byteOffset: number, littleEndian?: boolean): number; + getUint32(byteOffset: number, littleEndian?: boolean): number; + getFloat32(byteOffset: number, littleEndian?: boolean): number; + getFloat64(byteOffset: number, littleEndian?: boolean): number; setInt8(byteOffset: number, value: number): void; setUint8(byteOffset: number, value: number): void; - setInt16(byteOffset: number, value: number, littleEndian?: bool): void; - setUint16(byteOffset: number, value: number, littleEndian?: bool): void; - setInt32(byteOffset: number, value: number, littleEndian?: bool): void; - setUint32(byteOffset: number, value: number, littleEndian?: bool): void; - setFloat32(byteOffset: number, value: number, littleEndian?: bool): void; - setFloat64(byteOffset: number, value: number, littleEndian?: bool): void; + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; } declare var DataView: { prototype: DataView; @@ -1211,7 +1217,7 @@ interface TreeWalker { filter: NodeFilterCallback; root: Node; currentNode: Node; - expandEntityReferences: bool; + expandEntityReferences: boolean; previousSibling(): Node; lastChild(): Node; nextSibling(): Node; @@ -1256,11 +1262,18 @@ declare var Performance: { interface SVGSVGElementEventHandlers { onresize: (ev: UIEvent) => any; + addEventListener(type: "resize", listener: (ev: UIEvent) => void, useCapture?: boolean): void; onunload: (ev: Event) => any; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onscroll: (ev: UIEvent) => any; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onzoom: (ev: any) => any; + addEventListener(type: "zoom", listener: (ev: any) => any, useCapture?: boolean): void; onabort: (ev: UIEvent) => any; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface MSDataBindingTableExtensions { @@ -1279,7 +1292,7 @@ interface DOML2DeprecatedAlignmentStyle_HTMLParagraphElement { interface CompositionEvent extends UIEvent { data: string; locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, locale: string): void; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, dataArg: string, locale: string): void; } declare var CompositionEvent: { prototype: CompositionEvent; @@ -1350,18 +1363,18 @@ interface MSStyleCSSProperties extends MSCSSProperties { posLeft: number; pixelTop: number; pixelBottom: number; - textDecorationNone: bool; + textDecorationNone: boolean; pixelLeft: number; posTop: number; posBottom: number; - textDecorationOverline: bool; + textDecorationOverline: boolean; posWidth: number; - textDecorationLineThrough: bool; + textDecorationLineThrough: boolean; pixelHeight: number; - textDecorationBlink: bool; + textDecorationBlink: boolean; posRight: number; pixelRight: number; - textDecorationUnderline: bool; + textDecorationUnderline: boolean; } declare var MSStyleCSSProperties: { prototype: MSStyleCSSProperties; @@ -1371,10 +1384,10 @@ declare var MSStyleCSSProperties: { interface MSCSSStyleSheetExtensions { owningElement: Element; imports: StyleSheetList; - isAlternate: bool; + isAlternate: boolean; rules: MSCSSRuleList; - isPrefAlternate: bool; - readOnly: bool; + isPrefAlternate: boolean; + readOnly: boolean; cssText: string; href: string; id: string; @@ -1464,7 +1477,7 @@ interface PositionErrorCallback { interface DOMImplementation extends DOMHTMLImplementation { createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; - hasFeature(feature: string, version?: string): bool; + hasFeature(feature: string, version?: string): boolean; } declare var DOMImplementation: { prototype: DOMImplementation; @@ -1494,46 +1507,74 @@ interface DocumentRange { interface MSHTMLDocumentExtensions { onrowexit: (ev: MSEventObj) => any; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; compatible: MSCompatibleInfoCollection; oncontrolselect: (ev: MSEventObj) => any; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowsinserted: (ev: MSEventObj) => any; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onpropertychange: (ev: MSEventObj) => any; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; media: string; onafterupdate: (ev: MSEventObj) => any; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onhelp: (ev: Event) => any; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; uniqueID: string; onbeforeactivate: (ev: UIEvent) => any; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onstoragecommit: (ev: StorageEvent) => any; + addEventListener(type: "storagecommit", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; onselectionchange: (ev: Event) => any; + addEventListener(type: "selectionchange", listener: (ev: Event) => any, useCapture?: boolean): void; documentMode: number; onfocusout: (ev: FocusEvent) => any; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; ondataavailable: (ev: MSEventObj) => any; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onbeforeupdate: (ev: MSEventObj) => any; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onfocusin: (ev: FocusEvent) => any; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; security: string; namespaces: MSNamespaceInfoCollection; ondatasetcomplete: (ev: MSEventObj) => any; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onbeforedeactivate: (ev: UIEvent) => any; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onstop: (ev: Event) => any; + addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; onactivate: (ev: UIEvent) => any; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; + addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; frames: Window; onselectstart: (ev: Event) => any; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; onerrorupdate: (ev: MSEventObj) => any; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; parentWindow: Window; ondeactivate: (ev: UIEvent) => any; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondatasetchanged: (ev: MSEventObj) => any; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowsdelete: (ev: MSEventObj) => any; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onmsthumbnailclick: (ev: MSSiteModeEvent) => any; + addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; onrowenter: (ev: MSEventObj) => any; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onbeforeeditfocus: (ev: MSEventObj) => any; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; Script: MSScriptHost; oncellchange: (ev: MSEventObj) => any; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; URLUnencoded: string; updateSettings(): void; - execCommandShowHelp(commandId: string): bool; + execCommandShowHelp(commandId: string): boolean; releaseCapture(): void; focus(): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface CSS2Properties { @@ -1666,16 +1707,119 @@ interface Element extends Node, NodeSelector, ElementTraversal, MSElementExtensi scrollHeight: number; getAttribute(name?: string): string; getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; - hasAttributeNS(namespaceURI: string, localName: string): bool; + hasAttributeNS(namespaceURI: string, localName: string): boolean; getBoundingClientRect(): ClientRect; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; setAttributeNodeNS(newAttr: Attr): Attr; - hasAttribute(name: string): bool; + hasAttribute(name: string): boolean; removeAttribute(name?: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; getAttributeNode(name: string): Attr; getElementsByTagName(name: string): NodeList; + getElementsByTagName(name: "a"): NodeListOf; + getElementsByTagName(name: "abbr"): NodeListOf; + getElementsByTagName(name: "address"): NodeListOf; + getElementsByTagName(name: "area"): NodeListOf; + getElementsByTagName(name: "article"): NodeListOf; + getElementsByTagName(name: "aside"): NodeListOf; + getElementsByTagName(name: "audio"): NodeListOf; + getElementsByTagName(name: "b"): NodeListOf; + getElementsByTagName(name: "base"): NodeListOf; + getElementsByTagName(name: "bdi"): NodeListOf; + getElementsByTagName(name: "bdo"): NodeListOf; + getElementsByTagName(name: "blockquote"): NodeListOf; + getElementsByTagName(name: "body"): NodeListOf; + getElementsByTagName(name: "br"): NodeListOf; + getElementsByTagName(name: "button"): NodeListOf; + getElementsByTagName(name: "canvas"): NodeListOf; + getElementsByTagName(name: "caption"): NodeListOf; + getElementsByTagName(name: "cite"): NodeListOf; + getElementsByTagName(name: "code"): NodeListOf; + getElementsByTagName(name: "col"): NodeListOf; + getElementsByTagName(name: "colgroup"): NodeListOf; + getElementsByTagName(name: "datalist"): NodeListOf; + getElementsByTagName(name: "dd"): NodeListOf; + getElementsByTagName(name: "del"): NodeListOf; + getElementsByTagName(name: "dfn"): NodeListOf; + getElementsByTagName(name: "div"): NodeListOf; + getElementsByTagName(name: "dl"): NodeListOf; + getElementsByTagName(name: "dt"): NodeListOf; + getElementsByTagName(name: "em"): NodeListOf; + getElementsByTagName(name: "embed"): NodeListOf; + getElementsByTagName(name: "fieldset"): NodeListOf; + getElementsByTagName(name: "figcaption"): NodeListOf; + getElementsByTagName(name: "figure"): NodeListOf; + getElementsByTagName(name: "footer"): NodeListOf; + getElementsByTagName(name: "form"): NodeListOf; + getElementsByTagName(name: "h1"): NodeListOf; + getElementsByTagName(name: "h2"): NodeListOf; + getElementsByTagName(name: "h3"): NodeListOf; + getElementsByTagName(name: "h4"): NodeListOf; + getElementsByTagName(name: "h5"): NodeListOf; + getElementsByTagName(name: "h6"): NodeListOf; + getElementsByTagName(name: "head"): NodeListOf; + getElementsByTagName(name: "header"): NodeListOf; + getElementsByTagName(name: "hgroup"): NodeListOf; + getElementsByTagName(name: "hr"): NodeListOf; + getElementsByTagName(name: "html"): NodeListOf; + getElementsByTagName(name: "i"): NodeListOf; + getElementsByTagName(name: "iframe"): NodeListOf; + getElementsByTagName(name: "img"): NodeListOf; + getElementsByTagName(name: "input"): NodeListOf; + getElementsByTagName(name: "ins"): NodeListOf; + getElementsByTagName(name: "kbd"): NodeListOf; + getElementsByTagName(name: "label"): NodeListOf; + getElementsByTagName(name: "legend"): NodeListOf; + getElementsByTagName(name: "li"): NodeListOf; + getElementsByTagName(name: "link"): NodeListOf; + getElementsByTagName(name: "main"): NodeListOf; + getElementsByTagName(name: "map"): NodeListOf; + getElementsByTagName(name: "mark"): NodeListOf; + getElementsByTagName(name: "menu"): NodeListOf; + getElementsByTagName(name: "meta"): NodeListOf; + getElementsByTagName(name: "nav"): NodeListOf; + getElementsByTagName(name: "noscript"): NodeListOf; + getElementsByTagName(name: "object"): NodeListOf; + getElementsByTagName(name: "ol"): NodeListOf; + getElementsByTagName(name: "optgroup"): NodeListOf; + getElementsByTagName(name: "option"): NodeListOf; + getElementsByTagName(name: "p"): NodeListOf; + getElementsByTagName(name: "param"): NodeListOf; + getElementsByTagName(name: "pre"): NodeListOf; + getElementsByTagName(name: "progress"): NodeListOf; + getElementsByTagName(name: "q"): NodeListOf; + getElementsByTagName(name: "rp"): NodeListOf; + getElementsByTagName(name: "rt"): NodeListOf; + getElementsByTagName(name: "ruby"): NodeListOf; + getElementsByTagName(name: "s"): NodeListOf; + getElementsByTagName(name: "samp"): NodeListOf; + getElementsByTagName(name: "script"): NodeListOf; + getElementsByTagName(name: "section"): NodeListOf; + getElementsByTagName(name: "select"): NodeListOf; + getElementsByTagName(name: "small"): NodeListOf; + getElementsByTagName(name: "source"): NodeListOf; + getElementsByTagName(name: "span"): NodeListOf; + getElementsByTagName(name: "strong"): NodeListOf; + getElementsByTagName(name: "style"): NodeListOf; + getElementsByTagName(name: "sub"): NodeListOf; + getElementsByTagName(name: "summary"): NodeListOf; + getElementsByTagName(name: "sup"): NodeListOf; + getElementsByTagName(name: "table"): NodeListOf; + getElementsByTagName(name: "tbody"): NodeListOf; + getElementsByTagName(name: "td"): NodeListOf; + getElementsByTagName(name: "textarea"): NodeListOf; + getElementsByTagName(name: "tfoot"): NodeListOf; + getElementsByTagName(name: "th"): NodeListOf; + getElementsByTagName(name: "thead"): NodeListOf; + getElementsByTagName(name: "title"): NodeListOf; + getElementsByTagName(name: "tr"): NodeListOf; + getElementsByTagName(name: "track"): NodeListOf; + getElementsByTagName(name: "u"): NodeListOf; + getElementsByTagName(name: "ul"): NodeListOf; + getElementsByTagName(name: "var"): NodeListOf; + getElementsByTagName(name: "video"): NodeListOf; + getElementsByTagName(name: "wbr"): NodeListOf; setAttributeNode(newAttr: Attr): Attr; getClientRects(): ClientRectList; removeAttributeNode(oldAttr: Attr): Attr; @@ -1769,17 +1913,17 @@ interface Node extends EventTarget { prefix: string; removeChild(oldChild: Node): Node; appendChild(newChild: Node): Node; - isSupported(feature: string, version: string): bool; - isEqualNode(arg: Node): bool; + isSupported(feature: string, version: string): boolean; + isEqualNode(arg: Node): boolean; lookupPrefix(namespaceURI: string): string; - isDefaultNamespace(namespaceURI: string): bool; + isDefaultNamespace(namespaceURI: string): boolean; compareDocumentPosition(other: Node): number; normalize(): void; - isSameNode(other: Node): bool; - hasAttributes(): bool; + isSameNode(other: Node): boolean; + hasAttributes(): boolean; lookupNamespaceURI(prefix: string): string; - cloneNode(deep?: bool): Node; - hasChildNodes(): bool; + cloneNode(deep?: boolean): Node; + hasChildNodes(): boolean; replaceChild(newChild: Node, oldChild: Node): Node; insertBefore(newChild: Node, refChild?: Node): Node; ENTITY_REFERENCE_NODE: number; @@ -1830,7 +1974,7 @@ interface MSHTMLLegendElementExtensions { interface MSCSSStyleDeclarationExtensions { getAttribute(attributeName: string, flags?: number): any; setAttribute(attributeName: string, AttributeValue: any, flags?: number): void; - removeAttribute(attributeName: string, flags?: number): bool; + removeAttribute(attributeName: string, flags?: number): boolean; } interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { @@ -1862,7 +2006,7 @@ interface MSHTMLObjectElementExtensions { } interface DOML2DeprecatedListSpaceReduction { - compact: bool; + compact: boolean; } interface CSS3Properties { @@ -1912,21 +2056,21 @@ interface MouseEvent extends UIEvent, MSMouseEventExtensions { offsetY: number; x: number; y: number; - altKey: bool; - metaKey: bool; - ctrlKey: bool; + altKey: boolean; + metaKey: boolean; + ctrlKey: boolean; offsetX: number; screenX: number; clientY: number; - shiftKey: bool; + shiftKey: boolean; screenY: number; relatedTarget: EventTarget; button: number; pageY: number; buttons: number; clientX: number; - initMouseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget): void; - getModifierState(keyArg: string): bool; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; + getModifierState(keyArg: string): boolean; } declare var MouseEvent: { prototype: MouseEvent; @@ -2000,7 +2144,7 @@ declare var TextMetrics: { } interface DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { - noWrap: bool; + noWrap: boolean; } interface HTMLOListElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, DOML2DeprecatedListSpaceReduction, MSHTMLOListElementExtensions { @@ -2041,7 +2185,7 @@ declare var CDATASection: { interface StyleMedia { type: string; - matchMedium(mediaquery: string): bool; + matchMedium(mediaquery: string): boolean; } declare var StyleMedia: { prototype: StyleMedia; @@ -2061,31 +2205,31 @@ interface TextRange { queryCommandValue(cmdID: string): any; getBookmark(): string; move(Unit: string, Count?: number): number; - queryCommandIndeterm(cmdID: string): bool; - scrollIntoView(fStart?: bool): void; - findText(string: string, count?: number, flags?: number): bool; - execCommand(cmdID: string, showUI?: bool, value?: any): bool; + queryCommandIndeterm(cmdID: string): boolean; + scrollIntoView(fStart?: boolean): void; + findText(string: string, count?: number, flags?: number): boolean; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; getBoundingClientRect(): ClientRect; - moveToBookmark(Bookmark: string): bool; - isEqual(range: TextRange): bool; + moveToBookmark(Bookmark: string): boolean; + isEqual(range: TextRange): boolean; duplicate(): TextRange; - collapse(Start?: bool): void; + collapse(Start?: boolean): void; queryCommandText(cmdID: string): string; select(): void; pasteHTML(html: string): void; - inRange(range: TextRange): bool; + inRange(range: TextRange): boolean; moveEnd(Unit: string, Count?: number): number; getClientRects(): ClientRectList; moveStart(Unit: string, Count?: number): number; parentElement(): Element; - queryCommandState(cmdID: string): bool; + queryCommandState(cmdID: string): boolean; compareEndPoints(how: string, sourceRange: TextRange): number; - execCommandShowHelp(cmdID: string): bool; + execCommandShowHelp(cmdID: string): boolean; moveToElementText(element: Element): void; - expand(Unit: string): bool; - queryCommandSupported(cmdID: string): bool; + expand(Unit: string): boolean; + queryCommandSupported(cmdID: string): boolean; setEndPoint(how: string, SourceRange: TextRange): void; - queryCommandEnabled(cmdID: string): bool; + queryCommandEnabled(cmdID: string): boolean; } declare var TextRange: { prototype: TextRange; @@ -2100,7 +2244,7 @@ interface HTMLSelectElement extends HTMLElement, MSHTMLCollectionExtensions, MSD size: number; length: number; selectedIndex: number; - multiple: bool; + multiple: boolean; type: string; remove(index?: number): void; add(element: HTMLElement, before?: any): void; @@ -2138,7 +2282,7 @@ interface SVGTests { requiredFeatures: SVGStringList; requiredExtensions: SVGStringList; systemLanguage: SVGStringList; - hasExtension(extension: string): bool; + hasExtension(extension: string): boolean; } interface MSSelection { @@ -2169,7 +2313,7 @@ declare var HTMLMetaElement: { } interface Selection { - isCollapsed: bool; + isCollapsed: boolean; anchorNode: Node; focusNode: Node; anchorOffset: number; @@ -2233,7 +2377,7 @@ interface NodeIterator { whatToShow: number; filter: NodeFilterCallback; root: Node; - expandEntityReferences: bool; + expandEntityReferences: boolean; nextNode(): Node; detach(): void; previousNode(): Node; @@ -2289,7 +2433,7 @@ interface MSHTMLAppletElementExtensions extends DOML2DeprecatedBorderStyle_HTMLO data: string; contentDocument: Document; altHtml: string; - declare: bool; + declare: boolean; type: string; BaseHref: string; } @@ -2330,15 +2474,15 @@ interface ControlRangeCollection { queryCommandValue(cmdID: string): any; remove(index: number): void; add(item: Element): void; - queryCommandIndeterm(cmdID: string): bool; + queryCommandIndeterm(cmdID: string): boolean; scrollIntoView(varargStart?: any): void; item(index: number): Element; [index: number]: Element; - execCommand(cmdID: string, showUI?: bool, value?: any): bool; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; addElement(item: Element): void; - queryCommandState(cmdID: string): bool; - queryCommandSupported(cmdID: string): bool; - queryCommandEnabled(cmdID: string): bool; + queryCommandState(cmdID: string): boolean; + queryCommandSupported(cmdID: string): boolean; + queryCommandEnabled(cmdID: string): boolean; queryCommandText(cmdID: string): string; select(): void; } @@ -2355,18 +2499,22 @@ interface MSHTMLFrameElementExtensions { width: any; contentWindow: Window; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; frameBorder: string; height: any; border: string; frameSpacing: any; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface MSNamespaceInfo extends MSEventAttachmentTarget { urn: string; onreadystatechange: (ev: Event) => any; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; name: string; readyState: string; doImport(implementationUrl: string): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var MSNamespaceInfo: { prototype: MSNamespaceInfo; @@ -2395,12 +2543,12 @@ declare var HTMLTableCaptionElement: { interface HTMLOptionElement extends HTMLElement, MSDataBindingExtensions { index: number; - defaultSelected: bool; + defaultSelected: boolean; value: string; text: string; form: HTMLFormElement; label: string; - selected: bool; + selected: boolean; } declare var HTMLOptionElement: { prototype: HTMLOptionElement; @@ -2426,7 +2574,7 @@ declare var HTMLMenuElement: { interface MouseWheelEvent extends MouseEvent { wheelDelta: number; - initMouseWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; + initMouseWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; } declare var MouseWheelEvent: { prototype: MouseWheelEvent; @@ -2480,90 +2628,151 @@ interface MSHTMLTableDataCellElementExtensions { interface Window extends ViewCSS, MSEventAttachmentTarget, MSWindowExtensions, WindowPerformance, ScreenView, EventTarget, WindowLocalStorage, WindowSessionStorage, WindowTimers { ondragend: (ev: DragEvent) => any; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeydown: (ev: KeyboardEvent) => any; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; ondragover: (ev: DragEvent) => any; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeyup: (ev: KeyboardEvent) => any; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onreset: (ev: Event) => any; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; onmouseup: (ev: MouseEvent) => any; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragstart: (ev: DragEvent) => any; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; ondrag: (ev: DragEvent) => any; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmouseover: (ev: MouseEvent) => any; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragleave: (ev: DragEvent) => any; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; history: History; name: string; onafterprint: (ev: Event) => any; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; onpause: (ev: Event) => any; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeprint: (ev: Event) => any; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; top: Window; onmousedown: (ev: MouseEvent) => any; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onseeked: (ev: Event) => any; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; opener: Window; onclick: (ev: MouseEvent) => any; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onwaiting: (ev: Event) => any; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; ononline: (ev: Event) => any; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; ondurationchange: (ev: Event) => any; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; frames: Window; onblur: (ev: FocusEvent) => any; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onemptied: (ev: Event) => any; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; onseeking: (ev: Event) => any; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; oncanplay: (ev: Event) => any; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; onstalled: (ev: Event) => any; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; onmousemove: (ev: MouseEvent) => any; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onoffline: (ev: Event) => any; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; length: number; onbeforeunload: (ev: BeforeUnloadEvent) => any; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; onratechange: (ev: Event) => any; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; onstorage: (ev: StorageEvent) => any; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; onloadstart: (ev: Event) => any; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; ondragenter: (ev: DragEvent) => any; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onsubmit: (ev: Event) => any; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; self: Window; onprogress: (ev: any) => any; + addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; oncontextmenu: (ev: MouseEvent) => any; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onchange: (ev: Event) => any; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; onloadedmetadata: (ev: Event) => any; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; onplay: (ev: Event) => any; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: ErrorFunction; onplaying: (ev: Event) => any; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; parent: Window; location: Location; oncanplaythrough: (ev: Event) => any; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; onabort: (ev: UIEvent) => any; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onreadystatechange: (ev: Event) => any; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; onkeypress: (ev: KeyboardEvent) => any; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; frameElement: Element; onloadeddata: (ev: Event) => any; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; onsuspend: (ev: Event) => any; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; window: Window; onfocus: (ev: FocusEvent) => any; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmessage: (ev: MessageEvent) => any; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; ontimeupdate: (ev: Event) => any; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; onresize: (ev: UIEvent) => any; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; navigator: Navigator; onselect: (ev: UIEvent) => any; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondrop: (ev: DragEvent) => any; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmouseout: (ev: MouseEvent) => any; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onended: (ev: Event) => any; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; onhashchange: (ev: Event) => any; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; onunload: (ev: Event) => any; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onscroll: (ev: UIEvent) => any; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onmousewheel: (ev: MouseWheelEvent) => any; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onvolumechange: (ev: Event) => any; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; oninput: (ev: Event) => any; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; alert(message?: string): void; focus(): void; print(): void; prompt(message?: string, defaul?: string): string; toString(): string; - open(url?: string, target?: string, features?: string, replace?: bool): Window; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; close(): void; - confirm(message?: string): bool; + confirm(message?: string): boolean; postMessage(message: any, targetOrigin: string, ports?: any): void; showModalDialog(url?: string, argument?: any, options?: any): any; blur(): void; getSelection(): Selection; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var Window: { prototype: Window; @@ -2589,7 +2798,7 @@ declare var MSSiteModeEvent: { } interface MSCSSStyleRuleExtensions { - readOnly: bool; + readOnly: boolean; } interface StyleSheetPageList { @@ -2608,7 +2817,6 @@ interface HTMLCollection extends MSHTMLCollectionExtensions { (nameOrIndex: any, optionalIndex: any): Element; namedItem(name: string): Element; [index: number]: Element; - [name: string]: Element; (name: string): Element; } declare var HTMLCollection: { @@ -2663,8 +2871,8 @@ interface HTMLImageElement extends HTMLElement, DOML2DeprecatedMarginStyle, DOML name: string; height: number; longDesc: string; - isMap: bool; - complete: bool; + isMap: boolean; + complete: boolean; } declare var HTMLImageElement: { prototype: HTMLImageElement; @@ -2683,7 +2891,7 @@ interface HTMLAreaElement extends HTMLElement, MSHTMLAreaElementExtensions { hash: string; target: string; href: string; - noHref: bool; + noHref: boolean; shape: string; toString(): string; } @@ -2693,9 +2901,9 @@ declare var HTMLAreaElement: { } interface EventTarget { - removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; - addEventListener(type: string, listener: EventListener, useCapture?: bool): void; - dispatchEvent(evt: Event): bool; + removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; } interface SVGAngle { @@ -2755,16 +2963,16 @@ declare var CanvasGradient: { interface KeyboardEvent extends UIEvent, KeyboardEventExtensions { location: number; - shiftKey: bool; + shiftKey: boolean; locale: string; key: string; - altKey: bool; - metaKey: bool; + altKey: boolean; + metaKey: boolean; char: string; - ctrlKey: bool; - repeat: bool; - getModifierState(keyArg: string): bool; - initKeyboardEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, keyArg: string, locationArg: number, modifiersListArg: string, repeat: bool, locale: string): void; + ctrlKey: boolean; + repeat: boolean; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; DOM_KEY_LOCATION_RIGHT: number; DOM_KEY_LOCATION_STANDARD: number; DOM_KEY_LOCATION_LEFT: number; @@ -2788,20 +2996,226 @@ interface Document extends Node, DocumentStyle, DocumentRange, HTMLDocument, Nod xmlVersion: string; implementation: DOMImplementation; xmlEncoding: string; - xmlStandalone: bool; + xmlStandalone: boolean; documentElement: HTMLElement; inputEncoding: string; createElement(tagName: string): HTMLElement; + createElement(tagName: "a"): HTMLAnchorElement; + createElement(tagName: "abbr"): HTMLElement; + createElement(tagName: "address"): HTMLElement; + createElement(tagName: "area"): HTMLAreaElement; + createElement(tagName: "article"): HTMLElement; + createElement(tagName: "aside"): HTMLElement; + createElement(tagName: "audio"): HTMLAudioElement; + createElement(tagName: "b"): HTMLElement; + createElement(tagName: "base"): HTMLBaseElement; + createElement(tagName: "bdi"): HTMLElement; + createElement(tagName: "bdo"): HTMLElement; + createElement(tagName: "blockquote"): HTMLQuoteElement; + createElement(tagName: "body"): HTMLBodyElement; + createElement(tagName: "br"): HTMLBRElement; + createElement(tagName: "button"): HTMLButtonElement; + createElement(tagName: "canvas"): HTMLCanvasElement; + createElement(tagName: "caption"): HTMLTableCaptionElement; + createElement(tagName: "cite"): HTMLElement; + createElement(tagName: "code"): HTMLElement; + createElement(tagName: "col"): HTMLTableColElement; + createElement(tagName: "colgroup"): HTMLTableColElement; + createElement(tagName: "datalist"): HTMLDataListElement; + createElement(tagName: "dd"): HTMLElement; + createElement(tagName: "del"): HTMLModElement; + createElement(tagName: "dfn"): HTMLElement; + createElement(tagName: "div"): HTMLDivElement; + createElement(tagName: "dl"): HTMLDListElement; + createElement(tagName: "dt"): HTMLElement; + createElement(tagName: "em"): HTMLElement; + createElement(tagName: "embed"): HTMLEmbedElement; + createElement(tagName: "fieldset"): HTMLFieldSetElement; + createElement(tagName: "figcaption"): HTMLElement; + createElement(tagName: "figure"): HTMLElement; + createElement(tagName: "footer"): HTMLElement; + createElement(tagName: "form"): HTMLFormElement; + createElement(tagName: "h1"): HTMLHeadingElement; + createElement(tagName: "h2"): HTMLHeadingElement; + createElement(tagName: "h3"): HTMLHeadingElement; + createElement(tagName: "h4"): HTMLHeadingElement; + createElement(tagName: "h5"): HTMLHeadingElement; + createElement(tagName: "h6"): HTMLHeadingElement; + createElement(tagName: "head"): HTMLHeadElement; + createElement(tagName: "header"): HTMLElement; + createElement(tagName: "hgroup"): HTMLElement; + createElement(tagName: "hr"): HTMLHRElement; + createElement(tagName: "html"): HTMLHtmlElement; + createElement(tagName: "i"): HTMLElement; + createElement(tagName: "iframe"): HTMLIFrameElement; + createElement(tagName: "img"): HTMLImageElement; + createElement(tagName: "input"): HTMLInputElement; + createElement(tagName: "ins"): HTMLModElement; + createElement(tagName: "kbd"): HTMLElement; + createElement(tagName: "label"): HTMLLabelElement; + createElement(tagName: "legend"): HTMLLegendElement; + createElement(tagName: "li"): HTMLLIElement; + createElement(tagName: "link"): HTMLLinkElement; + createElement(tagName: "main"): HTMLElement; + createElement(tagName: "map"): HTMLMapElement; + createElement(tagName: "mark"): HTMLElement; + createElement(tagName: "menu"): HTMLMenuElement; + createElement(tagName: "meta"): HTMLMetaElement; + createElement(tagName: "nav"): HTMLElement; + createElement(tagName: "noscript"): HTMLElement; + createElement(tagName: "object"): HTMLObjectElement; + createElement(tagName: "ol"): HTMLOListElement; + createElement(tagName: "optgroup"): HTMLOptGroupElement; + createElement(tagName: "option"): HTMLOptionElement; + createElement(tagName: "p"): HTMLParagraphElement; + createElement(tagName: "param"): HTMLParamElement; + createElement(tagName: "pre"): HTMLPreElement; + createElement(tagName: "progress"): HTMLProgressElement; + createElement(tagName: "q"): HTMLQuoteElement; + createElement(tagName: "rp"): HTMLElement; + createElement(tagName: "rt"): HTMLElement; + createElement(tagName: "ruby"): HTMLElement; + createElement(tagName: "s"): HTMLElement; + createElement(tagName: "samp"): HTMLElement; + createElement(tagName: "script"): HTMLScriptElement; + createElement(tagName: "section"): HTMLElement; + createElement(tagName: "select"): HTMLSelectElement; + createElement(tagName: "small"): HTMLElement; + createElement(tagName: "source"): HTMLSourceElement; + createElement(tagName: "span"): HTMLSpanElement; + createElement(tagName: "strong"): HTMLElement; + createElement(tagName: "style"): HTMLStyleElement; + createElement(tagName: "sub"): HTMLElement; + createElement(tagName: "summary"): HTMLElement; + createElement(tagName: "sup"): HTMLElement; + createElement(tagName: "table"): HTMLTableElement; + createElement(tagName: "tbody"): HTMLTableSectionElement; + createElement(tagName: "td"): HTMLTableDataCellElement; + createElement(tagName: "textarea"): HTMLTextAreaElement; + createElement(tagName: "tfoot"): HTMLTableSectionElement; + createElement(tagName: "th"): HTMLTableHeaderCellElement; + createElement(tagName: "thead"): HTMLTableSectionElement; + createElement(tagName: "title"): HTMLTitleElement; + createElement(tagName: "tr"): HTMLTableRowElement; + createElement(tagName: "track"): HTMLTrackElement; + createElement(tagName: "u"): HTMLElement; + createElement(tagName: "ul"): HTMLUListElement; + createElement(tagName: "var"): HTMLElement; + createElement(tagName: "video"): HTMLVideoElement; + createElement(tagName: "wbr"): HTMLElement; adoptNode(source: Node): Node; createComment(data: string): Comment; createDocumentFragment(): DocumentFragment; getElementsByTagName(tagname: string): NodeList; + getElementsByTagName(name: "a"): NodeListOf; + getElementsByTagName(name: "abbr"): NodeListOf; + getElementsByTagName(name: "address"): NodeListOf; + getElementsByTagName(name: "area"): NodeListOf; + getElementsByTagName(name: "article"): NodeListOf; + getElementsByTagName(name: "aside"): NodeListOf; + getElementsByTagName(name: "audio"): NodeListOf; + getElementsByTagName(name: "b"): NodeListOf; + getElementsByTagName(name: "base"): NodeListOf; + getElementsByTagName(name: "bdi"): NodeListOf; + getElementsByTagName(name: "bdo"): NodeListOf; + getElementsByTagName(name: "blockquote"): NodeListOf; + getElementsByTagName(name: "body"): NodeListOf; + getElementsByTagName(name: "br"): NodeListOf; + getElementsByTagName(name: "button"): NodeListOf; + getElementsByTagName(name: "canvas"): NodeListOf; + getElementsByTagName(name: "caption"): NodeListOf; + getElementsByTagName(name: "cite"): NodeListOf; + getElementsByTagName(name: "code"): NodeListOf; + getElementsByTagName(name: "col"): NodeListOf; + getElementsByTagName(name: "colgroup"): NodeListOf; + getElementsByTagName(name: "datalist"): NodeListOf; + getElementsByTagName(name: "dd"): NodeListOf; + getElementsByTagName(name: "del"): NodeListOf; + getElementsByTagName(name: "dfn"): NodeListOf; + getElementsByTagName(name: "div"): NodeListOf; + getElementsByTagName(name: "dl"): NodeListOf; + getElementsByTagName(name: "dt"): NodeListOf; + getElementsByTagName(name: "em"): NodeListOf; + getElementsByTagName(name: "embed"): NodeListOf; + getElementsByTagName(name: "fieldset"): NodeListOf; + getElementsByTagName(name: "figcaption"): NodeListOf; + getElementsByTagName(name: "figure"): NodeListOf; + getElementsByTagName(name: "footer"): NodeListOf; + getElementsByTagName(name: "form"): NodeListOf; + getElementsByTagName(name: "h1"): NodeListOf; + getElementsByTagName(name: "h2"): NodeListOf; + getElementsByTagName(name: "h3"): NodeListOf; + getElementsByTagName(name: "h4"): NodeListOf; + getElementsByTagName(name: "h5"): NodeListOf; + getElementsByTagName(name: "h6"): NodeListOf; + getElementsByTagName(name: "head"): NodeListOf; + getElementsByTagName(name: "header"): NodeListOf; + getElementsByTagName(name: "hgroup"): NodeListOf; + getElementsByTagName(name: "hr"): NodeListOf; + getElementsByTagName(name: "html"): NodeListOf; + getElementsByTagName(name: "i"): NodeListOf; + getElementsByTagName(name: "iframe"): NodeListOf; + getElementsByTagName(name: "img"): NodeListOf; + getElementsByTagName(name: "input"): NodeListOf; + getElementsByTagName(name: "ins"): NodeListOf; + getElementsByTagName(name: "kbd"): NodeListOf; + getElementsByTagName(name: "label"): NodeListOf; + getElementsByTagName(name: "legend"): NodeListOf; + getElementsByTagName(name: "li"): NodeListOf; + getElementsByTagName(name: "link"): NodeListOf; + getElementsByTagName(name: "main"): NodeListOf; + getElementsByTagName(name: "map"): NodeListOf; + getElementsByTagName(name: "mark"): NodeListOf; + getElementsByTagName(name: "menu"): NodeListOf; + getElementsByTagName(name: "meta"): NodeListOf; + getElementsByTagName(name: "nav"): NodeListOf; + getElementsByTagName(name: "noscript"): NodeListOf; + getElementsByTagName(name: "object"): NodeListOf; + getElementsByTagName(name: "ol"): NodeListOf; + getElementsByTagName(name: "optgroup"): NodeListOf; + getElementsByTagName(name: "option"): NodeListOf; + getElementsByTagName(name: "p"): NodeListOf; + getElementsByTagName(name: "param"): NodeListOf; + getElementsByTagName(name: "pre"): NodeListOf; + getElementsByTagName(name: "progress"): NodeListOf; + getElementsByTagName(name: "q"): NodeListOf; + getElementsByTagName(name: "rp"): NodeListOf; + getElementsByTagName(name: "rt"): NodeListOf; + getElementsByTagName(name: "ruby"): NodeListOf; + getElementsByTagName(name: "s"): NodeListOf; + getElementsByTagName(name: "samp"): NodeListOf; + getElementsByTagName(name: "script"): NodeListOf; + getElementsByTagName(name: "section"): NodeListOf; + getElementsByTagName(name: "select"): NodeListOf; + getElementsByTagName(name: "small"): NodeListOf; + getElementsByTagName(name: "source"): NodeListOf; + getElementsByTagName(name: "span"): NodeListOf; + getElementsByTagName(name: "strong"): NodeListOf; + getElementsByTagName(name: "style"): NodeListOf; + getElementsByTagName(name: "sub"): NodeListOf; + getElementsByTagName(name: "summary"): NodeListOf; + getElementsByTagName(name: "sup"): NodeListOf; + getElementsByTagName(name: "table"): NodeListOf; + getElementsByTagName(name: "tbody"): NodeListOf; + getElementsByTagName(name: "td"): NodeListOf; + getElementsByTagName(name: "textarea"): NodeListOf; + getElementsByTagName(name: "tfoot"): NodeListOf; + getElementsByTagName(name: "th"): NodeListOf; + getElementsByTagName(name: "thead"): NodeListOf; + getElementsByTagName(name: "title"): NodeListOf; + getElementsByTagName(name: "tr"): NodeListOf; + getElementsByTagName(name: "track"): NodeListOf; + getElementsByTagName(name: "u"): NodeListOf; + getElementsByTagName(name: "ul"): NodeListOf; + getElementsByTagName(name: "var"): NodeListOf; + getElementsByTagName(name: "video"): NodeListOf; + getElementsByTagName(name: "wbr"): NodeListOf; getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; createProcessingInstruction(target: string, data: string): ProcessingInstruction; createElementNS(namespaceURI: string, qualifiedName: string): Element; createAttribute(name: string): Attr; createTextNode(data: string): Text; - importNode(importedNode: Node, deep: bool): Node; + importNode(importedNode: Node, deep: boolean): Node; createCDATASection(data: string): CDATASection; createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; getElementById(elementId: string): HTMLElement; @@ -2815,7 +3229,7 @@ interface MessageEvent extends Event { source: Window; origin: string; data: any; - initMessageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; } declare var MessageEvent: { prototype: MessageEvent; @@ -2834,7 +3248,7 @@ declare var SVGElement: { } interface HTMLScriptElement extends HTMLElement { - defer: bool; + defer: boolean; text: string; src: string; htmlFor: string; @@ -2908,9 +3322,9 @@ interface CanvasRenderingContext2D { restore(): void; setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; save(): void; - arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: bool): void; + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; measureText(text: string): TextMetrics; - isPointInPath(x: number, y: number): bool; + isPointInPath(x: number, y: number): boolean; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; rotate(angle: number): void; @@ -2966,12 +3380,12 @@ interface MSHTMLElementRangeExtensions { interface SVGPathSegArcAbs extends SVGPathSeg { y: number; - sweepFlag: bool; + sweepFlag: boolean; r2: number; x: number; angle: number; r1: number; - largeArcFlag: bool; + largeArcFlag: boolean; } declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; @@ -2980,7 +3394,7 @@ declare var SVGPathSegArcAbs: { interface MSScreenExtensions { deviceXDPI: number; - fontSmoothingEnabled: bool; + fontSmoothingEnabled: boolean; bufferDepth: number; logicalXDPI: number; systemXDPI: number; @@ -3038,7 +3452,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSHTMLFrameEleme marginWidth: string; contentDocument: Document; longDesc: string; - noResize: bool; + noResize: boolean; } declare var HTMLFrameElement: { prototype: HTMLFrameElement; @@ -3097,13 +3511,15 @@ interface MSHTMLButtonElementExtensions { interface XMLHttpRequest extends EventTarget, MSXMLHttpRequestExtensions { onreadystatechange: (ev: Event) => any; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; status: number; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; readyState: number; responseText: string; responseXML: Document; statusText: string; - open(method: string, url: string, async?: bool, user?: string, password?: string): void; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; send(data?: any): void; abort(): void; getAllResponseHeaders(): string; @@ -3114,6 +3530,7 @@ interface XMLHttpRequest extends EventTarget, MSXMLHttpRequestExtensions { UNSENT: number; OPENED: number; HEADERS_RECEIVED: number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var XMLHttpRequest: { prototype: XMLHttpRequest; @@ -3187,21 +3604,36 @@ interface MSHTMLTableCellElementExtensions { interface HTMLFrameSetElement extends HTMLElement, MSHTMLFrameSetElementExtensions, MSBorderColorStyle_HTMLFrameSetElement { onresize: (ev: UIEvent) => any; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ononline: (ev: Event) => any; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; onafterprint: (ev: Event) => any; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeprint: (ev: Event) => any; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; onoffline: (ev: Event) => any; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; rows: string; cols: string; onblur: (ev: FocusEvent) => any; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onunload: (ev: Event) => any; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onhashchange: (ev: Event) => any; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; onfocus: (ev: FocusEvent) => any; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmessage: (ev: MessageEvent) => any; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeunload: (ev: BeforeUnloadEvent) => any; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; onstorage: (ev: StorageEvent) => any; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; @@ -3259,8 +3691,8 @@ interface SVGLangSpace { interface DataTransfer { effectAllowed: string; dropEffect: string; - clearData(format?: string): bool; - setData(format: string, data: string): bool; + clearData(format?: string): boolean; + setData(format: string, data: string): boolean; getData(format: string): string; } declare var DataTransfer: { @@ -3270,7 +3702,7 @@ declare var DataTransfer: { interface FocusEvent extends UIEvent { relatedTarget: EventTarget; - initFocusEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, relatedTargetArg: EventTarget): void; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, relatedTargetArg: EventTarget): void; } declare var FocusEvent: { prototype: FocusEvent; @@ -3279,7 +3711,7 @@ declare var FocusEvent: { interface Range { startOffset: number; - collapsed: bool; + collapsed: boolean; endOffset: number; startContainer: Node; endContainer: Node; @@ -3293,7 +3725,7 @@ interface Range { toString(): string; compareBoundaryPoints(how: number, sourceRange: Range): number; insertNode(newNode: Node): void; - collapse(toStart: bool): void; + collapse(toStart: boolean): void; selectNodeContents(refNode: Node): void; cloneContents(): DocumentFragment; setEnd(refNode: Node, offset: number): void; @@ -3334,7 +3766,7 @@ declare var SVGPoint: { interface MSPluginsCollection { length: number; - refresh(reload?: bool): void; + refresh(reload?: boolean): void; } declare var MSPluginsCollection: { prototype: MSPluginsCollection; @@ -3372,7 +3804,7 @@ interface SVGSVGElement extends SVGElement, SVGZoomAndPan, SVGLangSpace, SVGLoca getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; unpauseAnimations(): void; createSVGRect(): SVGRect; - checkIntersection(element: SVGElement, rect: SVGRect): bool; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; unsuspendRedrawAll(): void; pauseAnimations(): void; suspendRedraw(maxWaitMilliseconds: number): number; @@ -3383,7 +3815,7 @@ interface SVGSVGElement extends SVGElement, SVGZoomAndPan, SVGLangSpace, SVGLoca unsuspendRedraw(suspendHandleID: number): void; forceRedraw(): void; getCurrentTime(): number; - checkEnclosure(element: SVGElement, rect: SVGRect): bool; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; createSVGMatrix(): SVGMatrix; createSVGPoint(): SVGPoint; createSVGNumber(): SVGNumber; @@ -3488,7 +3920,7 @@ interface ViewCSS { } interface MSAttrExtensions { - expando: bool; + expando: boolean; } interface MSStorageExtensions { @@ -3528,12 +3960,12 @@ interface MSHTMLCollectionExtensions { } interface DOML2DeprecatedWordWrapSuppression_HTMLDivElement { - noWrap: bool; + noWrap: boolean; } interface DocumentTraversal { - createNodeIterator(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): NodeIterator; - createTreeWalker(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): TreeWalker; + createNodeIterator(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: boolean): NodeIterator; + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: boolean): TreeWalker; } interface Storage extends MSStorageExtensions { @@ -3576,7 +4008,7 @@ declare var HTMLIFrameElement: { interface MSNavigatorAbilities { userLanguage: string; plugins: MSPluginsCollection; - cookieEnabled: bool; + cookieEnabled: boolean; appCodeName: string; cpuClass: string; appMinorVersion: string; @@ -3585,8 +4017,8 @@ interface MSNavigatorAbilities { mimeTypes: MSMimeTypesCollection; product: string; systemLanguage: string; - javaEnabled(): bool; - taintEnabled(): bool; + javaEnabled(): boolean; + taintEnabled(): boolean; } interface TextRangeCollection { @@ -3601,19 +4033,34 @@ declare var TextRangeCollection: { interface HTMLBodyElement extends HTMLElement, HTMLBodyElementDOML2Deprecated, MSHTMLBodyElementExtensions, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { onresize: (ev: UIEvent) => any; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ononline: (ev: Event) => any; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; onafterprint: (ev: Event) => any; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeprint: (ev: Event) => any; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; onoffline: (ev: Event) => any; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; onblur: (ev: FocusEvent) => any; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onhashchange: (ev: Event) => any; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; onunload: (ev: Event) => any; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onfocus: (ev: FocusEvent) => any; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmessage: (ev: MessageEvent) => any; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeunload: (ev: BeforeUnloadEvent) => any; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; onstorage: (ev: StorageEvent) => any; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLBodyElement: { prototype: HTMLBodyElement; @@ -3634,8 +4081,8 @@ declare var DocumentType: { } interface MSHTMLInputElementExtensions extends DOML2DeprecatedMarginStyle_HTMLInputElement, DOML2DeprecatedBorderStyle_HTMLInputElement { - status: bool; - complete: bool; + status: boolean; + complete: boolean; createTextRange(): TextRange; } @@ -3661,7 +4108,7 @@ interface MutationEvent extends Event { attrName: string; prevValue: string; relatedNode: Node; - initMutationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; MODIFICATION: number; REMOVAL: number; ADDITION: number; @@ -3676,7 +4123,7 @@ declare var MutationEvent: { interface DragEvent extends MouseEvent { dataTransfer: DataTransfer; - initDragEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; + initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; } declare var DragEvent: { prototype: DragEvent; @@ -3703,7 +4150,7 @@ interface DOML2DeprecatedListNumberingAndBulletStyle { interface HTMLInputElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLInputElement, MSImageResourceExtensions_HTMLInputElement, MSHTMLInputElementExtensions, MSDataBindingExtensions { width: string; - defaultChecked: bool; + defaultChecked: boolean; alt: string; accept: string; value: string; @@ -3713,10 +4160,10 @@ interface HTMLInputElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HT form: HTMLFormElement; selectionStart: number; height: string; - indeterminate: bool; - readOnly: bool; + indeterminate: boolean; + readOnly: boolean; size: number; - checked: bool; + checked: boolean; maxLength: number; selectionEnd: number; type: string; @@ -3767,8 +4214,8 @@ declare var SVGImageElement: { } interface MSElementExtensions { - msMatchesSelector(selectors: string): bool; - fireEvent(eventName: string, eventObj?: any): bool; + msMatchesSelector(selectors: string): boolean; + fireEvent(eventName: string, eventObj?: any): boolean; } interface HTMLParamElement extends HTMLElement { @@ -3859,20 +4306,31 @@ interface DOMHTMLImplementation { } interface NavigatorOnLine { - onLine: bool; + onLine: boolean; } interface SVGElementEventHandlers { onmouseover: (ev: MouseEvent) => any; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onmousemove: (ev: MouseEvent) => any; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onmouseout: (ev: MouseEvent) => any; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onfocusout: (ev: FocusEvent) => any; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onfocusin: (ev: FocusEvent) => any; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmousedown: (ev: MouseEvent) => any; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onmouseup: (ev: MouseEvent) => any; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onclick: (ev: MouseEvent) => any; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface WindowLocalStorage { @@ -3888,12 +4346,12 @@ declare var SVGMetadataElement: { interface SVGPathSegArcRel extends SVGPathSeg { y: number; - sweepFlag: bool; + sweepFlag: boolean; r2: number; x: number; angle: number; r1: number; - largeArcFlag: bool; + largeArcFlag: boolean; } declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; @@ -3927,14 +4385,19 @@ declare var SVGStringList: { interface XDomainRequest { timeout: number; onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onprogress: (ev: any) => any; + addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ontimeout: (ev: Event) => any; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; responseText: string; contentType: string; open(method: string, url: string): void; abort(): void; send(data?: any): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var XDomainRequest: { prototype: XDomainRequest; @@ -4020,7 +4483,7 @@ declare var SVGPathSegCurvetoCubicRel: { new(): SVGPathSegCurvetoCubicRel; } -interface MSEventObj { +interface MSEventObj extends Event { nextPage: string; keyCode: number; toElement: Element; @@ -4040,12 +4503,12 @@ interface MSEventObj { data: string; srcFilter: Object; boundElements: HTMLCollection; - cancelBubble: bool; - altLeft: bool; + cancelBubble: boolean; + altLeft: boolean; behaviorCookie: number; bookmarks: BookmarkCollection; type: string; - repeat: bool; + repeat: boolean; srcElement: Element; source: Window; fromElement: Element; @@ -4053,21 +4516,21 @@ interface MSEventObj { x: number; behaviorPart: number; qualifier: string; - altKey: bool; - ctrlKey: bool; + altKey: boolean; + ctrlKey: boolean; clientY: number; - shiftKey: bool; - shiftLeft: bool; - contentOverflow: bool; + shiftKey: boolean; + shiftLeft: boolean; + contentOverflow: boolean; screenY: number; - ctrlLeft: bool; + ctrlLeft: boolean; button: number; srcUrn: string; clientX: number; actionURL: string; getAttribute(strAttributeName: string, lFlags?: number): any; setAttribute(strAttributeName: string, AttributeValue: any, lFlags?: number): void; - removeAttribute(strAttributeName: string, lFlags?: number): bool; + removeAttribute(strAttributeName: string, lFlags?: number): boolean; } declare var MSEventObj: { prototype: MSEventObj; @@ -4110,7 +4573,8 @@ interface HTMLCanvasElement extends HTMLElement { height: number; toDataURL(): string; toDataURL(type: string, ...args: any[]): string; - getContext(contextId: string): CanvasRenderingContext2D; + getContext(contextId: string): any; + getContext(contextId: "2d"): CanvasRenderingContext2D; } declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; @@ -4134,7 +4598,7 @@ interface Location { port: string; pathname: string; host: string; - reload(flag?: bool): void; + reload(flag?: boolean): void; replace(url: string): void; assign(url: string): void; toString(): string; @@ -4155,11 +4619,11 @@ declare var HTMLStyleElement: { interface MSHTMLOptGroupElementExtensions { index: number; - defaultSelected: bool; + defaultSelected: boolean; text: string; value: string; form: HTMLFormElement; - selected: bool; + selected: boolean; } interface MSBorderColorHighlightStyle { @@ -4203,7 +4667,7 @@ declare var SVGTransform: { interface MSCSSFilter { Percent: number; - Enabled: bool; + Enabled: boolean; Duration: number; Play(Duration: number): void; Apply(): void; @@ -4217,7 +4681,7 @@ declare var MSCSSFilter: { interface UIEvent extends Event { detail: number; view: AbstractView; - initUIEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number): void; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number): void; } declare var UIEvent: { prototype: UIEvent; @@ -4284,7 +4748,7 @@ interface WheelEvent extends MouseEvent { deltaX: number; deltaMode: number; deltaY: number; - initWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; DOM_DELTA_PIXEL: number; DOM_DELTA_LINE: number; DOM_DELTA_PAGE: number; @@ -4302,7 +4766,7 @@ interface DOML2DeprecatedAlignmentStyle_HTMLDivElement { } interface MSEventAttachmentTarget { - attachEvent(event: string, listener: EventListener): bool; + attachEvent(event: string, listener: EventListener): boolean; detachEvent(event: string, listener: EventListener): void; } @@ -4329,14 +4793,14 @@ interface SVGPathElement extends SVGElement, SVGStylable, SVGAnimatedPathData, S createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcRel; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; getTotalLength(): number; createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcAbs; + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; } declare var SVGPathElement: { prototype: SVGPathElement; @@ -4354,7 +4818,7 @@ declare var MSCompatibleInfo: { interface MSHTMLDocumentEventExtensions { createEventObject(eventObj?: any): MSEventObj; - fireEvent(eventName: string, eventObj?: any): bool; + fireEvent(eventName: string, eventObj?: any): boolean; } interface Text extends CharacterData, MSNodeExtensions { @@ -4511,7 +4975,7 @@ declare var HTMLBaseFontElement: { interface CustomEvent extends Event { detail: Object; - initCustomEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, detailArg: Object): void; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: Object): void; } declare var CustomEvent: { prototype: CustomEvent; @@ -4545,7 +5009,7 @@ interface HTMLTextAreaElement extends HTMLElement, MSDataBindingExtensions, MSHT selectionStart: number; rows: number; cols: number; - readOnly: bool; + readOnly: boolean; wrap: string; selectionEnd: number; type: string; @@ -4588,7 +5052,8 @@ interface MSWindowModeless { interface HTMLMarqueeElement extends HTMLElement, DOML2DeprecatedMarginStyle_HTMLMarqueeElement, MSDataBindingExtensions, MSHTMLMarqueeElementExtensions, DOML2DeprecatedBackgroundColorStyle { width: string; onbounce: (ev: Event) => any; - trueSpeed: bool; + addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; + trueSpeed: boolean; scrollAmount: number; scrollDelay: number; behavior: string; @@ -4596,9 +5061,12 @@ interface HTMLMarqueeElement extends HTMLElement, DOML2DeprecatedMarginStyle_HTM loop: number; direction: string; onstart: (ev: Event) => any; + addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; onfinish: (ev: Event) => any; + addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; stop(): void; start(): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; @@ -4618,7 +5086,7 @@ declare var SVGRect: { interface MSNodeExtensions { swapNode(otherNode: Node): Node; - removeNode(deep?: bool): Node; + removeNode(deep?: boolean): Node; replaceNode(replacement: Node): Node; } @@ -4734,7 +5202,7 @@ declare var HTMLModElement: { } interface DOML2DeprecatedWordWrapSuppression { - noWrap: bool; + noWrap: boolean; } interface BeforeUnloadEvent extends Event { @@ -4747,7 +5215,7 @@ declare var BeforeUnloadEvent: { interface MSPopupWindow { document: HTMLDocument; - isOpen: bool; + isOpen: boolean; show(x: number, y: number, w: number, h: number, element?: any): void; hide(): void; } @@ -4795,15 +5263,15 @@ declare var SVGUseElement: { interface Event extends MSEventExtensions { timeStamp: number; - defaultPrevented: bool; - isTrusted: bool; + defaultPrevented: boolean; + isTrusted: boolean; currentTarget: EventTarget; target: EventTarget; eventPhase: number; type: string; - cancelable: bool; - bubbles: bool; - initEvent(eventTypeArg: string, canBubbleArg: bool, cancelableArg: bool): void; + cancelable: boolean; + bubbles: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; stopPropagation(): void; stopImmediatePropagation(): void; preventDefault(): void; @@ -4831,76 +5299,115 @@ declare var ImageData: { interface MSHTMLElementExtensions { onlosecapture: (ev: MSEventObj) => any; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowexit: (ev: MSEventObj) => any; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; oncontrolselect: (ev: MSEventObj) => any; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowsinserted: (ev: MSEventObj) => any; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onmouseleave: (ev: MouseEvent) => any; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; document: HTMLDocument; behaviorUrns: MSBehaviorUrnsCollection; onpropertychange: (ev: MSEventObj) => any; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; children: HTMLCollection; filters: Object; onbeforecut: (ev: DragEvent) => any; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; scopeName: string; onbeforepaste: (ev: DragEvent) => any; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmove: (ev: MSEventObj) => any; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onafterupdate: (ev: MSEventObj) => any; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onbeforecopy: (ev: DragEvent) => any; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onlayoutcomplete: (ev: MSEventObj) => any; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onresizeend: (ev: MSEventObj) => any; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; uniqueID: string; onhelp: (ev: Event) => any; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeactivate: (ev: UIEvent) => any; - isMultiLine: bool; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + isMultiLine: boolean; uniqueNumber: number; tagUrn: string; onfocusout: (ev: FocusEvent) => any; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; ondataavailable: (ev: MSEventObj) => any; - hideFocus: bool; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + hideFocus: boolean; onbeforeupdate: (ev: MSEventObj) => any; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onfilterchange: (ev: MSEventObj) => any; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onfocusin: (ev: FocusEvent) => any; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; recordNumber: any; parentTextEdit: Element; ondatasetcomplete: (ev: MSEventObj) => any; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onbeforedeactivate: (ev: UIEvent) => any; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; outerText: string; onresizestart: (ev: MSEventObj) => any; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onactivate: (ev: UIEvent) => any; - isTextEdit: bool; - isDisabled: bool; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + isTextEdit: boolean; + isDisabled: boolean; readyState: string; all: HTMLCollection; onmouseenter: (ev: MouseEvent) => any; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onmovestart: (ev: MSEventObj) => any; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onselectstart: (ev: Event) => any; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; onpaste: (ev: DragEvent) => any; - canHaveHTML: bool; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + canHaveHTML: boolean; innerText: string; onerrorupdate: (ev: MSEventObj) => any; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; ondeactivate: (ev: UIEvent) => any; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; oncut: (ev: DragEvent) => any; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmoveend: (ev: MSEventObj) => any; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onresize: (ev: UIEvent) => any; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; language: string; ondatasetchanged: (ev: MSEventObj) => any; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; oncopy: (ev: DragEvent) => any; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onrowsdelete: (ev: MSEventObj) => any; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; parentElement: HTMLElement; onrowenter: (ev: MSEventObj) => any; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onbeforeeditfocus: (ev: MSEventObj) => any; - canHaveChildren: bool; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + canHaveChildren: boolean; sourceIndex: number; oncellchange: (ev: MSEventObj) => any; - dragDrop(): bool; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + dragDrop(): boolean; releaseCapture(): void; addFilter(filter: Object): void; - setCapture(containerCapture?: bool): void; - removeBehavior(cookie: number): bool; - contains(child: HTMLElement): bool; + setCapture(containerCapture?: boolean): void; + removeBehavior(cookie: number): boolean; + contains(child: HTMLElement): boolean; applyElement(apply: Element, where?: string): Element; replaceAdjacentText(where: string, newText: string): string; - mergeAttributes(source: HTMLElement, preserveIdentity?: bool): void; + mergeAttributes(source: HTMLElement, preserveIdentity?: boolean): void; insertAdjacentElement(position: string, insertedElement: Element): Element; insertAdjacentText(where: string, text: string): void; getAdjacentText(where: string): string; @@ -4908,6 +5415,7 @@ interface MSHTMLElementExtensions { setActive(): void; addBehavior(bstrUrl: string, factory?: any): number; clearAttributes(): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface HTMLTableColElement extends HTMLElement, MSHTMLTableColElementExtensions, HTMLTableAlignment, DOML2DeprecatedAlignmentStyle_HTMLTableColElement { @@ -4921,102 +5429,155 @@ declare var HTMLTableColElement: { interface HTMLDocument extends MSEventAttachmentTarget, MSHTMLDocumentSelection, MSHTMLDocumentExtensions, MSNodeExtensions, MSResourceMetadata, MSHTMLDocumentEventExtensions, MSHTMLDocumentViewExtensions { ondragend: (ev: DragEvent) => any; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; ondragover: (ev: DragEvent) => any; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeydown: (ev: KeyboardEvent) => any; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; bgColor: string; onkeyup: (ev: KeyboardEvent) => any; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onreset: (ev: Event) => any; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; onmouseup: (ev: MouseEvent) => any; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragstart: (ev: DragEvent) => any; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; scripts: HTMLCollection; ondrag: (ev: DragEvent) => any; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; linkColor: string; ondragleave: (ev: DragEvent) => any; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmouseover: (ev: MouseEvent) => any; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onpause: (ev: Event) => any; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; charset: string; vlinkColor: string; onmousedown: (ev: MouseEvent) => any; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onseeked: (ev: Event) => any; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; title: string; onclick: (ev: MouseEvent) => any; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onwaiting: (ev: Event) => any; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; defaultCharset: string; embeds: HTMLCollection; ondurationchange: (ev: Event) => any; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; all: HTMLCollection; applets: HTMLCollection; forms: HTMLCollection; onblur: (ev: FocusEvent) => any; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; dir: string; body: HTMLElement; designMode: string; onemptied: (ev: Event) => any; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; domain: string; onseeking: (ev: Event) => any; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; oncanplay: (ev: Event) => any; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; onstalled: (ev: Event) => any; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; onmousemove: (ev: MouseEvent) => any; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onratechange: (ev: Event) => any; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; onloadstart: (ev: Event) => any; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; ondragenter: (ev: DragEvent) => any; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onsubmit: (ev: Event) => any; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; onprogress: (ev: any) => any; + addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; oncontextmenu: (ev: MouseEvent) => any; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; activeElement: Element; onchange: (ev: Event) => any; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; onloadedmetadata: (ev: Event) => any; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onplay: (ev: Event) => any; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; links: HTMLCollection; onplaying: (ev: Event) => any; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; URL: string; images: HTMLCollection; head: HTMLHeadElement; location: Location; cookie: string; oncanplaythrough: (ev: Event) => any; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; onabort: (ev: UIEvent) => any; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; characterSet: string; anchors: HTMLCollection; lastModified: string; onreadystatechange: (ev: Event) => any; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; onkeypress: (ev: KeyboardEvent) => any; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onloadeddata: (ev: Event) => any; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; plugins: HTMLCollection; onsuspend: (ev: Event) => any; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; referrer: string; readyState: string; alinkColor: string; onfocus: (ev: FocusEvent) => any; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; fgColor: string; ontimeupdate: (ev: Event) => any; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; onselect: (ev: UIEvent) => any; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondrop: (ev: DragEvent) => any; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmouseout: (ev: MouseEvent) => any; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onended: (ev: Event) => any; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; compatMode: string; onscroll: (ev: UIEvent) => any; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onmousewheel: (ev: MouseWheelEvent) => any; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onvolumechange: (ev: Event) => any; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; oninput: (ev: Event) => any; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; queryCommandValue(commandId: string): string; - queryCommandIndeterm(commandId: string): bool; - execCommand(commandId: string, showUI?: bool, value?: any): bool; + queryCommandIndeterm(commandId: string): boolean; + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; getElementsByName(elementName: string): NodeList; writeln(...content: string[]): void; - open(url?: string, name?: string, features?: string, replace?: bool): any; - queryCommandState(commandId: string): bool; + open(url?: string, name?: string, features?: string, replace?: boolean): any; + queryCommandState(commandId: string): boolean; close(): void; - hasFocus(): bool; + hasFocus(): boolean; getElementsByClassName(classNames: string): NodeList; - queryCommandSupported(commandId: string): bool; + queryCommandSupported(commandId: string): boolean; getSelection(): Selection; - queryCommandEnabled(commandId: string): bool; + queryCommandEnabled(commandId: string): boolean; write(...content: string[]): void; queryCommandText(commandId: string): string; + addEventListener(type: "DOMContentLoaded", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface SVGException { @@ -5153,7 +5714,6 @@ interface NamedNodeMap { [index: number]: Node; removeNamedItem(name: string): Node; getNamedItem(name: string): Node; - [name: string]: Node; setNamedItem(arg: Node): Node; getNamedItemNS(namespaceURI: string, localName: string): Node; setNamedItemNS(arg: Node): Node; @@ -5215,20 +5775,25 @@ declare var SVGPathSegCurvetoCubicSmoothRel: { interface MSWindowExtensions { status: string; onmouseleave: (ev: MouseEvent) => any; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; screenLeft: number; offscreenBuffering: any; maxConnectionsPerServer: number; onmouseenter: (ev: MouseEvent) => any; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; clipboardData: DataTransfer; defaultStatus: string; clientInformation: Navigator; - closed: bool; + closed: boolean; onhelp: (ev: Event) => any; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; external: BrowserPublic; event: MSEventObj; onfocusout: (ev: FocusEvent) => any; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; screenTop: number; onfocusin: (ev: FocusEvent) => any; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; showModelessDialog(url?: string, argument?: any, options?: any): Window; navigate(url: string): void; resizeBy(x?: number, y?: number): void; @@ -5241,6 +5806,7 @@ interface MSWindowExtensions { moveTo(x?: number, y?: number): void; moveBy(x?: number, y?: number): void; showHelp(url: string, helpArg?: any, features?: string): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface ProcessingInstruction extends Node { @@ -5277,7 +5843,7 @@ interface TextEvent extends UIEvent { inputMethod: number; data: string; locale: string; - initTextEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, inputMethod: number, locale: string): void; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, dataArg: string, inputMethod: number, locale: string): void; DOM_INPUT_METHOD_KEYBOARD: number; DOM_INPUT_METHOD_DROP: number; DOM_INPUT_METHOD_IME: number; @@ -5343,7 +5909,7 @@ interface SVGAnimatedPathData { } interface Position { - timestamp: Date; + timestamp: number; coords: Coordinates; } declare var Position: { @@ -5396,7 +5962,7 @@ declare var HTMLSpanElement: { } interface HTMLHRElementDOML2Deprecated { - noShade: bool; + noShade: boolean; } interface HTMLHeadElement extends HTMLElement { @@ -5455,7 +6021,7 @@ declare var SVGZoomAndPan: { } interface MSEventExtensions { - cancelBubble: bool; + cancelBubble: boolean; srcElement: Element; } @@ -5464,22 +6030,22 @@ interface HTMLMediaElement extends HTMLElement { played: TimeRanges; currentSrc: string; readyState: string; - autobuffer: bool; - loop: bool; - ended: bool; + autobuffer: boolean; + loop: boolean; + ended: boolean; buffered: TimeRanges; error: MediaError; seekable: TimeRanges; - autoplay: bool; - controls: bool; + autoplay: boolean; + controls: boolean; volume: number; src: string; playbackRate: number; duration: number; - muted: bool; + muted: boolean; defaultPlaybackRate: number; - paused: bool; - seeking: bool; + paused: boolean; + seeking: boolean; currentTime: number; preload: string; networkState: number; @@ -5533,7 +6099,7 @@ declare var MSMimeTypesCollection: { } interface StyleSheet { - disabled: bool; + disabled: boolean; ownerNode: Node; parentStyleSheet: StyleSheet; href: string; @@ -5586,6 +6152,12 @@ declare var NodeList: { new(): NodeList; } +interface NodeListOf { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + interface HTMLDTElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDTElement { } declare var HTMLDTElement: { @@ -5607,7 +6179,7 @@ interface StyleSheetPage { } interface DOML2DeprecatedWordWrapSuppression_HTMLDDElement { - noWrap: bool; + noWrap: boolean; } interface MSHTMLTableRowElementExtensions { @@ -5687,7 +6259,7 @@ interface MSHTMLOListElementExtensions { } interface DOML2DeprecatedWordWrapSuppression_HTMLDTElement { - noWrap: bool; + noWrap: boolean; } interface ScreenView extends AbstractView { @@ -5771,80 +6343,132 @@ declare var HTMLBGSoundElement: { interface HTMLElement extends Element, MSHTMLElementRangeExtensions, ElementCSSInlineStyle, MSEventAttachmentTarget, MSHTMLElementExtensions, MSNodeExtensions { ondragend: (ev: DragEvent) => any; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeydown: (ev: KeyboardEvent) => any; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; ondragover: (ev: DragEvent) => any; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeyup: (ev: KeyboardEvent) => any; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; offsetTop: number; onreset: (ev: Event) => any; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; onmouseup: (ev: MouseEvent) => any; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragstart: (ev: DragEvent) => any; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; ondrag: (ev: DragEvent) => any; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; innerHTML: string; onmouseover: (ev: MouseEvent) => any; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragleave: (ev: DragEvent) => any; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; lang: string; onpause: (ev: Event) => any; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; className: string; onseeked: (ev: Event) => any; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; onmousedown: (ev: MouseEvent) => any; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; title: string; onclick: (ev: MouseEvent) => any; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onwaiting: (ev: Event) => any; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; outerHTML: string; offsetLeft: number; ondurationchange: (ev: Event) => any; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; offsetHeight: number; dir: string; onblur: (ev: FocusEvent) => any; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onemptied: (ev: Event) => any; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; onseeking: (ev: Event) => any; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; oncanplay: (ev: Event) => any; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; onstalled: (ev: Event) => any; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; onmousemove: (ev: MouseEvent) => any; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; style: MSStyleCSSProperties; - isContentEditable: bool; + isContentEditable: boolean; onratechange: (ev: Event) => any; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; onloadstart: (ev: Event) => any; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; ondragenter: (ev: DragEvent) => any; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; contentEditable: string; onsubmit: (ev: Event) => any; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; tabIndex: number; onprogress: (ev: any) => any; + addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; oncontextmenu: (ev: MouseEvent) => any; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onchange: (ev: Event) => any; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; onloadedmetadata: (ev: Event) => any; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onplay: (ev: Event) => any; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; id: string; onplaying: (ev: Event) => any; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; oncanplaythrough: (ev: Event) => any; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; onabort: (ev: UIEvent) => any; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onreadystatechange: (ev: Event) => any; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; onkeypress: (ev: KeyboardEvent) => any; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; offsetParent: Element; onloadeddata: (ev: Event) => any; - disabled: bool; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + disabled: boolean; onsuspend: (ev: Event) => any; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; accessKey: string; onfocus: (ev: FocusEvent) => any; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; ontimeupdate: (ev: Event) => any; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; onselect: (ev: UIEvent) => any; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondrop: (ev: DragEvent) => any; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; offsetWidth: number; onmouseout: (ev: MouseEvent) => any; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onended: (ev: Event) => any; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; onscroll: (ev: UIEvent) => any; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onmousewheel: (ev: MouseWheelEvent) => any; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; onvolumechange: (ev: Event) => any; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; oninput: (ev: Event) => any; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; click(): void; getElementsByClassName(classNames: string): NodeList; - scrollIntoView(top?: bool): void; + scrollIntoView(top?: boolean): void; focus(): void; blur(): void; insertAdjacentHTML(where: string, html: string): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLElement: { prototype: HTMLElement; @@ -5884,7 +6508,7 @@ interface DOML2DeprecatedTextFlowControl_HTMLBlockElement { } interface PositionOptions { - enableHighAccuracy?: bool; + enableHighAccuracy?: boolean; timeout?: number; maximumAge?: number; } @@ -5901,7 +6525,7 @@ interface HTMLObjectElement extends HTMLElement, MSHTMLObjectElementExtensions, height: string; contentDocument: Document; codeBase: string; - declare: bool; + declare: boolean; type: string; code: string; } @@ -5924,7 +6548,7 @@ interface StorageEvent extends Event { url: string; storageArea: Storage; key: string; - initStorageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; + initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; } declare var StorageEvent: { prototype: StorageEvent; @@ -6062,8 +6686,8 @@ interface MSHTMLIsIndexElementExtensions { } interface SVGAnimatedBoolean { - animVal: bool; - baseVal: bool; + animVal: boolean; + baseVal: boolean; } declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; @@ -6079,8 +6703,10 @@ declare var SVGSwitchElement: { interface MSHTMLIFrameElementExtensions extends DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions, DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { onload: (ev: Event) => any; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; frameSpacing: any; - noResize: bool; + noResize: boolean; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface SVGPreserveAspectRatio { @@ -6121,7 +6747,7 @@ declare var SVGPreserveAspectRatio: { } interface Attr extends Node, MSAttrExtensions { - specified: bool; + specified: boolean; ownerElement: Element; value: string; name: string; @@ -6263,113 +6889,178 @@ declare var SVGMaskElement: { } declare var Audio: { new (src?: string): HTMLAudioElement; }; -declare var Option: { new (text?: string, value?: string, defaultSelected?: bool, selected?: bool): HTMLOptionElement; }; +declare var Option: { new (text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var Image: { new (width?: number, height?: number): HTMLImageElement; }; declare var ondragend: (ev: DragEvent) => any; +declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onkeydown: (ev: KeyboardEvent) => any; +declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare var ondragover: (ev: DragEvent) => any; +declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onkeyup: (ev: KeyboardEvent) => any; +declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare var onreset: (ev: Event) => any; +declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onmouseup: (ev: MouseEvent) => any; +declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var ondragstart: (ev: DragEvent) => any; +declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var ondrag: (ev: DragEvent) => any; +declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onmouseover: (ev: MouseEvent) => any; +declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var ondragleave: (ev: DragEvent) => any; +declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var history: History; declare var name: string; declare var onafterprint: (ev: Event) => any; +declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onpause: (ev: Event) => any; +declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onbeforeprint: (ev: Event) => any; +declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; declare var top: Window; declare var onmousedown: (ev: MouseEvent) => any; +declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onseeked: (ev: Event) => any; +declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; declare var opener: Window; declare var onclick: (ev: MouseEvent) => any; +declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onwaiting: (ev: Event) => any; +declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare var ononline: (ev: Event) => any; +declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; declare var ondurationchange: (ev: Event) => any; +declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var frames: Window; declare var onblur: (ev: FocusEvent) => any; +declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare var onemptied: (ev: Event) => any; +declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onseeking: (ev: Event) => any; +declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; declare var oncanplay: (ev: Event) => any; +declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onstalled: (ev: Event) => any; +declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onmousemove: (ev: MouseEvent) => any; +declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onoffline: (ev: Event) => any; +declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; declare var length: number; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; +declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; declare var onratechange: (ev: Event) => any; +declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onstorage: (ev: StorageEvent) => any; +declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; declare var onloadstart: (ev: Event) => any; +declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; declare var ondragenter: (ev: DragEvent) => any; +declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onsubmit: (ev: Event) => any; +declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; declare var self: Window; declare var onprogress: (ev: any) => any; +declare function addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; declare var ondblclick: (ev: MouseEvent) => any; +declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var oncontextmenu: (ev: MouseEvent) => any; +declare function addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onchange: (ev: Event) => any; +declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onloadedmetadata: (ev: Event) => any; +declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onplay: (ev: Event) => any; +declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onerror: ErrorFunction; declare var onplaying: (ev: Event) => any; +declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; declare var parent: Window; declare var location: Location; declare var oncanplaythrough: (ev: Event) => any; +declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onabort: (ev: UIEvent) => any; +declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var onreadystatechange: (ev: Event) => any; +declare function addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onkeypress: (ev: KeyboardEvent) => any; +declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare var frameElement: Element; declare var onloadeddata: (ev: Event) => any; +declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onsuspend: (ev: Event) => any; +declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; declare var window: Window; declare var onfocus: (ev: FocusEvent) => any; +declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare var onmessage: (ev: MessageEvent) => any; +declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; declare var ontimeupdate: (ev: Event) => any; +declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onresize: (ev: UIEvent) => any; +declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var navigator: Navigator; declare var onselect: (ev: UIEvent) => any; +declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var ondrop: (ev: DragEvent) => any; +declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onmouseout: (ev: MouseEvent) => any; +declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onended: (ev: Event) => any; +declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onhashchange: (ev: Event) => any; +declare function addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onunload: (ev: Event) => any; +declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onscroll: (ev: UIEvent) => any; +declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var onmousewheel: (ev: MouseWheelEvent) => any; +declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; declare var onload: (ev: Event) => any; +declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onvolumechange: (ev: Event) => any; +declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var oninput: (ev: Event) => any; +declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; declare function alert(message?: string): void; declare function focus(): void; declare function print(): void; declare function prompt(message?: string, defaul?: string): string; declare function toString(): string; -declare function open(url?: string, target?: string, features?: string, replace?: bool): Window; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; declare function close(): void; -declare function confirm(message?: string): bool; +declare function confirm(message?: string): boolean; declare function postMessage(message: any, targetOrigin: string, ports?: any): void; declare function showModalDialog(url?: string, argument?: any, options?: any): any; declare function blur(): void; declare function getSelection(): Selection; declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -declare function attachEvent(event: string, listener: EventListener): bool; +declare function attachEvent(event: string, listener: EventListener): boolean; declare function detachEvent(event: string, listener: EventListener): void; declare var status: string; declare var onmouseleave: (ev: MouseEvent) => any; +declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var screenLeft: number; declare var offscreenBuffering: any; declare var maxConnectionsPerServer: number; declare var onmouseenter: (ev: MouseEvent) => any; +declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var clipboardData: DataTransfer; declare var defaultStatus: string; declare var clientInformation: Navigator; -declare var closed: bool; +declare var closed: boolean; declare var onhelp: (ev: Event) => any; +declare function addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; declare var external: BrowserPublic; declare var event: MSEventObj; declare var onfocusout: (ev: FocusEvent) => any; +declare function addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare var screenTop: number; declare var onfocusin: (ev: FocusEvent) => any; +declare function addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare function showModelessDialog(url?: string, argument?: any, options?: any): Window; declare function navigate(url: string): void; declare function resizeBy(x?: number, y?: number): void; @@ -6397,9 +7088,9 @@ declare function scrollBy(x?: number, y?: number): void; declare function scrollTo(x?: number, y?: number): void; declare var styleMedia: StyleMedia; declare var document: Document; -declare function removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; -declare function addEventListener(type: string, listener: EventListener, useCapture?: bool): void; -declare function dispatchEvent(evt: Event): bool; +declare function removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +declare function dispatchEvent(evt: Event): boolean; declare var localStorage: Storage; declare var sessionStorage: Storage; declare function clearTimeout(handle: number): void; @@ -6414,6 +7105,7 @@ declare function setInterval(expression: any, msec?: number, language?: any): nu interface HTMLBodyElement { onpopstate: (ev: PopStateEvent) => any; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; } interface MSGestureEvent extends UIEvent { @@ -6434,7 +7126,7 @@ interface MSGestureEvent extends UIEvent { scale: number; gestureObject: any; clientX: number; - initGestureEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; MSGESTURE_FLAG_BEGIN: number; MSGESTURE_FLAG_END: number; MSGESTURE_FLAG_CANCEL: number; @@ -6460,10 +7152,10 @@ interface HTMLInputElement { files: FileList; max: string; formTarget: string; - willValidate: bool; + willValidate: boolean; step: string; - autofocus: bool; - required: bool; + autofocus: boolean; + required: boolean; formEnctype: string; valueAsNumber: number; placeholder: string; @@ -6475,8 +7167,8 @@ interface HTMLInputElement { pattern: string; validity: ValidityState; formNoValidate: string; - multiple: bool; - checkValidity(): bool; + multiple: boolean; + checkValidity(): boolean; stepDown(n?: number): void; stepUp(n?: number): void; setCustomValidity(error: string): void; @@ -6487,7 +7179,7 @@ interface ErrorEvent extends Event { filename: string; lineno: number; message: string; - initErrorEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, messageArg: string, filenameArg: string, linenoArg: number): void; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; } declare var ErrorEvent: { prototype: ErrorEvent; @@ -6536,25 +7228,42 @@ declare var SVGFEFloodElement: { interface MSElementExtensions { msRegionOverflow: string; onmspointerdown: (ev: any) => any; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; onmsgotpointercapture: (ev: any) => any; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturedoubletap: (ev: any) => any; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerhover: (ev: any) => any; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturehold: (ev: any) => any; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; onmspointermove: (ev: any) => any; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturechange: (ev: any) => any; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturestart: (ev: any) => any; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointercancel: (ev: any) => any; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; onmsgestureend: (ev: any) => any; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturetap: (ev: any) => any; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerout: (ev: any) => any; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; onmsinertiastart: (ev: any) => any; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; onmslostpointercapture: (ev: any) => any; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerover: (ev: any) => any; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; msContentZoomFactor: number; onmspointerup: (ev: any) => any; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; msGetRegionContent(): MSRangeCollection; msReleasePointerCapture(pointerId: number): void; msSetPointerCapture(pointerId: number): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var MSElementExtensions: { prototype: MSElementExtensions; @@ -6577,14 +7286,17 @@ declare var MSGesture: { interface TextTrackCue extends EventTarget { onenter: (ev: Event) => any; + addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; track: TextTrack; endTime: number; text: string; - pauseOnExit: bool; + pauseOnExit: boolean; id: string; startTime: number; onexit: (ev: Event) => any; + addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; getCueAsHTML(): DocumentFragment; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var TextTrackCue: { prototype: TextTrackCue; @@ -6592,7 +7304,7 @@ declare var TextTrackCue: { } interface MSHTMLDocumentViewExtensions { - msCSSOMElementFloatMetrics: bool; + msCSSOMElementFloatMetrics: boolean; msElementsFromPoint(x: number, y: number): NodeList; msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; } @@ -6630,9 +7342,9 @@ interface CSSFlexibleBoxProperties { interface DOMTokenList { length: number; - contains(token: string): bool; + contains(token: string): boolean; remove(token: string): void; - toggle(token: string): bool; + toggle(token: string): boolean; add(token: string): void; item(index: number): string; [index: number]: string; @@ -6720,7 +7432,7 @@ interface Navigator extends MSFileSaver { interface TransitionEvent extends Event { propertyName: string; elapsedTime: number; - initTransitionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, propertyNameArg: string, elapsedTimeArg: number): void; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; } declare var TransitionEvent: { prototype: TransitionEvent; @@ -6728,7 +7440,7 @@ declare var TransitionEvent: { } interface MediaQueryList { - matches: bool; + matches: boolean; media: string; addListener(listener: MediaQueryListListener): void; removeListener(listener: MediaQueryListListener): void; @@ -6763,10 +7475,10 @@ interface CSSFontsProperties { } interface CloseEvent extends Event { - wasClean: bool; + wasClean: boolean; reason: string; code: number; - initCloseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, wasCleanArg: bool, codeArg: number, reasonArg: string): void; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; } declare var CloseEvent: { prototype: CloseEvent; @@ -6778,10 +7490,14 @@ interface WebSocket extends EventTarget { readyState: number; bufferedAmount: number; onopen: (ev: Event) => any; + addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; extensions: string; onmessage: (ev: any) => any; + addEventListener(type: "message", listener: (ev: any) => any, useCapture?: boolean): void; onclose: (ev: CloseEvent) => any; + addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; binaryType: string; url: string; close(code?: number, reason?: string): void; @@ -6790,6 +7506,7 @@ interface WebSocket extends EventTarget { CLOSING: number; CONNECTING: number; CLOSED: number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var WebSocket: { prototype: WebSocket; @@ -6804,9 +7521,9 @@ declare var WebSocket: { interface ProgressEvent extends Event { loaded: number; - lengthComputable: bool; + lengthComputable: boolean; total: number; - initProgressEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, lengthComputableArg: bool, loadedArg: number, totalArg: number): void; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; } declare var ProgressEvent: { prototype: ProgressEvent; @@ -6831,7 +7548,7 @@ interface IDBObjectStore { deleteIndex(indexName: string): void; index(name: string): IDBIndex; get(key: any): IDBRequest; - delet(key: any): IDBRequest; + delete(key: any): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; @@ -6839,7 +7556,7 @@ declare var IDBObjectStore: { } interface ObjectURLOptions { - oneTimeOnly?: bool; + oneTimeOnly?: boolean; } interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { @@ -6855,21 +7572,37 @@ declare var SVGFEGaussianBlurElement: { interface MSHTMLDocumentExtensions { onmspointerdown: (ev: any) => any; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; onmspointercancel: (ev: any) => any; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturedoubletap: (ev: any) => any; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturetap: (ev: any) => any; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; onmsgestureend: (ev: any) => any; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerout: (ev: any) => any; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; onmsmanipulationstatechanged: (ev: any) => any; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; onmsinertiastart: (ev: any) => any; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerhover: (ev: any) => any; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; onmscontentzoom: (ev: any) => any; + addEventListener(type: "mscontentzoom", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturehold: (ev: any) => any; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; onmspointermove: (ev: any) => any; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerover: (ev: any) => any; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturechange: (ev: any) => any; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturestart: (ev: any) => any; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerup: (ev: any) => any; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; } declare var MSHTMLDocumentExtensions: { prototype: MSHTMLDocumentExtensions; @@ -6898,7 +7631,7 @@ declare var IDBVersionChangeEvent: { } interface IDBIndex { - unique: bool; + unique: boolean; name: string; keyPath: string; objectStore: IDBObjectStore; @@ -6929,8 +7662,8 @@ interface IDBCursor { key: any; primaryKey: any; advance(count: number): void; - delet(): IDBRequest; - continu(key?: any): void; + delete(): IDBRequest; + continue(key?: any): void; update(value: any): IDBRequest; } declare var IDBCursor: { @@ -7001,24 +7734,32 @@ declare var IDBCursorWithValue: { interface HTMLTextAreaElement { validationMessage: string; - autofocus: bool; + autofocus: boolean; validity: ValidityState; - required: bool; + required: boolean; maxLength: number; - willValidate: bool; + willValidate: boolean; placeholder: string; - checkValidity(): bool; + checkValidity(): boolean; setCustomValidity(error: string): void; } interface XMLHttpRequestEventTarget extends EventTarget { onprogress: (ev: ProgressEvent) => any; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onload: (ev: any) => any; + addEventListener(type: "load", listener: (ev: any) => any, useCapture?: boolean): void; ontimeout: (ev: any) => any; + addEventListener(type: "timeout", listener: (ev: any) => any, useCapture?: boolean): void; onabort: (ev: any) => any; + addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; onloadstart: (ev: any) => any; + addEventListener(type: "loadstart", listener: (ev: any) => any, useCapture?: boolean): void; onloadend: (ev: ProgressEvent) => any; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var XMLHttpRequestEventTarget: { prototype: XMLHttpRequestEventTarget; @@ -7033,10 +7774,13 @@ interface IDBEnvironment { interface AudioTrackList extends EventTarget { length: number; onchange: (ev: any) => any; + addEventListener(type: "change", listener: (ev: any) => any, useCapture?: boolean): void; onaddtrack: (ev: TrackEvent) => any; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; getTrackById(id: string): AudioTrack; item(index: number): AudioTrack; [index: number]: AudioTrack; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var AudioTrackList: { prototype: AudioTrackList; @@ -7045,17 +7789,24 @@ declare var AudioTrackList: { interface MSBaseReader extends EventTarget { onprogress: (ev: ProgressEvent) => any; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; readyState: number; onabort: (ev: any) => any; + addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; onloadend: (ev: ProgressEvent) => any; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onload: (ev: any) => any; + addEventListener(type: "load", listener: (ev: any) => any, useCapture?: boolean): void; onloadstart: (ev: any) => any; + addEventListener(type: "loadstart", listener: (ev: any) => any, useCapture?: boolean): void; result: any; abort(): void; LOADING: number; EMPTY: number; DONE: number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface History { @@ -7091,11 +7842,11 @@ declare var SVGFEMorphologyElement: { interface HTMLSelectElement { validationMessage: string; - autofocus: bool; + autofocus: boolean; validity: ValidityState; - required: bool; - willValidate: bool; - checkValidity(): bool; + required: boolean; + willValidate: boolean; + checkValidity(): boolean; setCustomValidity(error: string): void; } @@ -7173,7 +7924,7 @@ interface MSCSSContentZoomProperties { interface AnimationEvent extends Event { animationName: string; elapsedTime: number; - initAnimationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, animationNameArg: string, elapsedTimeArg: number): void; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; } declare var AnimationEvent: { prototype: AnimationEvent; @@ -7218,7 +7969,9 @@ declare var MSRangeCollection: { interface MSHTMLElementExtensions { onmscontentzoom: (ev: any) => any; + addEventListener(type: "mscontentzoom", listener: (ev: any) => any, useCapture?: boolean): void; onmsmanipulationstatechanged: (ev: any) => any; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; } declare var MSHTMLElementExtensions: { prototype: MSHTMLElementExtensions; @@ -7258,17 +8011,17 @@ declare var SVGFEFuncBElement: { interface IDBKeyRange { upper: any; - upperOpen: bool; + upperOpen: boolean; lower: any; - lowerOpen: bool; - bound(lower: any, upper: any, lowerOpen?: bool, upperOpen?: bool): IDBKeyRange; + lowerOpen: boolean; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; - lowerBound(bound: any, open?: bool): IDBKeyRange; - upperBound(bound: any, open?: bool): IDBKeyRange; + lowerBound(bound: any, open?: boolean): IDBKeyRange; + upperBound(bound: any, open?: boolean): IDBKeyRange; } declare var IDBKeyRange: { prototype: IDBKeyRange; - new(): IDBKeyRange; + new (): IDBKeyRange; } interface WindowConsole { @@ -7290,13 +8043,17 @@ declare var SVG1_1Properties: { interface IDBTransaction extends EventTarget { oncomplete: (ev: Event) => any; + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; db: IDBDatabase; mode: string; error: DOMError; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onabort: (ev: any) => any; + addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; abort(): void; objectStore(name: string): IDBObjectStore; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBTransaction: { prototype: IDBTransaction; @@ -7305,20 +8062,34 @@ declare var IDBTransaction: { interface MSWindowExtensions { onmspointerdown: (ev: any) => any; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; onmspointercancel: (ev: any) => any; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturedoubletap: (ev: any) => any; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; onmsgestureend: (ev: any) => any; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturetap: (ev: any) => any; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerout: (ev: any) => any; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerhover: (ev: any) => any; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; onmsinertiastart: (ev: any) => any; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointermove: (ev: any) => any; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturehold: (ev: any) => any; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerover: (ev: any) => any; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturechange: (ev: any) => any; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturestart: (ev: any) => any; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerup: (ev: any) => any; - msIsStaticHTML(html: string): bool; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + msIsStaticHTML(html: string): boolean; } declare var MSWindowExtensions: { prototype: MSWindowExtensions; @@ -7330,7 +8101,7 @@ interface AudioTrack { language: string; id: string; label: string; - enabled: bool; + enabled: boolean; } declare var AudioTrack: { prototype: AudioTrack; @@ -7407,6 +8178,7 @@ interface MSCSSTouchManipulationProperties { interface Window extends WindowAnimationTiming, WindowBase64, IDBEnvironment, WindowConsole { onpopstate: (ev: PopStateEvent) => any; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; applicationCache: ApplicationCache; matchMedia(mediaQuery: string): MediaQueryList; msMatchMedia(mediaQuery: string): MediaQueryList; @@ -7486,21 +8258,21 @@ declare var SVGFEColorMatrixElement: { interface Console { info(): void; info(message: any, ...optionalParams: any[]): void; - profile(reportName?: string): bool; + profile(reportName?: string): boolean; assert(): void; - assert(test: bool): void; - assert(test: bool, message: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): bool; - clear(): bool; - dir(): bool; - dir(value: any, ...optionalParams: any[]): bool; + assert(test: boolean): void; + assert(test: boolean, message: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + clear(): boolean; + dir(): boolean; + dir(value: any, ...optionalParams: any[]): boolean; warn(): void; warn(message: any, ...optionalParams: any[]): void; error(): void; error(message: any, ...optionalParams: any[]): void; log(): void; log(message: any, ...optionalParams: any[]): void; - profileEnd(): bool; + profileEnd(): boolean; } declare var Console: { prototype: Console; @@ -7523,10 +8295,10 @@ declare var SVGFESpotLightElement: { } interface DocumentVisibility { - msHidden: bool; + msHidden: boolean; msVisibilityState: string; visibilityState: string; - hidden: bool; + hidden: boolean; } interface WindowBase64 { @@ -7539,11 +8311,14 @@ interface IDBDatabase extends EventTarget { name: string; objectStoreNames: DOMStringList; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onabort: (ev: any) => any; + addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; close(): void; transaction(storeNames: any, mode?: string): IDBTransaction; deleteObjectStore(name: string): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBDatabase: { prototype: IDBDatabase; @@ -7559,7 +8334,7 @@ declare var MSProtocolsCollection: { interface DOMStringList { length: number; - contains(str: string): bool; + contains(str: string): boolean; item(index: number): string; [index: number]: string; } @@ -7586,7 +8361,10 @@ interface CSSMultiColumnProperties { interface IDBOpenDBRequest extends IDBRequest { onupgradeneeded: (ev: IDBVersionChangeEvent) => any; + addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; onblocked: (ev: Event) => any; + addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; @@ -7596,14 +8374,14 @@ declare var IDBOpenDBRequest: { interface HTMLButtonElement { validationMessage: string; formTarget: string; - willValidate: bool; + willValidate: boolean; formAction: string; - autofocus: bool; + autofocus: boolean; validity: ValidityState; formNoValidate: string; formEnctype: string; formMethod: string; - checkValidity(): bool; + checkValidity(): boolean; setCustomValidity(error: string): void; } @@ -7630,8 +8408,8 @@ declare var SVGFEOffsetElement: { interface HTMLFormElement { autocomplete: string; - noValidate: bool; - checkValidity(): bool; + noValidate: boolean; + checkValidity(): boolean; } interface MSUnsafeFunctionCallback { @@ -7646,7 +8424,7 @@ interface MessageEvent extends Event { } interface HTMLScriptElement { - async: bool; + async: boolean; } interface HTMLMediaElement extends MSHTMLMediaElementExtensions { @@ -7661,9 +8439,12 @@ interface TextTrack extends EventTarget { activeCues: TextTrackCueList; cues: TextTrackCueList; oncuechange: (ev: Event) => any; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; kind: string; onload: (ev: any) => any; + addEventListener(type: "load", listener: (ev: any) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; label: string; ERROR: number; SHOWING: number; @@ -7672,6 +8453,7 @@ interface TextTrack extends EventTarget { NONE: number; HIDDEN: number; DISABLED: number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var TextTrack: { prototype: TextTrack; @@ -7692,11 +8474,14 @@ interface MediaQueryListListener { interface IDBRequest extends EventTarget { source: any; onsuccess: (ev: Event) => any; + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; error: DOMError; transaction: IDBTransaction; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; readyState: string; result: any; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBRequest: { prototype: IDBRequest; @@ -7705,9 +8490,11 @@ declare var IDBRequest: { interface MessagePort extends EventTarget { onmessage: (ev: any) => any; + addEventListener(type: "message", listener: (ev: any) => any, useCapture?: boolean): void; close(): void; postMessage(message: any, ports?: any): void; start(): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var MessagePort: { prototype: MessagePort; @@ -7747,13 +8534,21 @@ declare var Blob: { interface ApplicationCache extends EventTarget { status: number; ondownloading: (ev: Event) => any; + addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; onprogress: (ev: ProgressEvent) => any; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onupdateready: (ev: Event) => any; + addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; oncached: (ev: Event) => any; + addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; onobsolete: (ev: Event) => any; + addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onchecking: (ev: Event) => any; + addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; onnoupdate: (ev: Event) => any; + addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; swapCache(): void; abort(): void; update(): void; @@ -7763,6 +8558,7 @@ interface ApplicationCache extends EventTarget { DOWNLOADING: number; IDLE: number; OBSOLETE: number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var ApplicationCache: { prototype: ApplicationCache; @@ -7776,18 +8572,22 @@ declare var ApplicationCache: { } interface MSHTMLVideoElementExtensions { - msIsStereo3D: bool; + msIsStereo3D: boolean; msStereo3DPackingMode: string; onMSVideoOptimalLayoutChanged: (ev: any) => any; + addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: any) => any, useCapture?: boolean): void; onMSVideoFrameStepCompleted: (ev: any) => any; + addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: any) => any, useCapture?: boolean): void; msStereo3DRenderMode: string; - msIsLayoutOptimalForPlayback: bool; - msHorizontalMirror: bool; + msIsLayoutOptimalForPlayback: boolean; + msHorizontalMirror: boolean; onMSVideoFormatChanged: (ev: any) => any; - msZoom: bool; - msInsertVideoEffect(activatableClassId: string, effectRequired: bool, config?: any): void; + addEventListener(type: "MSVideoFormatChanged", listener: (ev: any) => any, useCapture?: boolean): void; + msZoom: boolean; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - msFrameStep(forward: bool): void; + msFrameStep(forward: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface FrameRequestCallback { @@ -7806,12 +8606,12 @@ interface CSS3DTransformsProperties { } interface XMLHttpRequest { - withCredentials: bool; + withCredentials: boolean; } interface PopStateEvent extends Event { state: any; - initPopStateEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, stateArg: any): void; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; } declare var PopStateEvent: { prototype: PopStateEvent; @@ -7839,8 +8639,8 @@ interface CSSGridProperties { } interface MSFileSaver { - msSaveBlob(blob: any, defaultName?: string): bool; - msSaveOrOpenBlob(blob: any, defaultName?: string): bool; + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; } interface MSStream { @@ -7859,8 +8659,8 @@ interface MediaError extends MSMediaErrorExtensions { interface HTMLFieldSetElement { validationMessage: string; validity: ValidityState; - willValidate: bool; - checkValidity(): bool; + willValidate: boolean; + checkValidity(): boolean; setCustomValidity(error: string): void; } @@ -7879,9 +8679,10 @@ interface MSRangeExtensions { interface HTMLElement { oncuechange: (ev: Event) => any; - spellcheck: bool; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + spellcheck: boolean; classList: DOMTokenList; - draggable: bool; + draggable: boolean; } interface DataTransfer { @@ -7913,8 +8714,8 @@ interface Range extends MSRangeExtensions { interface HTMLObjectElement { validationMessage: string; validity: ValidityState; - willValidate: bool; - checkValidity(): bool; + willValidate: boolean; + checkValidity(): boolean; setCustomValidity(error: string): void; } @@ -7923,7 +8724,7 @@ interface MSPointerEvent extends MouseEvent { rotation: number; pressure: number; pointerType: number; - isPrimary: bool; + isPrimary: boolean; tiltY: number; height: number; intermediatePoints: any; @@ -7931,7 +8732,7 @@ interface MSPointerEvent extends MouseEvent { tiltX: number; hwTimestamp: number; pointerId: number; - initPointerEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: number, hwTimestampArg: number, isPrimary: bool): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: number, hwTimestampArg: number, isPrimary: boolean): void; getCurrentPoint(element: Element): void; getIntermediatePoints(element: Element): void; MSPOINTER_TYPE_PEN: number; @@ -7978,7 +8779,7 @@ interface MSCSSHighContrastProperties { interface MSManipulationEvent extends UIEvent { lastState: number; currentState: number; - initMSManipulationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, lastState: number, currentState: number): void; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: AbstractView, detailArg: number, lastState: number, currentState: number): void; MS_MANIPULATION_STATE_STOPPED: number; MS_MANIPULATION_STATE_ACTIVE: number; MS_MANIPULATION_STATE_INERTIA: number; @@ -7996,13 +8797,12 @@ interface FormData { } declare var FormData: { prototype: FormData; - new (): FormData; - new (form: HTMLFormElement): FormData; + new (form?: HTMLFormElement): FormData; } interface MSHTMLImageElementExtensions { - msPlayToPrimary: bool; - msPlayToDisabled: bool; + msPlayToPrimary: boolean; + msPlayToDisabled: boolean; msPlayToSource: any; } declare var MSHTMLImageElementExtensions: { @@ -8012,14 +8812,14 @@ declare var MSHTMLImageElementExtensions: { interface MSHTMLMediaElementExtensions { msAudioCategory: string; - msRealTime: bool; - msPlayToPrimary: bool; - msPlayToDisabled: bool; + msRealTime: boolean; + msPlayToPrimary: boolean; + msPlayToDisabled: boolean; msPlayToSource: any; msAudioDeviceType: string; msClearEffects(): void; msSetMediaProtectionManager(mediaProtectionManager?: any): void; - msInsertAudioEffect(activatableClassId: string, effectRequired: bool, config?: any): void; + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; } interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference { @@ -8040,6 +8840,8 @@ declare var HTMLDataListElement: { interface AbstractWorker extends EventTarget { onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { @@ -8071,15 +8873,15 @@ declare var SVGFECompositeElement: { } interface ValidityState { - customError: bool; - valueMissing: bool; - stepMismatch: bool; - rangeUnderflow: bool; - rangeOverflow: bool; - typeMismatch: bool; - patternMismatch: bool; - tooLong: bool; - valid: bool; + customError: boolean; + valueMissing: boolean; + stepMismatch: boolean; + rangeUnderflow: boolean; + rangeOverflow: boolean; + typeMismatch: boolean; + patternMismatch: boolean; + tooLong: boolean; + valid: boolean; } declare var ValidityState: { prototype: ValidityState; @@ -8095,7 +8897,7 @@ interface HTMLTrackElement extends HTMLElement { srclang: string; track: TextTrack; label: string; - defaul: bool; + defaul: boolean; } declare var HTMLTrackElement: { prototype: HTMLTrackElement; @@ -8118,12 +8920,18 @@ declare var MSApp: MSApp; interface MSXMLHttpRequestExtensions { response: any; onprogress: (ev: ProgressEvent) => any; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onabort: (ev: any) => any; + addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; responseType: string; onloadend: (ev: ProgressEvent) => any; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; upload: XMLHttpRequestEventTarget; onerror: (ev: ErrorEvent) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onloadstart: (ev: any) => any; + addEventListener(type: "loadstart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var MSXMLHttpRequestExtensions: { prototype: MSXMLHttpRequestExtensions; @@ -8191,8 +8999,10 @@ declare var MSCSSMatrix: { interface Worker extends AbstractWorker { onmessage: (ev: any) => any; + addEventListener(type: "message", listener: (ev: any) => any, useCapture?: boolean): void; postMessage(message: any, ports?: any): void; terminate(): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var Worker: { prototype: Worker; @@ -8210,8 +9020,8 @@ interface MSMediaErrorExtensions { interface MSNavigatorAbilities { msProtocols: MSProtocolsCollection; msMaxTouchPoints: number; - msPointerEnabled: bool; - msManipulationViewsEnabled: bool; + msPointerEnabled: boolean; + msManipulationViewsEnabled: boolean; } declare var MSNavigatorAbilities: { prototype: MSNavigatorAbilities; @@ -8219,6 +9029,7 @@ declare var MSNavigatorAbilities: { } declare var onpopstate: (ev: PopStateEvent) => any; +declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; declare var applicationCache: ApplicationCache; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function msMatchMedia(mediaQuery: string): MediaQueryList; @@ -8238,7 +9049,7 @@ declare var console: Console; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// -// TODO: These are only available in a Web Worker - should be in a seperate lib file +// TODO: These are only available in a Web Worker - should be in a separate lib file declare function importScripts(...urls: string[]): void; @@ -8254,11 +9065,10 @@ interface ITextWriter { } declare var WScript : { - Echo(s); + Echo(s: any); StdErr: ITextWriter; StdOut: ITextWriter; Arguments: { length: number; Item(n: number): string; }; ScriptFullName: string; Quit(exitCode?: number); } - diff --git a/_infrastructure/tests/typescript_0.8.2/tsc b/_infrastructure/tests/typescript/tsc similarity index 100% rename from _infrastructure/tests/typescript_0.8.2/tsc rename to _infrastructure/tests/typescript/tsc diff --git a/_infrastructure/tests/typescript/tsc.js b/_infrastructure/tests/typescript/tsc.js new file mode 100644 index 000000000..be3f9efb7 --- /dev/null +++ b/_infrastructure/tests/typescript/tsc.js @@ -0,0 +1,56803 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.isArray = function (value) { + return Object.prototype.toString.apply(value, []) === '[object Array]'; + }; + + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + + if (array1 === null || array2 === null) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + + return false; + }; + + ArrayUtilities.groupBy = function (array, func) { + var result = {}; + + for (var i = 0, n = array.length; i < n; i++) { + var v = array[i]; + var k = func(v); + + var list = result[k] || []; + list.push(v); + result[k] = list; + } + + return result; + }; + + ArrayUtilities.min = function (array, func) { + var min = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next < min) { + min = next; + } + } + + return min; + }; + + ArrayUtilities.max = function (array, func) { + var max = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next > max) { + max = next; + } + } + + return max; + }; + + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + + return array[array.length - 1]; + }; + + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value)) { + return value; + } + } + + return null; + }; + + ArrayUtilities.sum = function (array, func) { + var result = 0; + + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + + return result; + }; + + ArrayUtilities.whereNotNull = function (array) { + var result = []; + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (value !== null) { + result.push(value); + } + } + + return result; + }; + + ArrayUtilities.select = function (values, func) { + var result = []; + + for (var i = 0; i < values.length; i++) { + result.push(func(values[i])); + } + + return result; + }; + + ArrayUtilities.where = function (values, func) { + var result = []; + + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + + return result; + }; + + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + + return false; + }; + + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + + if (midValue === value) { + return middle; + } else if (midValue > value) { + high = middle - 1; + } else { + low = middle + 1; + } + } + + return ~low; + }; + + ArrayUtilities.createArray = function (length, defaultvalue) { + var result = []; + for (var i = 0; i < length; i++) { + result.push(defaultvalue); + } + + return result; + }; + + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Constants) { + Constants[Constants["Max31BitInteger"] = 1073741823] = "Max31BitInteger"; + Constants[Constants["Min31BitInteger"] = -1073741824] = "Min31BitInteger"; + })(TypeScript.Constants || (TypeScript.Constants = {})); + var Constants = TypeScript.Constants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Contract = (function () { + function Contract() { + } + Contract.requires = function (expression) { + if (!expression) { + throw new Error("Contract violated. False expression."); + } + }; + + Contract.throwIfFalse = function (expression) { + if (!expression) { + throw new Error("Contract violated. False expression."); + } + }; + + Contract.throwIfNull = function (value) { + if (value === null) { + throw new Error("Contract violated. Null value."); + } + }; + return Contract; + })(); + TypeScript.Contract = Contract; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Debug = (function () { + function Debug() { + } + Debug.assert = function (expression, message) { + if (!expression) { + throw new Error("Debug Failure. False expression: " + (message ? message : "")); + } + }; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCode) { + DiagnosticCode[DiagnosticCode["error_TS_0__1"] = 0] = "error_TS_0__1"; + DiagnosticCode[DiagnosticCode["warning_TS_0__1"] = 1] = "warning_TS_0__1"; + + DiagnosticCode[DiagnosticCode["_0__NL__1_TB__2"] = 2] = "_0__NL__1_TB__2"; + DiagnosticCode[DiagnosticCode["_0_TB__1"] = 3] = "_0_TB__1"; + + DiagnosticCode[DiagnosticCode["Unrecognized_escape_sequence"] = 4] = "Unrecognized_escape_sequence"; + DiagnosticCode[DiagnosticCode["Unexpected_character_0"] = 5] = "Unexpected_character_0"; + DiagnosticCode[DiagnosticCode["Missing_closing_quote_character"] = 6] = "Missing_closing_quote_character"; + DiagnosticCode[DiagnosticCode["Identifier_expected"] = 7] = "Identifier_expected"; + DiagnosticCode[DiagnosticCode["_0_keyword_expected"] = 8] = "_0_keyword_expected"; + DiagnosticCode[DiagnosticCode["_0_expected"] = 9] = "_0_expected"; + DiagnosticCode[DiagnosticCode["Identifier_expected__0__is_a_keyword"] = 10] = "Identifier_expected__0__is_a_keyword"; + DiagnosticCode[DiagnosticCode["Automatic_semicolon_insertion_not_allowed"] = 11] = "Automatic_semicolon_insertion_not_allowed"; + DiagnosticCode[DiagnosticCode["Unexpected_token__0_expected"] = 12] = "Unexpected_token__0_expected"; + DiagnosticCode[DiagnosticCode["Trailing_separator_not_allowed"] = 13] = "Trailing_separator_not_allowed"; + DiagnosticCode[DiagnosticCode["_StarSlash__expected"] = 14] = "_StarSlash__expected"; + DiagnosticCode[DiagnosticCode["_public_or_private_modifier_must_precede__static_"] = 15] = "_public_or_private_modifier_must_precede__static_"; + DiagnosticCode[DiagnosticCode["Unexpected_token_"] = 16] = "Unexpected_token_"; + DiagnosticCode[DiagnosticCode["A_catch_clause_variable_cannot_have_a_type_annotation"] = 17] = "A_catch_clause_variable_cannot_have_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Rest_parameter_must_be_last_in_list"] = 18] = "Rest_parameter_must_be_last_in_list"; + DiagnosticCode[DiagnosticCode["Parameter_cannot_have_question_mark_and_initializer"] = 19] = "Parameter_cannot_have_question_mark_and_initializer"; + DiagnosticCode[DiagnosticCode["Required_parameter_cannot_follow_optional_parameter"] = 20] = "Required_parameter_cannot_follow_optional_parameter"; + DiagnosticCode[DiagnosticCode["Index_signatures_cannot_have_rest_parameters"] = 21] = "Index_signatures_cannot_have_rest_parameters"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_cannot_have_accessibility_modifiers"] = 22] = "Index_signature_parameter_cannot_have_accessibility_modifiers"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_cannot_have_a_question_mark"] = 23] = "Index_signature_parameter_cannot_have_a_question_mark"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_cannot_have_an_initializer"] = 24] = "Index_signature_parameter_cannot_have_an_initializer"; + DiagnosticCode[DiagnosticCode["Index_signature_must_have_a_type_annotation"] = 25] = "Index_signature_must_have_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_must_have_a_type_annotation"] = 26] = "Index_signature_parameter_must_have_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_type_must_be__string__or__number_"] = 27] = "Index_signature_parameter_type_must_be__string__or__number_"; + DiagnosticCode[DiagnosticCode["_extends__clause_already_seen"] = 28] = "_extends__clause_already_seen"; + DiagnosticCode[DiagnosticCode["_extends__clause_must_precede__implements__clause"] = 29] = "_extends__clause_must_precede__implements__clause"; + DiagnosticCode[DiagnosticCode["Class_can_only_extend_single_type"] = 30] = "Class_can_only_extend_single_type"; + DiagnosticCode[DiagnosticCode["_implements__clause_already_seen"] = 31] = "_implements__clause_already_seen"; + DiagnosticCode[DiagnosticCode["Accessibility_modifier_already_seen"] = 32] = "Accessibility_modifier_already_seen"; + DiagnosticCode[DiagnosticCode["_0__modifier_must_precede__1__modifier"] = 33] = "_0__modifier_must_precede__1__modifier"; + DiagnosticCode[DiagnosticCode["_0__modifier_already_seen"] = 34] = "_0__modifier_already_seen"; + DiagnosticCode[DiagnosticCode["_0__modifier_cannot_appear_on_a_class_element"] = 35] = "_0__modifier_cannot_appear_on_a_class_element"; + DiagnosticCode[DiagnosticCode["Interface_declaration_cannot_have__implements__clause"] = 36] = "Interface_declaration_cannot_have__implements__clause"; + DiagnosticCode[DiagnosticCode["_super__invocation_cannot_have_type_arguments"] = 37] = "_super__invocation_cannot_have_type_arguments"; + DiagnosticCode[DiagnosticCode["Non_ambient_modules_cannot_use_quoted_names"] = 38] = "Non_ambient_modules_cannot_use_quoted_names"; + DiagnosticCode[DiagnosticCode["Statements_are_not_allowed_in_ambient_contexts"] = 39] = "Statements_are_not_allowed_in_ambient_contexts"; + DiagnosticCode[DiagnosticCode["Implementations_are_not_allowed_in_ambient_contexts"] = 40] = "Implementations_are_not_allowed_in_ambient_contexts"; + DiagnosticCode[DiagnosticCode["_declare__modifier_not_allowed_for_code_already_in_an_ambient_context"] = 41] = "_declare__modifier_not_allowed_for_code_already_in_an_ambient_context"; + DiagnosticCode[DiagnosticCode["Initializers_are_not_allowed_in_ambient_contexts"] = 42] = "Initializers_are_not_allowed_in_ambient_contexts"; + DiagnosticCode[DiagnosticCode["Overload_and_ambient_signatures_cannot_specify_parameter_properties"] = 43] = "Overload_and_ambient_signatures_cannot_specify_parameter_properties"; + DiagnosticCode[DiagnosticCode["Function_implementation_expected"] = 44] = "Function_implementation_expected"; + DiagnosticCode[DiagnosticCode["Constructor_implementation_expected"] = 45] = "Constructor_implementation_expected"; + DiagnosticCode[DiagnosticCode["Function_overload_name_must_be__0_"] = 46] = "Function_overload_name_must_be__0_"; + DiagnosticCode[DiagnosticCode["_0__modifier_cannot_appear_on_a_module_element"] = 47] = "_0__modifier_cannot_appear_on_a_module_element"; + DiagnosticCode[DiagnosticCode["_declare__modifier_cannot_appear_on_an_interface_declaration"] = 48] = "_declare__modifier_cannot_appear_on_an_interface_declaration"; + DiagnosticCode[DiagnosticCode["_declare__modifier_required_for_top_level_element"] = 49] = "_declare__modifier_required_for_top_level_element"; + DiagnosticCode[DiagnosticCode["_set__accessor_must_have_only_one_parameter"] = 50] = "_set__accessor_must_have_only_one_parameter"; + DiagnosticCode[DiagnosticCode["_set__accessor_parameter_cannot_have_accessibility_modifier"] = 51] = "_set__accessor_parameter_cannot_have_accessibility_modifier"; + DiagnosticCode[DiagnosticCode["_set__accessor_parameter_cannot_be_optional"] = 52] = "_set__accessor_parameter_cannot_be_optional"; + DiagnosticCode[DiagnosticCode["_set__accessor_parameter_cannot_have_initializer"] = 53] = "_set__accessor_parameter_cannot_have_initializer"; + DiagnosticCode[DiagnosticCode["_set__accessor_cannot_have_rest_parameter"] = 54] = "_set__accessor_cannot_have_rest_parameter"; + DiagnosticCode[DiagnosticCode["_get__accessor_cannot_have_parameters"] = 55] = "_get__accessor_cannot_have_parameters"; + DiagnosticCode[DiagnosticCode["Rest_parameter_cannot_be_optional"] = 56] = "Rest_parameter_cannot_be_optional"; + DiagnosticCode[DiagnosticCode["Rest_parameter_cannot_have_initializer"] = 57] = "Rest_parameter_cannot_have_initializer"; + DiagnosticCode[DiagnosticCode["Modifiers_cannot_appear_here"] = 58] = "Modifiers_cannot_appear_here"; + DiagnosticCode[DiagnosticCode["Accessors_are_only_available_when_targeting_EcmaScript5_and_higher"] = 59] = "Accessors_are_only_available_when_targeting_EcmaScript5_and_higher"; + DiagnosticCode[DiagnosticCode["Class_name_cannot_be__0_"] = 60] = "Class_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Interface_name_cannot_be__0_"] = 61] = "Interface_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Enum_name_cannot_be__0_"] = 62] = "Enum_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Module_name_cannot_be__0_"] = 63] = "Module_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Enum_member_must_have_initializer"] = 64] = "Enum_member_must_have_initializer"; + DiagnosticCode[DiagnosticCode["_module_______is_deprecated__Use__require_______instead"] = 65] = "_module_______is_deprecated__Use__require_______instead"; + DiagnosticCode[DiagnosticCode["Export_assignments_cannot_be_used_in_internal_modules"] = 66] = "Export_assignments_cannot_be_used_in_internal_modules"; + DiagnosticCode[DiagnosticCode["Export_assignment_not_allowed_in_module_with_exported_element"] = 67] = "Export_assignment_not_allowed_in_module_with_exported_element"; + DiagnosticCode[DiagnosticCode["Module_cannot_have_multiple_export_assignments"] = 68] = "Module_cannot_have_multiple_export_assignments"; + + DiagnosticCode[DiagnosticCode["Duplicate_identifier__0_"] = 69] = "Duplicate_identifier__0_"; + DiagnosticCode[DiagnosticCode["The_name__0__does_not_exist_in_the_current_scope"] = 70] = "The_name__0__does_not_exist_in_the_current_scope"; + DiagnosticCode[DiagnosticCode["The_name__0__does_not_refer_to_a_value"] = 71] = "The_name__0__does_not_refer_to_a_value"; + DiagnosticCode[DiagnosticCode["Keyword__super__can_only_be_used_inside_a_class_instance_method"] = 72] = "Keyword__super__can_only_be_used_inside_a_class_instance_method"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an_assignment_expression_must_be_a_variable__property_or_indexer"] = 73] = "The_left_hand_side_of_an_assignment_expression_must_be_a_variable__property_or_indexer"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_callable__Did_you_mean_to_include__new__"] = 74] = "Value_of_type__0__is_not_callable__Did_you_mean_to_include__new__"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_callable"] = 75] = "Value_of_type__0__is_not_callable"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_newable"] = 76] = "Value_of_type__0__is_not_newable"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_indexable_by_type__1_"] = 77] = "Value_of_type__0__is_not_indexable_by_type__1_"; + DiagnosticCode[DiagnosticCode["Operator__0__cannot_be_applied_to_types__1__and__2_"] = 78] = "Operator__0__cannot_be_applied_to_types__1__and__2_"; + DiagnosticCode[DiagnosticCode["Operator__0__cannot_be_applied_to_types__1__and__2__3"] = 79] = "Operator__0__cannot_be_applied_to_types__1__and__2__3"; + DiagnosticCode[DiagnosticCode["Cannot_convert__0__to__1_"] = 80] = "Cannot_convert__0__to__1_"; + DiagnosticCode[DiagnosticCode["Cannot_convert__0__to__1__NL__2"] = 81] = "Cannot_convert__0__to__1__NL__2"; + DiagnosticCode[DiagnosticCode["Expected_var__class__interface__or_module"] = 82] = "Expected_var__class__interface__or_module"; + DiagnosticCode[DiagnosticCode["Operator__0__cannot_be_applied_to_type__1_"] = 83] = "Operator__0__cannot_be_applied_to_type__1_"; + DiagnosticCode[DiagnosticCode["Getter__0__already_declared"] = 84] = "Getter__0__already_declared"; + DiagnosticCode[DiagnosticCode["Setter__0__already_declared"] = 85] = "Setter__0__already_declared"; + DiagnosticCode[DiagnosticCode["Accessor_cannot_have_type_parameters"] = 86] = "Accessor_cannot_have_type_parameters"; + DiagnosticCode[DiagnosticCode["Exported_class__0__extends_private_class__1_"] = 87] = "Exported_class__0__extends_private_class__1_"; + DiagnosticCode[DiagnosticCode["Exported_class__0__implements_private_interface__1_"] = 88] = "Exported_class__0__implements_private_interface__1_"; + DiagnosticCode[DiagnosticCode["Exported_interface__0__extends_private_interface__1_"] = 89] = "Exported_interface__0__extends_private_interface__1_"; + DiagnosticCode[DiagnosticCode["Exported_class__0__extends_class_from_inaccessible_module__1_"] = 90] = "Exported_class__0__extends_class_from_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Exported_class__0__implements_interface_from_inaccessible_module__1_"] = 91] = "Exported_class__0__implements_interface_from_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Exported_interface__0__extends_interface_from_inaccessible_module__1_"] = 92] = "Exported_interface__0__extends_interface_from_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_"] = 93] = "Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Public_property__0__of__exported_class_has_or_is_using_private_type__1_"] = 94] = "Public_property__0__of__exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Property__0__of__exported_interface_has_or_is_using_private_type__1_"] = 95] = "Property__0__of__exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Exported_variable__0__has_or_is_using_private_type__1_"] = 96] = "Exported_variable__0__has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_"] = 97] = "Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Public_property__0__of__exported_class_is_using_inaccessible_module__1_"] = 98] = "Public_property__0__of__exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Property__0__of__exported_interface_is_using_inaccessible_module__1_"] = 99] = "Property__0__of__exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Exported_variable__0__is_using_inaccessible_module__1_"] = 100] = "Exported_variable__0__is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_"] = 101] = "Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_"] = 102] = "Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_"] = 103] = "Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_"] = 104] = "Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_"] = 105] = "Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_"] = 106] = "Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_"] = 107] = "Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_"] = 108] = "Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_exported_function_has_or_is_using_private_type__1_"] = 109] = "Parameter__0__of_exported_function_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_"] = 110] = "Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_"] = 111] = "Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_"] = 112] = "Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_"] = 113] = "Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_"] = 114] = "Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_"] = 115] = "Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_"] = 116] = "Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_"] = 117] = "Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_exported_function_is_using_inaccessible_module__1_"] = 118] = "Parameter__0__of_exported_function_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_"] = 119] = "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_"] = 120] = "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_"] = 121] = "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_"] = 122] = "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_"] = 123] = "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_"] = 124] = "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_"] = 125] = "Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_"] = 126] = "Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_exported_function_has_or_is_using_private_type__0_"] = 127] = "Return_type_of_exported_function_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_"] = 128] = "Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_"] = 129] = "Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_"] = 130] = "Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_"] = 131] = "Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_"] = 132] = "Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_"] = 133] = "Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_"] = 134] = "Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_"] = 135] = "Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_exported_function_is_using_inaccessible_module__0_"] = 136] = "Return_type_of_exported_function_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["_new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead"] = 137] = "_new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead"; + DiagnosticCode[DiagnosticCode["A_parameter_list_must_follow_a_generic_type_argument_list______expected"] = 138] = "A_parameter_list_must_follow_a_generic_type_argument_list______expected"; + DiagnosticCode[DiagnosticCode["Multiple_constructor_implementations_are_not_allowed"] = 139] = "Multiple_constructor_implementations_are_not_allowed"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_external_module__0_"] = 140] = "Unable_to_resolve_external_module__0_"; + DiagnosticCode[DiagnosticCode["Module_cannot_be_aliased_to_a_non_module_type"] = 141] = "Module_cannot_be_aliased_to_a_non_module_type"; + DiagnosticCode[DiagnosticCode["A_class_may_only_extend_another_class"] = 142] = "A_class_may_only_extend_another_class"; + DiagnosticCode[DiagnosticCode["A_class_may_only_implement_another_class_or_interface"] = 143] = "A_class_may_only_implement_another_class_or_interface"; + DiagnosticCode[DiagnosticCode["An_interface_may_only_extend_another_class_or_interface"] = 144] = "An_interface_may_only_extend_another_class_or_interface"; + DiagnosticCode[DiagnosticCode["An_interface_cannot_implement_another_type"] = 145] = "An_interface_cannot_implement_another_type"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_type"] = 146] = "Unable_to_resolve_type"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_type_of__0_"] = 147] = "Unable_to_resolve_type_of__0_"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_type_parameter_constraint"] = 148] = "Unable_to_resolve_type_parameter_constraint"; + DiagnosticCode[DiagnosticCode["Type_parameter_constraint_cannot_be_a_primitive_type"] = 149] = "Type_parameter_constraint_cannot_be_a_primitive_type"; + DiagnosticCode[DiagnosticCode["Supplied_parameters_do_not_match_any_signature_of_call_target"] = 150] = "Supplied_parameters_do_not_match_any_signature_of_call_target"; + DiagnosticCode[DiagnosticCode["Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0"] = 151] = "Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0"; + DiagnosticCode[DiagnosticCode["Invalid__new__expression"] = 152] = "Invalid__new__expression"; + DiagnosticCode[DiagnosticCode["Call_signatures_used_in_a__new__expression_must_have_a__void__return_type"] = 153] = "Call_signatures_used_in_a__new__expression_must_have_a__void__return_type"; + DiagnosticCode[DiagnosticCode["Could_not_select_overload_for__new__expression"] = 154] = "Could_not_select_overload_for__new__expression"; + DiagnosticCode[DiagnosticCode["Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_"] = 155] = "Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_"; + DiagnosticCode[DiagnosticCode["Could_not_select_overload_for__call__expression"] = 156] = "Could_not_select_overload_for__call__expression"; + DiagnosticCode[DiagnosticCode["Unable_to_invoke_type_with_no_call_signatures"] = 157] = "Unable_to_invoke_type_with_no_call_signatures"; + DiagnosticCode[DiagnosticCode["Calls_to__super__are_only_valid_inside_a_class"] = 158] = "Calls_to__super__are_only_valid_inside_a_class"; + DiagnosticCode[DiagnosticCode["Generic_type__0__requires_1_type_argument_s_"] = 159] = "Generic_type__0__requires_1_type_argument_s_"; + DiagnosticCode[DiagnosticCode["Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_"] = 160] = "Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_"; + DiagnosticCode[DiagnosticCode["Type_of_array_literal_cannot_be_determined__Best_common_type_could_not_be_found_for_array_elements"] = 161] = "Type_of_array_literal_cannot_be_determined__Best_common_type_could_not_be_found_for_array_elements"; + DiagnosticCode[DiagnosticCode["Could_not_find_enclosing_symbol_for_dotted_name__0_"] = 162] = "Could_not_find_enclosing_symbol_for_dotted_name__0_"; + DiagnosticCode[DiagnosticCode["The_property__0__does_not_exist_on_value_of_type__1__"] = 163] = "The_property__0__does_not_exist_on_value_of_type__1__"; + DiagnosticCode[DiagnosticCode["Could_not_find_symbol__0_"] = 164] = "Could_not_find_symbol__0_"; + DiagnosticCode[DiagnosticCode["_get__and__set__accessor_must_have_the_same_type"] = 165] = "_get__and__set__accessor_must_have_the_same_type"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_in_current_location"] = 166] = "_this__cannot_be_referenced_in_current_location"; + DiagnosticCode[DiagnosticCode["Use_of_deprecated__bool__type__Use__boolean__instead"] = 167] = "Use_of_deprecated__bool__type__Use__boolean__instead"; + + DiagnosticCode[DiagnosticCode["Class__0__is_recursively_referenced_as_a_base_type_of_itself"] = 168] = "Class__0__is_recursively_referenced_as_a_base_type_of_itself"; + DiagnosticCode[DiagnosticCode["Interface__0__is_recursively_referenced_as_a_base_type_of_itself"] = 169] = "Interface__0__is_recursively_referenced_as_a_base_type_of_itself"; + DiagnosticCode[DiagnosticCode["_super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class"] = 170] = "_super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class"; + DiagnosticCode[DiagnosticCode["_super__cannot_be_referenced_in_non_derived_classes"] = 171] = "_super__cannot_be_referenced_in_non_derived_classes"; + DiagnosticCode[DiagnosticCode["A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties"] = 172] = "A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties"; + DiagnosticCode[DiagnosticCode["Constructors_for_derived_classes_must_contain_a__super__call"] = 173] = "Constructors_for_derived_classes_must_contain_a__super__call"; + DiagnosticCode[DiagnosticCode["Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors"] = 174] = "Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors"; + DiagnosticCode[DiagnosticCode["_0_1__is_inaccessible"] = 175] = "_0_1__is_inaccessible"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_within_module_bodies"] = 176] = "_this__cannot_be_referenced_within_module_bodies"; + DiagnosticCode[DiagnosticCode["_this__must_only_be_used_inside_a_function_or_script_context"] = 177] = "_this__must_only_be_used_inside_a_function_or_script_context"; + DiagnosticCode[DiagnosticCode["Invalid__addition__expression___types_do_not_agree"] = 178] = "Invalid__addition__expression___types_do_not_agree"; + DiagnosticCode[DiagnosticCode["The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"] = 179] = "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"] = 180] = "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"; + DiagnosticCode[DiagnosticCode["The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type"] = 181] = "The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type"; + DiagnosticCode[DiagnosticCode["Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation"] = 182] = "Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_"] = 183] = "Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_"; + DiagnosticCode[DiagnosticCode["The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter"] = 184] = "The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_"] = 185] = "The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_"; + DiagnosticCode[DiagnosticCode["The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"] = 186] = "The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"] = 187] = "The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"; + DiagnosticCode[DiagnosticCode["The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type"] = 188] = "The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type"; + DiagnosticCode[DiagnosticCode["Setters_cannot_return_a_value"] = 189] = "Setters_cannot_return_a_value"; + DiagnosticCode[DiagnosticCode["Tried_to_set_variable_type_to_module_type__0__"] = 190] = "Tried_to_set_variable_type_to_module_type__0__"; + DiagnosticCode[DiagnosticCode["Tried_to_set_variable_type_to_uninitialized_module_type__0__"] = 191] = "Tried_to_set_variable_type_to_uninitialized_module_type__0__"; + DiagnosticCode[DiagnosticCode["Function__0__declared_a_non_void_return_type__but_has_no_return_expression"] = 192] = "Function__0__declared_a_non_void_return_type__but_has_no_return_expression"; + DiagnosticCode[DiagnosticCode["Getters_must_return_a_value"] = 193] = "Getters_must_return_a_value"; + DiagnosticCode[DiagnosticCode["Getter_and_setter_accessors_do_not_agree_in_visibility"] = 194] = "Getter_and_setter_accessors_do_not_agree_in_visibility"; + DiagnosticCode[DiagnosticCode["Invalid_left_hand_side_of_assignment_expression"] = 195] = "Invalid_left_hand_side_of_assignment_expression"; + DiagnosticCode[DiagnosticCode["Function_declared_a_non_void_return_type__but_has_no_return_expression"] = 196] = "Function_declared_a_non_void_return_type__but_has_no_return_expression"; + DiagnosticCode[DiagnosticCode["Cannot_resolve_return_type_reference"] = 197] = "Cannot_resolve_return_type_reference"; + DiagnosticCode[DiagnosticCode["Constructors_cannot_have_a_return_type_of__void_"] = 198] = "Constructors_cannot_have_a_return_type_of__void_"; + DiagnosticCode[DiagnosticCode["Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_"] = 199] = "Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_"; + DiagnosticCode[DiagnosticCode["All_symbols_within_a__with__block_will_be_resolved_to__any__"] = 200] = "All_symbols_within_a__with__block_will_be_resolved_to__any__"; + DiagnosticCode[DiagnosticCode["Import_declarations_in_an_internal_module_cannot_reference_an_external_module"] = 201] = "Import_declarations_in_an_internal_module_cannot_reference_an_external_module"; + DiagnosticCode[DiagnosticCode["Class__0__declares_interface__1__but_does_not_implement_it__NL__2"] = 202] = "Class__0__declares_interface__1__but_does_not_implement_it__NL__2"; + DiagnosticCode[DiagnosticCode["Class__0__declares_class__1__but_does_not_implement_it__NL__2"] = 203] = "Class__0__declares_class__1__but_does_not_implement_it__NL__2"; + DiagnosticCode[DiagnosticCode["The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer"] = 204] = "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_in_initializers_in_a_class_body"] = 205] = "_this__cannot_be_referenced_in_initializers_in_a_class_body"; + DiagnosticCode[DiagnosticCode["Class__0__cannot_extend_class__1__NL__2"] = 206] = "Class__0__cannot_extend_class__1__NL__2"; + DiagnosticCode[DiagnosticCode["Interface__0__cannot_extend_class__1__NL__2"] = 207] = "Interface__0__cannot_extend_class__1__NL__2"; + DiagnosticCode[DiagnosticCode["Interface__0__cannot_extend_interface__1__NL__2"] = 208] = "Interface__0__cannot_extend_interface__1__NL__2"; + DiagnosticCode[DiagnosticCode["Duplicate_overload_signature_for__0_"] = 209] = "Duplicate_overload_signature_for__0_"; + DiagnosticCode[DiagnosticCode["Duplicate_constructor_overload_signature"] = 210] = "Duplicate_constructor_overload_signature"; + DiagnosticCode[DiagnosticCode["Duplicate_overload_call_signature"] = 211] = "Duplicate_overload_call_signature"; + DiagnosticCode[DiagnosticCode["Duplicate_overload_construct_signature"] = 212] = "Duplicate_overload_construct_signature"; + DiagnosticCode[DiagnosticCode["Overload_signature_is_not_compatible_with_function_definition"] = 213] = "Overload_signature_is_not_compatible_with_function_definition"; + DiagnosticCode[DiagnosticCode["Overload_signature_is_not_compatible_with_function_definition__NL__0"] = 214] = "Overload_signature_is_not_compatible_with_function_definition__NL__0"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_public_or_private"] = 215] = "Overload_signatures_must_all_be_public_or_private"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_exported_or_local"] = 216] = "Overload_signatures_must_all_be_exported_or_local"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_ambient_or_non_ambient"] = 217] = "Overload_signatures_must_all_be_ambient_or_non_ambient"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_optional_or_required"] = 218] = "Overload_signatures_must_all_be_optional_or_required"; + DiagnosticCode[DiagnosticCode["Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature"] = 219] = "Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_in_constructor_arguments"] = 220] = "_this__cannot_be_referenced_in_constructor_arguments"; + DiagnosticCode[DiagnosticCode["Static_member_cannot_be_accessed_off_an_instance_variable"] = 221] = "Static_member_cannot_be_accessed_off_an_instance_variable"; + DiagnosticCode[DiagnosticCode["Instance_member_cannot_be_accessed_off_a_class"] = 222] = "Instance_member_cannot_be_accessed_off_a_class"; + DiagnosticCode[DiagnosticCode["Untyped_function_calls_may_not_accept_type_arguments"] = 223] = "Untyped_function_calls_may_not_accept_type_arguments"; + DiagnosticCode[DiagnosticCode["Non_generic_functions_may_not_accept_type_arguments"] = 224] = "Non_generic_functions_may_not_accept_type_arguments"; + DiagnosticCode[DiagnosticCode["A_generic_type_may_not_reference_itself_with_its_own_type_parameters"] = 225] = "A_generic_type_may_not_reference_itself_with_its_own_type_parameters"; + DiagnosticCode[DiagnosticCode["Static_methods_cannot_reference_class_type_parameters"] = 226] = "Static_methods_cannot_reference_class_type_parameters"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___"] = 227] = "Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___"; + DiagnosticCode[DiagnosticCode["Rest_parameters_must_be_array_types"] = 228] = "Rest_parameters_must_be_array_types"; + DiagnosticCode[DiagnosticCode["Overload_signature_implementation_cannot_use_specialized_type"] = 229] = "Overload_signature_implementation_cannot_use_specialized_type"; + DiagnosticCode[DiagnosticCode["Export_assignments_may_only_be_used_in_External_modules"] = 230] = "Export_assignments_may_only_be_used_in_External_modules"; + DiagnosticCode[DiagnosticCode["Export_assignments_may_only_be_made_with_acceptable_kinds"] = 231] = "Export_assignments_may_only_be_made_with_acceptable_kinds"; + DiagnosticCode[DiagnosticCode["Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword"] = 232] = "Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword"; + DiagnosticCode[DiagnosticCode["Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__"] = 233] = "Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__"; + DiagnosticCode[DiagnosticCode["Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2"] = 234] = "Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2"; + DiagnosticCode[DiagnosticCode["All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__"] = 235] = "All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__"; + DiagnosticCode[DiagnosticCode["All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1"] = 236] = "All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1"; + DiagnosticCode[DiagnosticCode["All_named_properties_must_be_subtypes_of_string_indexer_type___0__"] = 237] = "All_named_properties_must_be_subtypes_of_string_indexer_type___0__"; + DiagnosticCode[DiagnosticCode["All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1"] = 238] = "All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1"; + DiagnosticCode[DiagnosticCode["Generic_type_references_must_include_all_type_arguments"] = 239] = "Generic_type_references_must_include_all_type_arguments"; + + DiagnosticCode[DiagnosticCode["Type__0__is_missing_property__1__from_type__2_"] = 240] = "Type__0__is_missing_property__1__from_type__2_"; + DiagnosticCode[DiagnosticCode["Types_of_property__0__of_types__1__and__2__are_incompatible"] = 241] = "Types_of_property__0__of_types__1__and__2__are_incompatible"; + DiagnosticCode[DiagnosticCode["Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3"] = 242] = "Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3"; + DiagnosticCode[DiagnosticCode["Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_"] = 243] = "Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_"; + DiagnosticCode[DiagnosticCode["Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_"] = 244] = "Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_"; + DiagnosticCode[DiagnosticCode["Types__0__and__1__define_property__2__as_private"] = 245] = "Types__0__and__1__define_property__2__as_private"; + DiagnosticCode[DiagnosticCode["Call_signatures_of_types__0__and__1__are_incompatible"] = 246] = "Call_signatures_of_types__0__and__1__are_incompatible"; + DiagnosticCode[DiagnosticCode["Call_signatures_of_types__0__and__1__are_incompatible__NL__2"] = 247] = "Call_signatures_of_types__0__and__1__are_incompatible__NL__2"; + DiagnosticCode[DiagnosticCode["Type__0__requires_a_call_signature__but_Type__1__lacks_one"] = 248] = "Type__0__requires_a_call_signature__but_Type__1__lacks_one"; + DiagnosticCode[DiagnosticCode["Construct_signatures_of_types__0__and__1__are_incompatible"] = 249] = "Construct_signatures_of_types__0__and__1__are_incompatible"; + DiagnosticCode[DiagnosticCode["Construct_signatures_of_types__0__and__1__are_incompatible__NL__2"] = 250] = "Construct_signatures_of_types__0__and__1__are_incompatible__NL__2"; + DiagnosticCode[DiagnosticCode["Type__0__requires_a_construct_signature__but_Type__1__lacks_one"] = 251] = "Type__0__requires_a_construct_signature__but_Type__1__lacks_one"; + DiagnosticCode[DiagnosticCode["Index_signatures_of_types__0__and__1__are_incompatible"] = 252] = "Index_signatures_of_types__0__and__1__are_incompatible"; + DiagnosticCode[DiagnosticCode["Index_signatures_of_types__0__and__1__are_incompatible__NL__2"] = 253] = "Index_signatures_of_types__0__and__1__are_incompatible__NL__2"; + DiagnosticCode[DiagnosticCode["Call_signature_expects__0__or_fewer_parameters"] = 254] = "Call_signature_expects__0__or_fewer_parameters"; + DiagnosticCode[DiagnosticCode["Could_not_apply_type__0__to_argument__1__which_is_of_type__2_"] = 255] = "Could_not_apply_type__0__to_argument__1__which_is_of_type__2_"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function"] = 256] = "Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function"] = 257] = "Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor"] = 258] = "Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property"] = 259] = "Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property"; + DiagnosticCode[DiagnosticCode["Types_of_static_property__0__of_class__1__and_class__2__are_incompatible"] = 260] = "Types_of_static_property__0__of_class__1__and_class__2__are_incompatible"; + DiagnosticCode[DiagnosticCode["Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3"] = 261] = "Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3"; + DiagnosticCode[DiagnosticCode["Type_reference_cannot_refer_to_container__0_"] = 262] = "Type_reference_cannot_refer_to_container__0_"; + DiagnosticCode[DiagnosticCode["Type_reference_must_refer_to_type"] = 263] = "Type_reference_must_refer_to_type"; + DiagnosticCode[DiagnosticCode["Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element"] = 264] = "Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element"; + + DiagnosticCode[DiagnosticCode["Current_host_does_not_support__w_atch_option"] = 265] = "Current_host_does_not_support__w_atch_option"; + DiagnosticCode[DiagnosticCode["ECMAScript_target_version__0__not_supported___Using_default__1__code_generation"] = 266] = "ECMAScript_target_version__0__not_supported___Using_default__1__code_generation"; + DiagnosticCode[DiagnosticCode["Module_code_generation__0__not_supported___Using_default__1__code_generation"] = 267] = "Module_code_generation__0__not_supported___Using_default__1__code_generation"; + DiagnosticCode[DiagnosticCode["Could_not_find_file___0_"] = 268] = "Could_not_find_file___0_"; + DiagnosticCode[DiagnosticCode["Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed"] = 269] = "Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed"; + DiagnosticCode[DiagnosticCode["A_file_cannot_have_a_reference_itself"] = 270] = "A_file_cannot_have_a_reference_itself"; + DiagnosticCode[DiagnosticCode["Cannot_resolve_referenced_file___0_"] = 271] = "Cannot_resolve_referenced_file___0_"; + DiagnosticCode[DiagnosticCode["Cannot_resolve_imported_file___0_"] = 272] = "Cannot_resolve_imported_file___0_"; + DiagnosticCode[DiagnosticCode["Cannot_find_the_common_subdirectory_path_for_the_input_files"] = 273] = "Cannot_find_the_common_subdirectory_path_for_the_input_files"; + DiagnosticCode[DiagnosticCode["Cannot_compile_dynamic_modules_when_emitting_into_single_file"] = 274] = "Cannot_compile_dynamic_modules_when_emitting_into_single_file"; + DiagnosticCode[DiagnosticCode["Emit_Error__0"] = 275] = "Emit_Error__0"; + })(TypeScript.DiagnosticCode || (TypeScript.DiagnosticCode = {})); + var DiagnosticCode = TypeScript.DiagnosticCode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticMessages = { + error_TS_0__1: { + category: 3 /* NoPrefix */, + message: "error TS{0}: {1}", + code: 0 + }, + warning_TS_0__1: { + category: 3 /* NoPrefix */, + message: "warning TS{0}: {1}", + code: 1 + }, + _0__NL__1_TB__2: { + category: 3 /* NoPrefix */, + message: "{0}{NL}{{1}TB}{2}", + code: 21 + }, + _0_TB__1: { + category: 3 /* NoPrefix */, + message: "{{0}TB}{1}", + code: 22 + }, + Unrecognized_escape_sequence: { + category: 1 /* Error */, + message: "Unrecognized escape sequence.", + code: 1000 + }, + Unexpected_character_0: { + category: 1 /* Error */, + message: "Unexpected character {0}.", + code: 1001 + }, + Missing_closing_quote_character: { + category: 1 /* Error */, + message: "Missing close quote character.", + code: 1002 + }, + Identifier_expected: { + category: 1 /* Error */, + message: "Identifier expected.", + code: 1003 + }, + _0_keyword_expected: { + category: 1 /* Error */, + message: "'{0}' keyword expected.", + code: 1004 + }, + _0_expected: { + category: 1 /* Error */, + message: "'{0}' expected.", + code: 1005 + }, + Identifier_expected__0__is_a_keyword: { + category: 1 /* Error */, + message: "Identifier expected; '{0}' is a keyword.", + code: 1006 + }, + Automatic_semicolon_insertion_not_allowed: { + category: 1 /* Error */, + message: "Automatic semicolon insertion not allowed.", + code: 1007 + }, + Unexpected_token__0_expected: { + category: 1 /* Error */, + message: "Unexpected token; '{0}' expected.", + code: 1008 + }, + Trailing_separator_not_allowed: { + category: 1 /* Error */, + message: "Trailing separator not allowed.", + code: 1009 + }, + _StarSlash__expected: { + category: 1 /* Error */, + message: "'*/' expected.", + code: 1010 + }, + _public_or_private_modifier_must_precede__static_: { + category: 1 /* Error */, + message: "'public' or 'private' modifier must precede 'static'.", + code: 1011 + }, + Unexpected_token_: { + category: 1 /* Error */, + message: "Unexpected token.", + code: 1012 + }, + A_catch_clause_variable_cannot_have_a_type_annotation: { + category: 1 /* Error */, + message: "A catch clause variable cannot have a type annotation.", + code: 1013 + }, + Rest_parameter_must_be_last_in_list: { + category: 1 /* Error */, + message: "Rest parameter must be last in list.", + code: 1014 + }, + Parameter_cannot_have_question_mark_and_initializer: { + category: 1 /* Error */, + message: "Parameter cannot have question mark and initializer.", + code: 1015 + }, + Required_parameter_cannot_follow_optional_parameter: { + category: 1 /* Error */, + message: "Required parameter cannot follow optional parameter.", + code: 1016 + }, + Index_signatures_cannot_have_rest_parameters: { + category: 1 /* Error */, + message: "Index signatures cannot have rest parameters.", + code: 1017 + }, + Index_signature_parameter_cannot_have_accessibility_modifiers: { + category: 1 /* Error */, + message: "Index signature parameter cannot have accessibility modifiers.", + code: 1018 + }, + Index_signature_parameter_cannot_have_a_question_mark: { + category: 1 /* Error */, + message: "Index signature parameter cannot have a question mark.", + code: 1019 + }, + Index_signature_parameter_cannot_have_an_initializer: { + category: 1 /* Error */, + message: "Index signature parameter cannot have an initializer.", + code: 1020 + }, + Index_signature_must_have_a_type_annotation: { + category: 1 /* Error */, + message: "Index signature must have a type annotation.", + code: 1021 + }, + Index_signature_parameter_must_have_a_type_annotation: { + category: 1 /* Error */, + message: "Index signature parameter must have a type annotation.", + code: 1022 + }, + Index_signature_parameter_type_must_be__string__or__number_: { + category: 1 /* Error */, + message: "Index signature parameter type must be 'string' or 'number'.", + code: 1023 + }, + _extends__clause_already_seen: { + category: 1 /* Error */, + message: "'extends' clause already seen.", + code: 1024 + }, + _extends__clause_must_precede__implements__clause: { + category: 1 /* Error */, + message: "'extends' clause must precede 'implements' clause.", + code: 1025 + }, + Class_can_only_extend_single_type: { + category: 1 /* Error */, + message: "Class can only extend single type.", + code: 1026 + }, + _implements__clause_already_seen: { + category: 1 /* Error */, + message: "'implements' clause already seen.", + code: 1027 + }, + Accessibility_modifier_already_seen: { + category: 1 /* Error */, + message: "Accessibility modifier already seen.", + code: 1028 + }, + _0__modifier_must_precede__1__modifier: { + category: 1 /* Error */, + message: "'{0}' modifier must precede '{1}' modifier.", + code: 1029 + }, + _0__modifier_already_seen: { + category: 1 /* Error */, + message: "'{0}' modifier already seen.", + code: 1030 + }, + _0__modifier_cannot_appear_on_a_class_element: { + category: 1 /* Error */, + message: "'{0}' modifier cannot appear on a class element.", + code: 1031 + }, + Interface_declaration_cannot_have__implements__clause: { + category: 1 /* Error */, + message: "Interface declaration cannot have 'implements' clause.", + code: 1032 + }, + _super__invocation_cannot_have_type_arguments: { + category: 1 /* Error */, + message: "'super' invocation cannot have type arguments.", + code: 1034 + }, + Non_ambient_modules_cannot_use_quoted_names: { + category: 1 /* Error */, + message: "Non ambient modules cannot use quoted names.", + code: 1035 + }, + Statements_are_not_allowed_in_ambient_contexts: { + category: 1 /* Error */, + message: "Statements are not allowed in ambient contexts.", + code: 1036 + }, + Implementations_are_not_allowed_in_ambient_contexts: { + category: 1 /* Error */, + message: "Implementations are not allowed in ambient contexts.", + code: 1037 + }, + _declare__modifier_not_allowed_for_code_already_in_an_ambient_context: { + category: 1 /* Error */, + message: "'declare' modifier not allowed for code already in an ambient context.", + code: 1038 + }, + Initializers_are_not_allowed_in_ambient_contexts: { + category: 1 /* Error */, + message: "Initializers are not allowed in ambient contexts.", + code: 1039 + }, + Overload_and_ambient_signatures_cannot_specify_parameter_properties: { + category: 1 /* Error */, + message: "Overload and ambient signatures cannot specify parameter properties.", + code: 1040 + }, + Function_implementation_expected: { + category: 1 /* Error */, + message: "Function implementation expected.", + code: 1041 + }, + Constructor_implementation_expected: { + category: 1 /* Error */, + message: "Constructor implementation expected.", + code: 1042 + }, + Function_overload_name_must_be__0_: { + category: 1 /* Error */, + message: "Function overload name must be '{0}'.", + code: 1043 + }, + _0__modifier_cannot_appear_on_a_module_element: { + category: 1 /* Error */, + message: "'{0}' modifier cannot appear on a module element.", + code: 1044 + }, + _declare__modifier_cannot_appear_on_an_interface_declaration: { + category: 1 /* Error */, + message: "'declare' modifier cannot appear on an interface declaration.", + code: 1045 + }, + _declare__modifier_required_for_top_level_element: { + category: 1 /* Error */, + message: "'declare' modifier required for top level element.", + code: 1046 + }, + Rest_parameter_cannot_be_optional: { + category: 1 /* Error */, + message: "Rest parameter cannot be optional.", + code: 1047 + }, + Rest_parameter_cannot_have_initializer: { + category: 1 /* Error */, + message: "Rest parameter cannot have initializer.", + code: 1048 + }, + _set__accessor_must_have_only_one_parameter: { + category: 1 /* Error */, + message: "'set' accessor must have one and only one parameter.", + code: 1049 + }, + _set__accessor_parameter_cannot_have_accessibility_modifier: { + category: 1 /* Error */, + message: "'set' accessor parameter cannot have accessibility modifier.", + code: 1050 + }, + _set__accessor_parameter_cannot_be_optional: { + category: 1 /* Error */, + message: "'set' accessor parameter cannot be optional.", + code: 1051 + }, + _set__accessor_parameter_cannot_have_initializer: { + category: 1 /* Error */, + message: "'set' accessor parameter cannot have initializer.", + code: 1052 + }, + _set__accessor_cannot_have_rest_parameter: { + category: 1 /* Error */, + message: "'set' accessor cannot have rest parameter.", + code: 1053 + }, + _get__accessor_cannot_have_parameters: { + category: 1 /* Error */, + message: "'get' accessor cannot have parameters.", + code: 1054 + }, + Modifiers_cannot_appear_here: { + category: 1 /* Error */, + message: "Modifiers cannot appear here.", + code: 1055 + }, + Accessors_are_only_available_when_targeting_EcmaScript5_and_higher: { + category: 1 /* Error */, + message: "Accessors are only when targeting EcmaScript5 and higher.", + code: 1056 + }, + Class_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Class name cannot be '{0}'.", + code: 1057 + }, + Interface_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Interface name cannot be '{0}'.", + code: 1058 + }, + Enum_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Enum name cannot be '{0}'.", + code: 1059 + }, + Module_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Module name cannot be '{0}'.", + code: 1060 + }, + Enum_member_must_have_initializer: { + category: 1 /* Error */, + message: "Enum member must have initializer.", + code: 1061 + }, + _module_______is_deprecated__Use__require_______instead: { + category: 0 /* Warning */, + message: "'module(...)' is deprecated. Use 'require(...)' instead.", + code: 1062 + }, + Export_assignments_cannot_be_used_in_internal_modules: { + category: 1 /* Error */, + message: "Export assignments cannot be used in internal modules.", + code: 1063 + }, + Export_assignment_not_allowed_in_module_with_exported_element: { + category: 1 /* Error */, + message: "Export assignment not allowed in module with exported element.", + code: 1064 + }, + Module_cannot_have_multiple_export_assignments: { + category: 1 /* Error */, + message: "Module cannot have multiple export assignments.", + code: 1065 + }, + Duplicate_identifier__0_: { + category: 1 /* Error */, + message: "Duplicate identifier '{0}'.", + code: 2000 + }, + The_name__0__does_not_exist_in_the_current_scope: { + category: 1 /* Error */, + message: "The name '{0}' does not exist in the current scope.", + code: 2001 + }, + The_name__0__does_not_refer_to_a_value: { + category: 1 /* Error */, + message: "The name '{0}' does not refer to a value.", + code: 2002 + }, + Keyword__super__can_only_be_used_inside_a_class_instance_method: { + category: 1 /* Error */, + message: "Keyword 'super' can only be used inside a class instance method.", + code: 2003 + }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable__property_or_indexer: { + category: 1 /* Error */, + message: "The left-hand side of an assignment expression must be a variable, property or indexer.", + code: 2004 + }, + Value_of_type__0__is_not_callable__Did_you_mean_to_include__new__: { + category: 1 /* Error */, + message: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + code: 2005 + }, + Value_of_type__0__is_not_callable: { + category: 1 /* Error */, + message: "Value of type '{0}' is not callable.", + code: 2006 + }, + Value_of_type__0__is_not_newable: { + category: 1 /* Error */, + message: "Value of type '{0}' is not newable.", + code: 2007 + }, + Value_of_type__0__is_not_indexable_by_type__1_: { + category: 1 /* Error */, + message: "Value of type '{0}' is not indexable by type '{1}'.", + code: 2008 + }, + Operator__0__cannot_be_applied_to_types__1__and__2_: { + category: 1 /* Error */, + message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + code: 2009 + }, + Operator__0__cannot_be_applied_to_types__1__and__2__3: { + category: 1 /* Error */, + message: "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}", + code: 2010 + }, + Cannot_convert__0__to__1_: { + category: 1 /* Error */, + message: "Cannot convert '{0}' to '{1}'.", + code: 2011 + }, + Cannot_convert__0__to__1__NL__2: { + category: 1 /* Error */, + message: "Cannot convert '{0}' to '{1}':{NL}{2}", + code: 2012 + }, + Expected_var__class__interface__or_module: { + category: 1 /* Error */, + message: "Expected var, class, interface, or module.", + code: 2013 + }, + Operator__0__cannot_be_applied_to_type__1_: { + category: 1 /* Error */, + message: "Operator '{0}' cannot be applied to type '{1}'.", + code: 2014 + }, + Getter__0__already_declared: { + category: 1 /* Error */, + message: "Getter '{0}' already declared.", + code: 2015 + }, + Setter__0__already_declared: { + category: 1 /* Error */, + message: "Setter '{0}' already declared.", + code: 2016 + }, + Accessor_cannot_have_type_parameters: { + category: 1 /* Error */, + message: "Accessors cannot have type parameters.", + code: 2017 + }, + Exported_class__0__extends_private_class__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' extends private class '{1}'.", + code: 2018 + }, + Exported_class__0__implements_private_interface__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' implements private interface '{1}'.", + code: 2019 + }, + Exported_interface__0__extends_private_interface__1_: { + category: 1 /* Error */, + message: "Exported interface '{0}' extends private interface '{1}'.", + code: 2020 + }, + Exported_class__0__extends_class_from_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' extends class from inaccessible module {1}.", + code: 2021 + }, + Exported_class__0__implements_interface_from_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' implements interface from inaccessible module {1}.", + code: 2022 + }, + Exported_interface__0__extends_interface_from_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported interface '{0}' extends interface from inaccessible module {1}.", + code: 2023 + }, + Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Public static property '{0}' of exported class has or is using private type '{1}'.", + code: 2024 + }, + Public_property__0__of__exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Public property '{0}' of exported class has or is using private type '{1}'.", + code: 2025 + }, + Property__0__of__exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Property '{0}' of exported interface has or is using private type '{1}'.", + code: 2026 + }, + Exported_variable__0__has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Exported variable '{0}' has or is using private type '{1}'.", + code: 2027 + }, + Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Public static property '{0}' of exported class is using inaccessible module {1}.", + code: 2028 + }, + Public_property__0__of__exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Public property '{0}' of exported class is using inaccessible module {1}.", + code: 2029 + }, + Property__0__of__exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Property '{0}' of exported interface is using inaccessible module {1}.", + code: 2030 + }, + Exported_variable__0__is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported variable '{0}' is using inaccessible module {1}.", + code: 2031 + }, + Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + code: 2032 + }, + Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + code: 2033 + }, + Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + code: 2034 + }, + Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + code: 2035 + }, + Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + code: 2036 + }, + Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + code: 2037 + }, + Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + code: 2038 + }, + Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + code: 2039 + }, + Parameter__0__of_exported_function_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of exported function has or is using private type '{1}'.", + code: 2040 + }, + Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + code: 2041 + }, + Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + code: 2042 + }, + Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + code: 2043 + }, + Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + code: 2044 + }, + Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + code: 2045 + }, + Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + code: 2046 + }, + Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + code: 2047 + }, + Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + code: 2048 + }, + Parameter__0__of_exported_function_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of exported function is using inaccessible module {1}.", + code: 2049 + }, + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public static property getter from exported class has or is using private type '{0}'.", + code: 2050 + }, + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public property getter from exported class has or is using private type '{0}'.", + code: 2051 + }, + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + code: 2052 + }, + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of call signature from exported interface has or is using private type '{0}'.", + code: 2053 + }, + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of index signature from exported interface has or is using private type '{0}'.", + code: 2054 + }, + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public static method from exported class has or is using private type '{0}'.", + code: 2055 + }, + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public method from exported class has or is using private type '{0}'.", + code: 2056 + }, + Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of method from exported interface has or is using private type '{0}'.", + code: 2057 + }, + Return_type_of_exported_function_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of exported function has or is using private type '{0}'.", + code: 2058 + }, + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public static property getter from exported class is using inaccessible module {0}.", + code: 2059 + }, + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public property getter from exported class is using inaccessible module {0}.", + code: 2060 + }, + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + code: 2061 + }, + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of call signature from exported interface is using inaccessible module {0}.", + code: 2062 + }, + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of index signature from exported interface is using inaccessible module {0}.", + code: 2063 + }, + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public static method from exported class is using inaccessible module {0}.", + code: 2064 + }, + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public method from exported class is using inaccessible module {0}.", + code: 2065 + }, + Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of method from exported interface is using inaccessible module {0}.", + code: 2066 + }, + Return_type_of_exported_function_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of exported function is using inaccessible module {0}.", + code: 2067 + }, + _new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead: { + category: 1 /* Error */, + message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + code: 2068 + }, + A_parameter_list_must_follow_a_generic_type_argument_list______expected: { + category: 1 /* Error */, + message: "A parameter list must follow a generic type argument list. '(' expected.", + code: 2069 + }, + Multiple_constructor_implementations_are_not_allowed: { + category: 1 /* Error */, + message: "Multiple constructor implementations are not allowed.", + code: 2070 + }, + Unable_to_resolve_external_module__0_: { + category: 1 /* Error */, + message: "Unable to resolve external module '{0}'.", + code: 2071 + }, + Module_cannot_be_aliased_to_a_non_module_type: { + category: 1 /* Error */, + message: "Module cannot be aliased to a non-module type.", + code: 2072 + }, + A_class_may_only_extend_another_class: { + category: 1 /* Error */, + message: "A class may only extend another class.", + code: 2073 + }, + A_class_may_only_implement_another_class_or_interface: { + category: 1 /* Error */, + message: "A class may only implement another class or interface.", + code: 2074 + }, + An_interface_may_only_extend_another_class_or_interface: { + category: 1 /* Error */, + message: "An interface may only extend another class or interface.", + code: 2075 + }, + An_interface_cannot_implement_another_type: { + category: 1 /* Error */, + message: "An interface cannot implement another type.", + code: 2076 + }, + Unable_to_resolve_type: { + category: 1 /* Error */, + message: "Unable to resolve type.", + code: 2077 + }, + Unable_to_resolve_type_of__0_: { + category: 1 /* Error */, + message: "Unable to resolve type of '{0}'.", + code: 2078 + }, + Unable_to_resolve_type_parameter_constraint: { + category: 1 /* Error */, + message: "Unable to resolve type parameter constraint.", + code: 2079 + }, + Type_parameter_constraint_cannot_be_a_primitive_type: { + category: 1 /* Error */, + message: "Type parameter constraint cannot be a primitive type.", + code: 2080 + }, + Supplied_parameters_do_not_match_any_signature_of_call_target: { + category: 1 /* Error */, + message: "Supplied parameters do not match any signature of call target.", + code: 2081 + }, + Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0: { + category: 1 /* Error */, + message: "Supplied parameters do not match any signature of call target:{NL}{0}", + code: 2082 + }, + Invalid__new__expression: { + category: 1 /* Error */, + message: "Invalid 'new' expression.", + code: 2083 + }, + Call_signatures_used_in_a__new__expression_must_have_a__void__return_type: { + category: 1 /* Error */, + message: "Call signatures used in a 'new' expression must have a 'void' return type.", + code: 2084 + }, + Could_not_select_overload_for__new__expression: { + category: 1 /* Error */, + message: "Could not select overload for 'new' expression.", + code: 2085 + }, + Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_: { + category: 1 /* Error */, + message: "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.", + code: 2086 + }, + Could_not_select_overload_for__call__expression: { + category: 1 /* Error */, + message: "Could not select overload for 'call' expression.", + code: 2087 + }, + Unable_to_invoke_type_with_no_call_signatures: { + category: 1 /* Error */, + message: "Unable to invoke type with no call signatures.", + code: 2088 + }, + Calls_to__super__are_only_valid_inside_a_class: { + category: 1 /* Error */, + message: "Calls to 'super' are only valid inside a class.", + code: 2089 + }, + Generic_type__0__requires_1_type_argument_s_: { + category: 1 /* Error */, + message: "Generic type '{0}' requires {1} type argument(s).", + code: 2090 + }, + Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_: { + category: 1 /* Error */, + message: "Type of conditional expression cannot be determined. Best common type could not be found between '{0}' and '{1}'.", + code: 2091 + }, + Type_of_array_literal_cannot_be_determined__Best_common_type_could_not_be_found_for_array_elements: { + category: 1 /* Error */, + message: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + code: 2092 + }, + Could_not_find_enclosing_symbol_for_dotted_name__0_: { + category: 1 /* Error */, + message: "Could not find enclosing symbol for dotted name '{0}'.", + code: 2093 + }, + The_property__0__does_not_exist_on_value_of_type__1__: { + category: 1 /* Error */, + message: "The property '{0}' does not exist on value of type '{1}'.", + code: 2094 + }, + Could_not_find_symbol__0_: { + category: 1 /* Error */, + message: "Could not find symbol '{0}'.", + code: 2095 + }, + _get__and__set__accessor_must_have_the_same_type: { + category: 1 /* Error */, + message: "'get' and 'set' accessor must have the same type.", + code: 2096 + }, + _this__cannot_be_referenced_in_current_location: { + category: 1 /* Error */, + message: "'this' cannot be referenced in current location.", + code: 2097 + }, + Use_of_deprecated__bool__type__Use__boolean__instead: { + category: 0 /* Warning */, + message: "Use of deprecated type 'bool'. Use 'boolean' instead.", + code: 2098 + }, + Static_methods_cannot_reference_class_type_parameters: { + category: 1 /* Error */, + message: "Static methods cannot reference class type parameters.", + code: 2099 + }, + Class__0__is_recursively_referenced_as_a_base_type_of_itself: { + category: 1 /* Error */, + message: "Class '{0}' is recursively referenced as a base type of itself.", + code: 2100 + }, + Interface__0__is_recursively_referenced_as_a_base_type_of_itself: { + category: 1 /* Error */, + message: "Interface '{0}' is recursively referenced as a base type of itself.", + code: 2101 + }, + _super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class: { + category: 1 /* Error */, + message: "'super' property access is permitted only in a constructor, instance member function, or instance member accessor of a derived class.", + code: 2102 + }, + _super__cannot_be_referenced_in_non_derived_classes: { + category: 1 /* Error */, + message: "'super' cannot be referenced in non-derived classes.", + code: 2103 + }, + A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties: { + category: 1 /* Error */, + message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + code: 2104 + }, + Constructors_for_derived_classes_must_contain_a__super__call: { + category: 1 /* Error */, + message: "Constructors for derived classes must contain a 'super' call.", + code: 2105 + }, + Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors: { + category: 1 /* Error */, + message: "Super calls are not permitted outside constructors or in local functions inside constructors.", + code: 2106 + }, + _0_1__is_inaccessible: { + category: 1 /* Error */, + message: "'{0}.{1}' is inaccessible.", + code: 2107 + }, + _this__cannot_be_referenced_within_module_bodies: { + category: 1 /* Error */, + message: "'this' cannot be referenced within module bodies.", + code: 2108 + }, + _this__must_only_be_used_inside_a_function_or_script_context: { + category: 1 /* Error */, + message: "'this' must only be used inside a function or script context.", + code: 2109 + }, + Invalid__addition__expression___types_do_not_agree: { + category: 1 /* Error */, + message: "Invalid '+' expression - types not known to support the addition operator.", + code: 2111 + }, + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type: { + category: 1 /* Error */, + message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + code: 2112 + }, + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type: { + category: 1 /* Error */, + message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + code: 2113 + }, + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type: { + category: 1 /* Error */, + message: "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.", + code: 2114 + }, + Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation: { + category: 1 /* Error */, + message: "Variable declarations for for/in expressions cannot contain a type annotation.", + code: 2115 + }, + Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_: { + category: 1 /* Error */, + message: "Variable declarations for for/in expressions must be of types 'string' or 'any'.", + code: 2116 + }, + The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter: { + category: 1 /* Error */, + message: "The right operand of a for/in expression must be of type 'any', an object type or a type parameter.", + code: 2117 + }, + The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_: { + category: 1 /* Error */, + message: "The left-hand side of an 'in' expression must be of types 'string' or 'any'.", + code: 2118 + }, + The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter: { + category: 1 /* Error */, + message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + code: 2119 + }, + The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter: { + category: 1 /* Error */, + message: "The left-hand side of an 'instanceOf' expression must be of type 'any', an object type or a type parameter.", + code: 2120 + }, + The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type: { + category: 1 /* Error */, + message: "The right-hand side of an 'instanceOf' expression must be of type 'any' or a subtype of the 'Function' interface type.", + code: 2121 + }, + Setters_cannot_return_a_value: { + category: 1 /* Error */, + message: "Setters cannot return a value.", + code: 2122 + }, + Tried_to_set_variable_type_to_module_type__0__: { + category: 1 /* Error */, + message: "Tried to set variable type to container type '{0}'.", + code: 2123 + }, + Tried_to_set_variable_type_to_uninitialized_module_type__0__: { + category: 1 /* Error */, + message: "Tried to set variable type to uninitialized module type '{0}'.", + code: 2124 + }, + Function__0__declared_a_non_void_return_type__but_has_no_return_expression: { + category: 1 /* Error */, + message: "Function {0} declared a non-void return type, but has no return expression.", + code: 2125 + }, + Getters_must_return_a_value: { + category: 1 /* Error */, + message: "Getters must return a value.", + code: 2126 + }, + Getter_and_setter_accessors_do_not_agree_in_visibility: { + category: 1 /* Error */, + message: "Getter and setter accessors do not agree in visibility.", + code: 2127 + }, + Invalid_left_hand_side_of_assignment_expression: { + category: 1 /* Error */, + message: "Invalid left-hand side of assignment expression.", + code: 2130 + }, + Function_declared_a_non_void_return_type__but_has_no_return_expression: { + category: 1 /* Error */, + message: "Function declared a non-void return type, but has no return expression.", + code: 2131 + }, + Cannot_resolve_return_type_reference: { + category: 1 /* Error */, + message: "Cannot resolve return type reference.", + code: 2132 + }, + Constructors_cannot_have_a_return_type_of__void_: { + category: 1 /* Error */, + message: "Constructors cannot have a return type of 'void'.", + code: 2133 + }, + Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_: { + category: 1 /* Error */, + message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'", + code: 2134 + }, + All_symbols_within_a__with__block_will_be_resolved_to__any__: { + category: 1 /* Error */, + message: "All symbols within a with block will be resolved to 'any'.", + code: 2135 + }, + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { + category: 1 /* Error */, + message: "Import declarations in an internal module cannot reference an external module.", + code: 2136 + }, + Class__0__declares_interface__1__but_does_not_implement_it__NL__2: { + category: 1 /* Error */, + message: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + code: 2137 + }, + Class__0__declares_class__1__but_does_not_implement_it__NL__2: { + category: 1 /* Error */, + message: "Class {0} declares class {1} as an implemented interface but does not implement it:{NL}{2}", + code: 2138 + }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer: { + category: 1 /* Error */, + message: "The operand of an increment or decrement operator must be a variable, property or indexer.", + code: 2139 + }, + _this__cannot_be_referenced_in_initializers_in_a_class_body: { + category: 1 /* Error */, + message: "'this' cannot be referenced in initializers in a class body.", + code: 2140 + }, + Class__0__cannot_extend_class__1__NL__2: { + category: 1 /* Error */, + message: "Class '{0}' cannot extend class '{1}':{NL}{2}", + code: 2141 + }, + Interface__0__cannot_extend_class__1__NL__2: { + category: 1 /* Error */, + message: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + code: 2142 + }, + Interface__0__cannot_extend_interface__1__NL__2: { + category: 1 /* Error */, + message: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + code: 2143 + }, + Duplicate_overload_signature_for__0_: { + category: 1 /* Error */, + message: "Duplicate overload signature for '{0}'.", + code: 2144 + }, + Duplicate_constructor_overload_signature: { + category: 1 /* Error */, + message: "Duplicate constructor overload signature.", + code: 2145 + }, + Duplicate_overload_call_signature: { + category: 1 /* Error */, + message: "Duplicate overload call signature.", + code: 2146 + }, + Duplicate_overload_construct_signature: { + category: 1 /* Error */, + message: "Duplicate overload construct signature.", + code: 2147 + }, + Overload_signature_is_not_compatible_with_function_definition: { + category: 1 /* Error */, + message: "Overload signature is not compatible with function definition.", + code: 2148 + }, + Overload_signature_is_not_compatible_with_function_definition__NL__0: { + category: 1 /* Error */, + message: "Overload signature is not compatible with function definition:{NL}{0}", + code: 2149 + }, + Overload_signatures_must_all_be_public_or_private: { + category: 1 /* Error */, + message: "Overload signatures must all be public or private.", + code: 2150 + }, + Overload_signatures_must_all_be_exported_or_local: { + category: 1 /* Error */, + message: "Overload signatures must all be exported or local.", + code: 2151 + }, + Overload_signatures_must_all_be_ambient_or_non_ambient: { + category: 1 /* Error */, + message: "Overload signatures must all be ambient or non-ambient.", + code: 2152 + }, + Overload_signatures_must_all_be_optional_or_required: { + category: 1 /* Error */, + message: "Overload signatures must all be optional or required.", + code: 2153 + }, + Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature: { + category: 1 /* Error */, + message: "Specialized overload signature is not subtype of any non-specialized signature.", + code: 2154 + }, + _this__cannot_be_referenced_in_constructor_arguments: { + category: 1 /* Error */, + message: "'this' cannot be referenced in constructor arguments.", + code: 2155 + }, + Static_member_cannot_be_accessed_off_an_instance_variable: { + category: 1 /* Error */, + message: "Static member cannot be accessed off an instance variable.", + code: 2156 + }, + Instance_member_cannot_be_accessed_off_a_class: { + category: 1 /* Error */, + message: "Instance member cannot be accessed off a class.", + code: 2157 + }, + Untyped_function_calls_may_not_accept_type_arguments: { + category: 1 /* Error */, + message: "Untyped function calls may not accept type arguments.", + code: 2158 + }, + Non_generic_functions_may_not_accept_type_arguments: { + category: 1 /* Error */, + message: "Non-generic functions may not accept type arguments.", + code: 2159 + }, + A_generic_type_may_not_reference_itself_with_its_own_type_parameters: { + category: 1 /* Error */, + message: "A generic type may not reference itself with a wrapped form of its own type parameters.", + code: 2160 + }, + Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___: { + category: 1 /* Error */, + message: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + code: 2161 + }, + Rest_parameters_must_be_array_types: { + category: 1 /* Error */, + message: "Rest parameters must be array types.", + code: 2162 + }, + Overload_signature_implementation_cannot_use_specialized_type: { + category: 1 /* Error */, + message: "Overload signature implementation cannot use specialized type.", + code: 2163 + }, + Export_assignments_may_only_be_used_in_External_modules: { + category: 1 /* Error */, + message: "Export assignments may only be used at the top-level of external modules", + code: 2164 + }, + Export_assignments_may_only_be_made_with_acceptable_kinds: { + category: 1 /* Error */, + message: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules", + code: 2165 + }, + Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword: { + category: 1 /* Error */, + message: "Only public instance methods of the base class are accessible via the super keyword", + code: 2166 + }, + Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__: { + category: 1 /* Error */, + message: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}'", + code: 2167 + }, + Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2: { + category: 1 /* Error */, + message: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}':{NL}{2}", + code: 2168 + }, + All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__: { + category: 1 /* Error */, + message: "All numerically named properties must be subtypes of numeric indexer type '{0}'", + code: 2169 + }, + All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1: { + category: 1 /* Error */, + message: "All numerically named properties must be subtypes of numeric indexer type '{0}':{NL}{1}", + code: 2170 + }, + All_named_properties_must_be_subtypes_of_string_indexer_type___0__: { + category: 1 /* Error */, + message: "All named properties must be subtypes of string indexer type '{0}'", + code: 2171 + }, + All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1: { + category: 1 /* Error */, + message: "All named properties must be subtypes of string indexer type '{0}':{NL}{1}", + code: 2172 + }, + Generic_type_references_must_include_all_type_arguments: { + category: 1 /* Error */, + message: "Generic type references must include all type arguments", + code: 2173 + }, + Type__0__is_missing_property__1__from_type__2_: { + category: 3 /* NoPrefix */, + message: "Type '{0}' is missing property '{1}' from type '{2}'.", + code: 4000 + }, + Types_of_property__0__of_types__1__and__2__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + code: 4001 + }, + Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3: { + category: 3 /* NoPrefix */, + message: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + code: 4002 + }, + Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_: { + category: 3 /* NoPrefix */, + message: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + code: 4003 + }, + Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_: { + category: 3 /* NoPrefix */, + message: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + code: 4004 + }, + Types__0__and__1__define_property__2__as_private: { + category: 3 /* NoPrefix */, + message: "Types '{0}' and '{1}' define property '{2}' as private.", + code: 4005 + }, + Call_signatures_of_types__0__and__1__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Call signatures of types '{0}' and '{1}' are incompatible.", + code: 4006 + }, + Call_signatures_of_types__0__and__1__are_incompatible__NL__2: { + category: 3 /* NoPrefix */, + message: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + code: 4007 + }, + Type__0__requires_a_call_signature__but_Type__1__lacks_one: { + category: 3 /* NoPrefix */, + message: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + code: 4008 + }, + Construct_signatures_of_types__0__and__1__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Construct signatures of types '{0}' and '{1}' are incompatible.", + code: 4009 + }, + Construct_signatures_of_types__0__and__1__are_incompatible__NL__2: { + category: 3 /* NoPrefix */, + message: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + code: 40010 + }, + Type__0__requires_a_construct_signature__but_Type__1__lacks_one: { + category: 3 /* NoPrefix */, + message: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + code: 4011 + }, + Index_signatures_of_types__0__and__1__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Index signatures of types '{0}' and '{1}' are incompatible.", + code: 4012 + }, + Index_signatures_of_types__0__and__1__are_incompatible__NL__2: { + category: 3 /* NoPrefix */, + message: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + code: 4013 + }, + Call_signature_expects__0__or_fewer_parameters: { + category: 3 /* NoPrefix */, + message: "Call signature expects {0} or fewer parameters.", + code: 4014 + }, + Could_not_apply_type__0__to_argument__1__which_is_of_type__2_: { + category: 3 /* NoPrefix */, + message: "Could not apply type'{0}' to argument {1} which is of type '{2}'.", + code: 4015 + }, + Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + code: 4016 + }, + Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + code: 4017 + }, + Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + code: 4018 + }, + Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + code: 4019 + }, + Types_of_static_property__0__of_class__1__and_class__2__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + code: 4020 + }, + Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3: { + category: 3 /* NoPrefix */, + message: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + code: 4021 + }, + Type_reference_cannot_refer_to_container__0_: { + category: 1 /* Error */, + message: "Type reference cannot refer to container '{0}'.", + code: 4022 + }, + Type_reference_must_refer_to_type: { + category: 1 /* Error */, + message: "Type reference cannot must refer to type.", + code: 4023 + }, + Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element: { + category: 1 /* Error */, + message: "Enums with multiple declarations must provide an initializer for the first enum element.", + code: 4024 + }, + Current_host_does_not_support__w_atch_option: { + category: 1 /* Error */, + message: "Current host does not support -w[atch] option.", + code: 5001 + }, + ECMAScript_target_version__0__not_supported___Using_default__1__code_generation: { + category: 0 /* Warning */, + message: "ECMAScript target version '{0}' not supported. Using default '{1}' code generation.", + code: 5002 + }, + Module_code_generation__0__not_supported___Using_default__1__code_generation: { + category: 0 /* Warning */, + message: "Module code generation '{0}' not supported. Using default '{1}' code generation.", + code: 5003 + }, + Could_not_find_file___0_: { + category: 1 /* Error */, + message: "Could not find file: '{0}'.", + code: 5004 + }, + Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed: { + category: 1 /* Error */, + message: "Unknown extension for file: '{0}'. Only .ts and .d.ts extensions are allowed.", + code: 5005 + }, + A_file_cannot_have_a_reference_itself: { + category: 1 /* Error */, + message: "A file cannot have a reference itself.", + code: 5006 + }, + Cannot_resolve_referenced_file___0_: { + category: 1 /* Error */, + message: "Cannot resolve referenced file: '{0}'.", + code: 5007 + }, + Cannot_resolve_imported_file___0_: { + category: 1 /* Error */, + message: "Cannot resolve imported file: '{0}'.", + code: 5008 + }, + Cannot_find_the_common_subdirectory_path_for_the_input_files: { + category: 1 /* Error */, + message: "Cannot find the common subdirectory path for the input files", + code: 5009 + }, + Cannot_compile_dynamic_modules_when_emitting_into_single_file: { + category: 1 /* Error */, + message: "Cannot compile dynamic modules when emitting into single file", + code: 5010 + }, + Emit_Error__0: { + category: 1 /* Error */, + message: "Emit Error: {0}.", + code: 5011 + } + }; + + var seenCodes = []; + for (var name in TypeScript.diagnosticMessages) { + if (TypeScript.diagnosticMessages.hasOwnProperty(name)) { + var diagnosticMessage = TypeScript.diagnosticMessages[name]; + var value = seenCodes[diagnosticMessage.code]; + if (value) { + throw new Error("Duplicate diagnostic code: " + diagnosticMessage.code); + } + + seenCodes[diagnosticMessage.code] = diagnosticMessage; + } + } +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + "." + (message ? (" " + message) : "")); + }; + + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument + "."); + }; + + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument + "."); + }; + + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + + Errors.invalidOperation = function (message) { + return new Error(message ? ("Invalid operation: " + message) : "Invalid operation."); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + + for (var i = start; i < end; i++) { + hashCode = (hashCode ^ text[i]) * Hash.FNV_PRIME; + } + + return hashCode; + }; + + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + + hash = (((hash << 5) + hash) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + + var start = 0; + var len = key.length; + + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + + hash = (((hash << 5) + hash) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeMurmur2CharArrayHashCode = function (key, start, len) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = len; + var h = (0 ^ numberOfCharsLeft); + + var index = start; + while (numberOfCharsLeft >= 2) { + var c1 = key[index]; + var c2 = key[index + 1]; + + var k = c1 | (c2 << 16); + + k *= m; + k ^= k >> r; + k *= m; + + h *= m; + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key[index]; + h *= m; + } + + h ^= h >> 13; + h *= m; + h ^= h >> 15; + + return h; + }; + + Hash.computeMurmur2StringHashCode = function (key) { + var m = 0x5bd1e995; + var r = 24; + + var start = 0; + var len = key.length; + var numberOfCharsLeft = len; + + var h = (0 ^ numberOfCharsLeft); + + var index = start; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + + var k = c1 | (c2 << 16); + + k *= m; + k ^= k >> r; + k *= m; + + h *= m; + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h *= m; + } + + h ^= h >> 13; + h *= m; + h ^= h >> 15; + + return h; + }; + + Hash.getPrime = function (min) { + for (var i = 0; i < Hash.primes.length; i++) { + var num = Hash.primes[i]; + if (num >= min) { + return num; + } + } + + throw TypeScript.Errors.notYetImplemented(); + }; + + Hash.expandPrime = function (oldSize) { + var num = oldSize << 1; + if (num > 2146435069 && 2146435069 > oldSize) { + return 2146435069; + } + return Hash.getPrime(num); + }; + + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + + Hash.primes = [ + 3, + 7, + 11, + 17, + 23, + 29, + 37, + 47, + 59, + 71, + 89, + 107, + 131, + 163, + 197, + 239, + 293, + 353, + 431, + 521, + 631, + 761, + 919, + 1103, + 1327, + 1597, + 1931, + 2333, + 2801, + 3371, + 4049, + 4861, + 5839, + 7013, + 8419, + 10103, + 12143, + 14591, + 17519, + 21023, + 25229, + 30293, + 36353, + 43627, + 52361, + 62851, + 75431, + 90523, + 108631, + 130363, + 156437, + 187751, + 225307, + 270371, + 324449, + 389357, + 467237, + 560689, + 672827, + 807403, + 968897, + 1162687, + 1395263, + 1674319, + 2009191, + 2411033, + 2893249, + 3471899, + 4166287, + 4999559, + 5999471, + 7199369 + ]; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultHashTableCapacity = 256; + + var HashTableEntry = (function () { + function HashTableEntry(Key, Value, HashCode, Next) { + this.Key = Key; + this.Value = Value; + this.HashCode = HashCode; + this.Next = Next; + } + return HashTableEntry; + })(); + + var HashTable = (function () { + function HashTable(capacity, hash, equals) { + this.hash = hash; + this.equals = equals; + this.entries = []; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.hash = hash; + this.equals = equals; + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + HashTable.prototype.set = function (key, value) { + this.addOrSet(key, value, false); + }; + + HashTable.prototype.add = function (key, value) { + this.addOrSet(key, value, true); + }; + + HashTable.prototype.containsKey = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + return entry !== null; + }; + + HashTable.prototype.get = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + + return entry === null ? null : entry.Value; + }; + + HashTable.prototype.computeHashCode = function (key) { + var hashCode = this.hash === null ? key.hashCode() : this.hash(key); + + hashCode = hashCode & 0x7FFFFFFF; + TypeScript.Debug.assert(hashCode > 0); + + return hashCode; + }; + + HashTable.prototype.addOrSet = function (key, value, throwOnExistingEntry) { + var hashCode = this.computeHashCode(key); + + var entry = this.findEntry(key, hashCode); + if (entry !== null) { + if (throwOnExistingEntry) { + throw TypeScript.Errors.argument('key', 'Key was already in table.'); + } + + entry.Key = key; + entry.Value = value; + return; + } + + return this.addEntry(key, value, hashCode); + }; + + HashTable.prototype.findEntry = function (key, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode) { + var equals = this.equals === null ? key === e.Key : this.equals(key, e.Key); + + if (equals) { + return e; + } + } + } + + return null; + }; + + HashTable.prototype.addEntry = function (key, value, hashCode) { + var index = hashCode % this.entries.length; + + var e = new HashTableEntry(key, value, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Key; + }; + + HashTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + return HashTable; + })(); + Collections.HashTable = HashTable; + + function createHashTable(capacity, hash, equals) { + if (typeof capacity === "undefined") { capacity = Collections.DefaultHashTableCapacity; } + if (typeof hash === "undefined") { hash = null; } + if (typeof equals === "undefined") { equals = null; } + return new HashTable(capacity, hash, equals); + } + Collections.createHashTable = createHashTable; + + var currentHashCode = 1; + function identityHashCode(value) { + if (value.__hash === undefined) { + value.__hash = currentHashCode; + currentHashCode++; + } + + return value.__hash; + } + Collections.identityHashCode = identityHashCode; + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Diagnostic = (function () { + function Diagnostic(fileName, start, length, diagnosticCode, arguments) { + if (typeof arguments === "undefined") { arguments = null; } + this._diagnosticCode = diagnosticCode; + this._arguments = (arguments && arguments.length > 0) ? arguments : null; + this._fileName = fileName; + this._originalStart = this._start = start; + this._length = length; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + + result.diagnosticCode = TypeScript.DiagnosticCode[this.diagnosticCode()]; + + var arguments = (this).arguments(); + if (arguments && arguments.length > 0) { + result.arguments = arguments; + } + + return result; + }; + + Diagnostic.prototype.fileName = function () { + return this._fileName; + }; + + Diagnostic.prototype.start = function () { + return this._start; + }; + + Diagnostic.prototype.length = function () { + return this._length; + }; + + Diagnostic.prototype.diagnosticCode = function () { + return this._diagnosticCode; + }; + + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + + Diagnostic.prototype.text = function () { + return TypeScript.getDiagnosticText(this._diagnosticCode, this._arguments); + }; + + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticCode, this._arguments); + }; + + Diagnostic.prototype.adjustOffset = function (pos) { + this._start = this._originalStart + pos; + }; + + Diagnostic.prototype.additionalLocations = function () { + return []; + }; + + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return diagnostic1._fileName === diagnostic2._fileName && diagnostic1._start === diagnostic2._start && diagnostic1._length === diagnostic2._length && diagnostic1._diagnosticCode === diagnostic2._diagnosticCode && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return v1 === v2; + }); + }; + return Diagnostic; + })(); + TypeScript.Diagnostic = Diagnostic; + + function getLargestIndex(diagnostic) { + var largest = -1; + var stringComponents = diagnostic.split("_"); + + for (var i = 0; i < stringComponents.length; i++) { + var val = parseInt(stringComponents[i]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + + return largest; + } + + function getDiagnosticInfoFromCode(diagnosticCode) { + var diagnosticName = TypeScript.DiagnosticCode[diagnosticCode]; + return TypeScript.diagnosticMessages[diagnosticName]; + } + TypeScript.getDiagnosticInfoFromCode = getDiagnosticInfoFromCode; + + function getDiagnosticText(diagnosticCode, args) { + var diagnosticName = TypeScript.DiagnosticCode[diagnosticCode]; + + var diagnostic = TypeScript.diagnosticMessages[diagnosticName]; + + var actualCount = args ? args.length : 0; + if (!diagnostic) { + throw new Error("Invalid diagnostic"); + } else { + var expectedCount = 1 + getLargestIndex(diagnosticName); + + if (expectedCount !== actualCount) { + throw new Error("Expected " + expectedCount + " arguments to diagnostic, got " + actualCount + " instead"); + } + } + + var diagnosticMessageText = diagnostic.message.replace(/{({(\d+)})?TB}/g, function (match, p1, num) { + var tabChar = "\t"; + var result = tabChar; + if (num && args[num]) { + for (var i = 1; i < args[num]; i++) { + result += tabChar; + } + } + + return result; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return "\r\n"; + }); + + return diagnosticMessageText; + } + TypeScript.getDiagnosticText = getDiagnosticText; + + function getDiagnosticMessage(diagnosticCode, args) { + var diagnostic = getDiagnosticInfoFromCode(diagnosticCode); + var diagnosticMessageText = getDiagnosticText(diagnosticCode, args); + + var message; + if (diagnostic.category === 1 /* Error */) { + message = getDiagnosticText(0 /* error_TS_0__1 */, [diagnostic.code, diagnosticMessageText]); + } else if (diagnostic.category === 0 /* Warning */) { + message = getDiagnosticText(1 /* warning_TS_0__1 */, [diagnostic.code, diagnosticMessageText]); + } else { + message = diagnosticMessageText; + } + + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var ByteOrderMark; +(function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; +})(ByteOrderMark || (ByteOrderMark = {})); + +var FileInformation = (function () { + function FileInformation(contents, byteOrderMark) { + this._contents = contents; + this._byteOrderMark = byteOrderMark; + } + FileInformation.prototype.contents = function () { + return this._contents; + }; + + FileInformation.prototype.byteOrderMark = function () { + return this._byteOrderMark; + }; + return FileInformation; +})(); + +var Environment = (function () { + function getWindowsScriptHostEnvironment() { + try { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + } catch (e) { + return null; + } + + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + currentDirectory: function () { + return (WScript).CreateObject("WScript.Shell").CurrentDirectory; + }, + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + + streamObj.Charset = 'x-ansi'; + + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + + streamObj.Position = 0; + + var byteOrderMark = 0 /* None */; + + if (bomChar.charCodeAt(0) === 0xFE && bomChar.charCodeAt(1) === 0xFF) { + streamObj.Charset = 'unicode'; + byteOrderMark = 2 /* Utf16BigEndian */; + } else if (bomChar.charCodeAt(0) === 0xFF && bomChar.charCodeAt(1) === 0xFE) { + streamObj.Charset = 'unicode'; + byteOrderMark = 3 /* Utf16LittleEndian */; + } else if (bomChar.charCodeAt(0) === 0xEF && bomChar.charCodeAt(1) === 0xBB) { + streamObj.Charset = 'utf-8'; + byteOrderMark = 1 /* Utf8 */; + } else { + streamObj.Charset = 'utf-8'; + } + + var contents = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return new FileInformation(contents, byteOrderMark); + } catch (err) { + throw new Error("Error reading file \"" + path + "\": " + err.message); + } + }, + writeFile: function (path, contents, writeByteOrderMark) { + var textStream = getStreamObject(); + textStream.Charset = 'utf-8'; + textStream.Open(); + textStream.WriteText(contents, 0); + + if (!writeByteOrderMark) { + textStream.Position = 3; + } else { + textStream.Position = 0; + } + + var fileStream = getStreamObject(); + fileStream.Type = 1; + fileStream.Open(); + + textStream.CopyTo(fileStream); + + fileStream.Flush(); + fileStream.SaveToFile(path, 2); + fileStream.Close(); + + textStream.Flush(); + textStream.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + deleteFile: function (path) { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + listFiles: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "\\" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "\\" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + arguments: args, + standardOut: WScript.StdOut + }; + } + ; + + function getNodeEnvironment() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + currentDirectory: function () { + return (process).cwd(); + }, + readFile: function (file) { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] === 0xFF) { + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return new FileInformation(buffer.toString("ucs2", 2), 2 /* Utf16BigEndian */); + } + break; + case 0xFF: + if (buffer[1] === 0xFE) { + return new FileInformation(buffer.toString("ucs2", 2), 3 /* Utf16LittleEndian */); + } + break; + case 0xEF: + if (buffer[1] === 0xBB) { + return new FileInformation(buffer.toString("utf8", 3), 1 /* Utf8 */); + } + } + + return new FileInformation(buffer.toString("utf8", 0), 0 /* None */); + }, + writeFile: function (path, contents, writeByteOrderMark) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + throw "\"" + path + "\" exists but isn't a directory."; + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + mkdirRecursiveSync(_path.dirname(path)); + + if (writeByteOrderMark) { + contents = '\uFEFF' + contents; + } + _fs.writeFileSync(path, contents, "utf8"); + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + listFiles: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder) { + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "\\" + files[i]); + if (options.recursive && stat.isDirectory()) { + paths = paths.concat(filesInFolder(folder + "\\" + files[i])); + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "\\" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path); + }, + arguments: process.argv.slice(2), + standardOut: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWindowsScriptHostEnvironment(); + } else if (typeof module !== 'undefined' && module.exports) { + return getNodeEnvironment(); + } else { + return null; + } +})(); +var TypeScript; +(function (TypeScript) { + var IntegerUtilities = (function () { + function IntegerUtilities() { + } + IntegerUtilities.integerDivide = function (numerator, denominator) { + return (numerator / denominator) >> 0; + }; + + IntegerUtilities.integerMultiplyLow32Bits = function (n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + }; + + IntegerUtilities.integerMultiplyHigh32Bits = function (n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultHigh32 = n1High16 * n2High16 + ((((n1Low16 * n2Low16) >>> 17) + n1Low16 * n2High16) >>> 15); + return resultHigh32; + }; + return IntegerUtilities; + })(); + TypeScript.IntegerUtilities = IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MathPrototype = (function () { + function MathPrototype() { + } + MathPrototype.max = function (a, b) { + return a >= b ? a : b; + }; + + MathPrototype.min = function (a, b) { + return a <= b ? a : b; + }; + return MathPrototype; + })(); + TypeScript.MathPrototype = MathPrototype; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultStringTableCapacity = 256; + + var StringTableEntry = (function () { + function StringTableEntry(Text, HashCode, Next) { + this.Text = Text; + this.HashCode = HashCode; + this.Next = Next; + } + return StringTableEntry; + })(); + + var StringTable = (function () { + function StringTable(capacity) { + this.entries = []; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + StringTable.prototype.addCharArray = function (key, start, len) { + var hashCode = TypeScript.Hash.computeSimple31BitCharArrayHashCode(key, start, len) & 0x7FFFFFFF; + + var entry = this.findCharArrayEntry(key, start, len, hashCode); + if (entry !== null) { + return entry.Text; + } + + var slice = key.slice(start, start + len); + return this.addEntry(TypeScript.StringUtilities.fromCharCodeArray(slice), hashCode); + }; + + StringTable.prototype.findCharArrayEntry = function (key, start, len, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && StringTable.textCharArrayEquals(e.Text, key, start, len)) { + return e; + } + } + + return null; + }; + + StringTable.prototype.addEntry = function (text, hashCode) { + var index = hashCode % this.entries.length; + + var e = new StringTableEntry(text, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Text; + }; + + StringTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + + StringTable.textCharArrayEquals = function (text, array, start, length) { + if (text.length !== length) { + return false; + } + + var s = start; + for (var i = 0; i < length; i++) { + if (text.charCodeAt(i) !== array[s]) { + return false; + } + + s++; + } + + return true; + }; + return StringTable; + })(); + Collections.StringTable = StringTable; + + Collections.DefaultStringTable = new StringTable(Collections.DefaultStringTableCapacity); + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + + StringUtilities.fromCharCodeArray = function (array) { + return String.fromCharCode.apply(null, array); + }; + + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + + StringUtilities.copyTo = function (source, sourceIndex, destination, destinationIndex, count) { + for (var i = 0; i < count; i++) { + destination[destinationIndex + i] = source.charCodeAt(sourceIndex + i); + } + }; + + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + + StringUtilities.stringEquals = function (val1, val2) { + return val1 === val2; + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var global = Function("return this").call(null); + +var TypeScript; +(function (TypeScript) { + var Clock; + (function (Clock) { + Clock.now; + Clock.resolution; + + if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { + global['WScript'].InitializeProjection(); + + Clock.now = function () { + return TestUtilities.QueryPerformanceCounter(); + }; + + Clock.resolution = TestUtilities.QueryPerformanceFrequency(); + } else { + Clock.now = function () { + return Date.now(); + }; + + Clock.resolution = 1000; + } + })(Clock || (Clock = {})); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = Clock.now(); + }; + + Timer.prototype.end = function () { + this.time = (Clock.now() - this.startTime); + }; + return Timer; + })(); + TypeScript.Timer = Timer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + + StringScriptSnapshot.prototype.getLineStartPositions = function () { + return TypeScript.TextUtilities.parseLineStarts(TypeScript.SimpleText.fromString(this.text)); + }; + + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_lineStarts, length) { + this._lineStarts = _lineStarts; + this.length = length; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this._lineStarts, length: this.length }; + }; + + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { + return v1 === v2; + }); + }; + + LineMap.prototype.lineStarts = function () { + return this._lineStarts; + }; + + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + + LineMap.fromSimpleText = function (text) { + var lineStarts = TypeScript.TextUtilities.parseLineStarts(text); + + return new LineMap(lineStarts, text.length()); + }; + + LineMap.fromScriptSnapshot = function (scriptSnapshot) { + return new LineMap(scriptSnapshot.getLineStartPositions(), scriptSnapshot.getLength()); + }; + + LineMap.fromString = function (text) { + return LineMap.fromSimpleText(TypeScript.SimpleText.fromString(text)); + }; + LineMap.empty = new LineMap([0], 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + (function (TextFactory) { + function getStartAndLengthOfLineBreakEndingAt(text, index, info) { + var c = text.charCodeAt(index); + if (c === 10 /* lineFeed */) { + if (index > 0 && text.charCodeAt(index - 1) === 13 /* carriageReturn */) { + info.startPosition = index - 1; + info.length = 2; + } else { + info.startPosition = index; + info.length = 1; + } + } else if (TypeScript.TextUtilities.isAnyLineBreakCharacter(c)) { + info.startPosition = index; + info.length = 1; + } else { + info.startPosition = index + 1; + info.length = 0; + } + } + + var LinebreakInfo = (function () { + function LinebreakInfo(startPosition, length) { + this.startPosition = startPosition; + this.length = length; + } + return LinebreakInfo; + })(); + + var TextLine = (function () { + function TextLine(text, body, lineBreakLength, lineNumber) { + this._text = null; + this._textSpan = null; + TypeScript.Contract.throwIfNull(text); + TypeScript.Contract.throwIfFalse(lineBreakLength >= 0); + TypeScript.Contract.requires(lineNumber >= 0); + this._text = text; + this._textSpan = body; + this._lineBreakLength = lineBreakLength; + this._lineNumber = lineNumber; + } + TextLine.prototype.start = function () { + return this._textSpan.start(); + }; + + TextLine.prototype.end = function () { + return this._textSpan.end(); + }; + + TextLine.prototype.endIncludingLineBreak = function () { + return this.end() + this._lineBreakLength; + }; + + TextLine.prototype.extent = function () { + return this._textSpan; + }; + + TextLine.prototype.extentIncludingLineBreak = function () { + return TypeScript.TextSpan.fromBounds(this.start(), this.endIncludingLineBreak()); + }; + + TextLine.prototype.toString = function () { + return this._text.toString(this._textSpan); + }; + + TextLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + return TextLine; + })(); + + var TextBase = (function () { + function TextBase() { + this.lazyLineStarts = null; + this.linebreakInfo = new LinebreakInfo(0, 0); + this.lastLineFoundForPosition = null; + } + TextBase.prototype.length = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.charCodeAt = function (position) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + TextBase.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this, span); + }; + + TextBase.prototype.substr = function (start, length, intern) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + TextBase.prototype.lines = function () { + var lines = []; + + var length = this.lineCount(); + for (var i = 0; i < length; ++i) { + lines[i] = this.getLineFromLineNumber(i); + } + + return lines; + }; + + TextBase.prototype.lineMap = function () { + return new TypeScript.LineMap(this.lineStarts(), this.length()); + }; + + TextBase.prototype.lineStarts = function () { + if (this.lazyLineStarts === null) { + this.lazyLineStarts = TypeScript.TextUtilities.parseLineStarts(this); + } + + return this.lazyLineStarts; + }; + + TextBase.prototype.getLineFromLineNumber = function (lineNumber) { + var lineStarts = this.lineStarts(); + + if (lineNumber < 0 || lineNumber >= lineStarts.length) { + throw TypeScript.Errors.argumentOutOfRange("lineNumber"); + } + + var first = lineStarts[lineNumber]; + if (lineNumber === lineStarts.length - 1) { + return new TextLine(this, new TypeScript.TextSpan(first, this.length() - first), 0, lineNumber); + } else { + getStartAndLengthOfLineBreakEndingAt(this, lineStarts[lineNumber + 1] - 1, this.linebreakInfo); + return new TextLine(this, new TypeScript.TextSpan(first, this.linebreakInfo.startPosition - first), this.linebreakInfo.length, lineNumber); + } + }; + + TextBase.prototype.getLineFromPosition = function (position) { + var lastFound = this.lastLineFoundForPosition; + if (lastFound !== null && lastFound.start() <= position && lastFound.endIncludingLineBreak() > position) { + return lastFound; + } + + var lineNumber = this.getLineNumberFromPosition(position); + + var result = this.getLineFromLineNumber(lineNumber); + this.lastLineFoundForPosition = result; + return result; + }; + + TextBase.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length()) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + TextBase.prototype.getLinePosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + return TextBase; + })(); + + var SubText = (function (_super) { + __extends(SubText, _super); + function SubText(text, span) { + _super.call(this); + + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SubText.prototype.length = function () { + return this.span.length(); + }; + + SubText.prototype.charCodeAt = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.text.charCodeAt(this.span.start() + position); + }; + + SubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + return SubText; + })(TextBase); + + var StringText = (function (_super) { + __extends(StringText, _super); + function StringText(data) { + _super.call(this); + this.source = null; + + if (data === null) { + throw TypeScript.Errors.argumentNull("data"); + } + + this.source = data; + } + StringText.prototype.length = function () { + return this.source.length; + }; + + StringText.prototype.charCodeAt = function (position) { + if (position < 0 || position >= this.source.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.source.charCodeAt(position); + }; + + StringText.prototype.substr = function (start, length, intern) { + return this.source.substr(start, length); + }; + + StringText.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + if (span === null) { + span = new TypeScript.TextSpan(0, this.length()); + } + + this.checkSubSpan(span); + + if (span.start() === 0 && span.length() === this.length()) { + return this.source; + } + + return this.source.substr(span.start(), span.length()); + }; + + StringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.source, sourceIndex, destination, destinationIndex, count); + }; + return StringText; + })(TextBase); + + function createText(value) { + return new StringText(value); + } + TextFactory.createText = createText; + })(TypeScript.TextFactory || (TypeScript.TextFactory = {})); + var TextFactory = TypeScript.TextFactory; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleSubText = (function () { + function SimpleSubText(text, span) { + this.text = null; + this.span = null; + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SimpleSubText.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + SimpleSubText.prototype.checkSubPosition = function (position) { + if (position < 0 || position >= this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + }; + + SimpleSubText.prototype.length = function () { + return this.span.length(); + }; + + SimpleSubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SimpleSubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SimpleSubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SimpleSubText.prototype.substr = function (start, length, intern) { + var span = this.getCompositeSpan(start, length); + return this.text.substr(span.start(), span.length(), intern); + }; + + SimpleSubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SimpleSubText.prototype.charCodeAt = function (index) { + this.checkSubPosition(index); + return this.text.charCodeAt(this.span.start() + index); + }; + + SimpleSubText.prototype.lineMap = function () { + return TypeScript.LineMap.fromSimpleText(this); + }; + return SimpleSubText; + })(); + + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + + SimpleStringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.value, sourceIndex, destination, destinationIndex, count); + }; + + SimpleStringText.prototype.substr = function (start, length, intern) { + if (intern) { + var array = length <= SimpleStringText.charArray.length ? SimpleStringText.charArray : TypeScript.ArrayUtilities.createArray(length, 0); + this.copyTo(start, array, 0, length); + return TypeScript.Collections.DefaultStringTable.addCharArray(array, 0, length); + } + + return this.value.substr(start, length); + }; + + SimpleStringText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + + SimpleStringText.prototype.lineMap = function () { + return TypeScript.LineMap.fromSimpleText(this); + }; + SimpleStringText.charArray = TypeScript.ArrayUtilities.createArray(1024, 0); + return SimpleStringText; + })(); + + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + + SimpleScriptSnapshotText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var text = this.scriptSnapshot.getText(sourceIndex, sourceIndex + count); + TypeScript.StringUtilities.copyTo(text, 0, destination, destinationIndex, count); + }; + + SimpleScriptSnapshotText.prototype.substr = function (start, length, intern) { + return this.scriptSnapshot.getText(start, start + length); + }; + + SimpleScriptSnapshotText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleScriptSnapshotText.prototype.lineMap = function () { + var lineStartPositions = this.scriptSnapshot.getLineStartPositions(); + return new TypeScript.LineMap(lineStartPositions, this.length()); + }; + return SimpleScriptSnapshotText; + })(); + + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length(); + + if (0 === length) { + var result = []; + result.push(0); + return result; + } + + var position = 0; + var index = 0; + var arrayBuilder = []; + var lineNumber = 0; + + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + + if (0 === lineBreakLength) { + index++; + } else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + + arrayBuilder.push(position); + + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length()) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } else if (isAnyLineBreakCharacter(c)) { + return 1; + } else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + + if (start + length < start) { + throw new Error("length"); + } + + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + + TextSpan.prototype.length = function () { + return this._length; + }; + + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + return overlapStart < overlapEnd; + }; + + TextSpan.prototype.overlap = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + + return null; + }; + + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + + TextSpan.prototype.intersection = function (span) { + var intersectStart = TypeScript.MathPrototype.max(this._start, span._start); + var intersectEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + + return null; + }; + + TextSpan.fromBounds = function (start, end) { + TypeScript.Contract.requires(start >= 0); + TypeScript.Contract.requires(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + + TextChangeRange.collapseChangesFromSingleVersion = function (changes) { + var diff = 0; + var start = 1073741823 /* Max31BitInteger */; + var end = 0; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + diff += change.newLength() - change.span().length(); + + if (change.span().start() < start) { + start = change.span().start(); + } + + if (change.span().end() > end) { + end = change.span().end(); + } + } + + if (start > end) { + return null; + } + + var combined = TypeScript.TextSpan.fromBounds(start, end); + var newLen = combined.length() + diff; + + return new TextChangeRange(combined, newLen); + }; + + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + + if (changes.length === 1) { + return changes[0]; + } + + var change0 = changes[0]; + + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + + oldStartN = TypeScript.MathPrototype.min(oldStart1, oldStart2); + oldEndN = TypeScript.MathPrototype.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = TypeScript.MathPrototype.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CharacterInfo = (function () { + function CharacterInfo() { + } + CharacterInfo.isDecimalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + }; + + CharacterInfo.isHexDigit = function (c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + }; + + CharacterInfo.hexValue = function (c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + }; + + CharacterInfo.isWhitespace = function (ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + + return false; + }; + + CharacterInfo.isLineTerminator = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + + return false; + }; + return CharacterInfo; + })(); + TypeScript.CharacterInfo = CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["TriviaNewLineMask"] = 0x00000001] = "TriviaNewLineMask"; + SyntaxConstants[SyntaxConstants["TriviaCommentMask"] = 0x00000002] = "TriviaCommentMask"; + SyntaxConstants[SyntaxConstants["TriviaFullWidthShift"] = 2] = "TriviaFullWidthShift"; + + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; +})(); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfToken(token, syntaxInformationMap, options) { + return columnForStartOfToken(token, syntaxInformationMap, options) + token.width(); + } + Indentation.columnForEndOfToken = columnForEndOfToken; + + function columnForStartOfToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + var current = token; + while (current !== firstTokenInLine) { + current = syntaxInformationMap.previousToken(current); + + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } else { + leadingTextInReverse.push(current.fullText()); + } + } + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfToken = columnForStartOfToken; + + function columnForStartOfFirstTokenInLineContainingToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingToken = columnForStartOfFirstTokenInLineContainingToken; + + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + + if (lineSegments.length > 0) { + break; + } + } + + leadingTextInReverse.push(trivia.fullText()); + } + } + + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + + return column; + } + + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } else { + column++; + } + } + + return column; + } + + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = TypeScript.MathPrototype.max(0, column); + + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + + function indentationTrivia(column, options) { + return TypeScript.Syntax.whitespace(this.indentationString(column, options)); + } + Indentation.indentationTrivia = indentationTrivia; + + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(TypeScript.LanguageVersion || (TypeScript.LanguageVersion = {})); + var LanguageVersion = TypeScript.LanguageVersion; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ParseOptions = (function () { + function ParseOptions(allowAutomaticSemicolonInsertion, allowModuleKeywordInExternalModuleReference) { + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + this._allowModuleKeywordInExternalModuleReference = allowModuleKeywordInExternalModuleReference; + } + ParseOptions.prototype.toJSON = function (key) { + return { + allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion, + allowModuleKeywordInExternalModuleReference: this._allowModuleKeywordInExternalModuleReference + }; + }; + + ParseOptions.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + + ParseOptions.prototype.allowModuleKeywordInExternalModuleReference = function () { + return this._allowModuleKeywordInExternalModuleReference; + }; + return ParseOptions; + })(); + TypeScript.ParseOptions = ParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionedElement = (function () { + function PositionedElement(parent, element, fullStart) { + this._parent = parent; + this._element = element; + this._fullStart = fullStart; + } + PositionedElement.create = function (parent, element, fullStart) { + if (element === null) { + return null; + } + + if (element.isNode()) { + return new PositionedNode(parent, element, fullStart); + } else if (element.isToken()) { + return new PositionedToken(parent, element, fullStart); + } else if (element.isList()) { + return new PositionedList(parent, element, fullStart); + } else if (element.isSeparatedList()) { + return new PositionedSeparatedList(parent, element, fullStart); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + PositionedElement.prototype.parent = function () { + return this._parent; + }; + + PositionedElement.prototype.parentElement = function () { + return this._parent && this._parent._element; + }; + + PositionedElement.prototype.element = function () { + return this._element; + }; + + PositionedElement.prototype.kind = function () { + return this.element().kind(); + }; + + PositionedElement.prototype.childIndex = function (child) { + return TypeScript.Syntax.childIndex(this.element(), child); + }; + + PositionedElement.prototype.childCount = function () { + return this.element().childCount(); + }; + + PositionedElement.prototype.childAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + return PositionedElement.create(this, this.element().childAt(index), this.fullStart() + offset); + }; + + PositionedElement.prototype.childStart = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEnd = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.childStartAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEndAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.getPositionedChild = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return PositionedElement.create(this, child, this.fullStart() + offset); + }; + + PositionedElement.prototype.fullStart = function () { + return this._fullStart; + }; + + PositionedElement.prototype.fullEnd = function () { + return this.fullStart() + this.element().fullWidth(); + }; + + PositionedElement.prototype.fullWidth = function () { + return this.element().fullWidth(); + }; + + PositionedElement.prototype.start = function () { + return this.fullStart() + this.element().leadingTriviaWidth(); + }; + + PositionedElement.prototype.end = function () { + return this.fullStart() + this.element().leadingTriviaWidth() + this.element().width(); + }; + + PositionedElement.prototype.root = function () { + var current = this; + while (current.parent() !== null) { + current = current.parent(); + } + + return current; + }; + + PositionedElement.prototype.containingNode = function () { + var current = this.parent(); + + while (current !== null && !current.element().isNode()) { + current = current.parent(); + } + + return current; + }; + return PositionedElement; + })(); + TypeScript.PositionedElement = PositionedElement; + + var PositionedNodeOrToken = (function (_super) { + __extends(PositionedNodeOrToken, _super); + function PositionedNodeOrToken(parent, nodeOrToken, fullStart) { + _super.call(this, parent, nodeOrToken, fullStart); + } + PositionedNodeOrToken.prototype.nodeOrToken = function () { + return this.element(); + }; + return PositionedNodeOrToken; + })(PositionedElement); + TypeScript.PositionedNodeOrToken = PositionedNodeOrToken; + + var PositionedNode = (function (_super) { + __extends(PositionedNode, _super); + function PositionedNode(parent, node, fullStart) { + _super.call(this, parent, node, fullStart); + } + PositionedNode.prototype.node = function () { + return this.element(); + }; + return PositionedNode; + })(PositionedNodeOrToken); + TypeScript.PositionedNode = PositionedNode; + + var PositionedToken = (function (_super) { + __extends(PositionedToken, _super); + function PositionedToken(parent, token, fullStart) { + _super.call(this, parent, token, fullStart); + } + PositionedToken.prototype.token = function () { + return this.element(); + }; + + PositionedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var triviaList = this.token().leadingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = this.start(); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), currentTriviaEndPosition - trivia.fullWidth()); + } + + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + + var start = this.fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + var triviaList = this.token().trailingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var fullStart = this.end(); + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), fullStart); + } + + fullStart += trivia.fullWidth(); + } + } + + return this.root().node().findToken(this.fullEnd(), includeSkippedTokens); + }; + return PositionedToken; + })(PositionedNodeOrToken); + TypeScript.PositionedToken = PositionedToken; + + var PositionedList = (function (_super) { + __extends(PositionedList, _super); + function PositionedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedList.prototype.list = function () { + return this.element(); + }; + return PositionedList; + })(PositionedElement); + TypeScript.PositionedList = PositionedList; + + var PositionedSeparatedList = (function (_super) { + __extends(PositionedSeparatedList, _super); + function PositionedSeparatedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedSeparatedList.prototype.list = function () { + return this.element(); + }; + return PositionedSeparatedList; + })(PositionedElement); + TypeScript.PositionedSeparatedList = PositionedSeparatedList; + + var PositionedSkippedToken = (function (_super) { + __extends(PositionedSkippedToken, _super); + function PositionedSkippedToken(parentToken, token, fullStart) { + _super.call(this, parentToken.parent(), token, fullStart); + this._parentToken = parentToken; + } + PositionedSkippedToken.prototype.parentToken = function () { + return this._parentToken; + }; + + PositionedSkippedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var start = this.fullStart(); + + if (includeSkippedTokens) { + var previousToken; + + if (start >= this.parentToken().end()) { + previousToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + + return this.parentToken(); + } else { + previousToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + } + } + + var start = this.parentToken().fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedSkippedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + if (includeSkippedTokens) { + var end = this.end(); + var nextToken; + + if (end <= this.parentToken().start()) { + nextToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + + return this.parentToken(); + } else { + nextToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + } + } + + return this.root().node().findToken(this.parentToken().fullEnd(), includeSkippedTokens); + }; + return PositionedSkippedToken; + })(PositionedToken); + TypeScript.PositionedSkippedToken = PositionedSkippedToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Scanner = (function () { + function Scanner(fileName, text, languageVersion, window) { + if (typeof window === "undefined") { window = TypeScript.ArrayUtilities.createArray(2048, 0); } + Scanner.initializeStaticData(); + + this.slidingWindow = new TypeScript.SlidingWindow(this, window, 0, text.length()); + this.fileName = fileName; + this.text = text; + this._languageVersion = languageVersion; + } + Scanner.initializeStaticData = function () { + if (Scanner.isKeywordStartCharacter.length === 0) { + Scanner.isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + Scanner.isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + Scanner.isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + Scanner.isNumericLiteralStart = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if (character >= 97 /* a */ && character <= 122 /* z */) { + Scanner.isIdentifierStartCharacter[character] = true; + Scanner.isIdentifierPartCharacter[character] = true; + } else if ((character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + Scanner.isIdentifierStartCharacter[character] = true; + Scanner.isIdentifierPartCharacter[character] = true; + } else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + Scanner.isIdentifierPartCharacter[character] = true; + Scanner.isNumericLiteralStart[character] = true; + } + } + + Scanner.isNumericLiteralStart[46 /* dot */] = true; + + for (var keywordKind = TypeScript.SyntaxKind.FirstKeyword; keywordKind <= TypeScript.SyntaxKind.LastKeyword; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + Scanner.isKeywordStartCharacter[keyword.charCodeAt(0)] = true; + } + } + }; + + Scanner.prototype.languageVersion = function () { + return this._languageVersion; + }; + + Scanner.prototype.fetchMoreItems = function (argument, sourceIndex, window, destinationIndex, spaceAvailable) { + var charactersRemaining = this.text.length() - sourceIndex; + var amountToRead = TypeScript.MathPrototype.min(charactersRemaining, spaceAvailable); + this.text.copyTo(sourceIndex, window, destinationIndex, amountToRead); + return amountToRead; + }; + + Scanner.prototype.currentCharCode = function () { + return this.slidingWindow.currentItem(null); + }; + + Scanner.prototype.absoluteIndex = function () { + return this.slidingWindow.absoluteIndex(); + }; + + Scanner.prototype.setAbsoluteIndex = function (index) { + this.slidingWindow.setAbsoluteIndex(index); + }; + + Scanner.prototype.scan = function (diagnostics, allowRegularExpression) { + var diagnosticsLength = diagnostics.length; + var fullStart = this.slidingWindow.absoluteIndex(); + var leadingTriviaInfo = this.scanTriviaInfo(diagnostics, false); + + var start = this.slidingWindow.absoluteIndex(); + var kind = this.scanSyntaxToken(diagnostics, allowRegularExpression); + var end = this.slidingWindow.absoluteIndex(); + + var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo); + + return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; + }; + + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo) { + if (kind >= TypeScript.SyntaxKind.FirstFixedWidth) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); + } else { + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(this.text, fullStart, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo); + } else { + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } else { + var width = end - start; + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(this.text, fullStart, kind, width); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(this.text, fullStart, kind, width, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); + } + } + }; + + Scanner.scanTrivia = function (text, start, length, isTrailing) { + var scanner = new Scanner(null, text.subText(new TypeScript.TextSpan(start, length)), 1 /* EcmaScript5 */, Scanner.triviaWindow); + return scanner.scanTrivia(isTrailing); + }; + + Scanner.prototype.scanTrivia = function (isTrailing) { + var trivia = []; + + while (true) { + if (!this.slidingWindow.isAtEndOfSource()) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(this.scanWhitespaceTrivia()); + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + trivia.push(this.scanSingleLineCommentTrivia()); + continue; + } + + if (ch2 === 42 /* asterisk */) { + trivia.push(this.scanMultiLineCommentTrivia()); + continue; + } + + throw TypeScript.Errors.invalidOperation(); + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(this.scanLineTerminatorSequenceTrivia(ch)); + + if (!isTrailing) { + continue; + } + + break; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + return TypeScript.Syntax.triviaList(trivia); + } + }; + + Scanner.prototype.scanTriviaInfo = function (diagnostics, isTrailing) { + var width = 0; + var hasCommentOrNewLine = 0; + + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanSingleLineCommentTriviaLength(); + continue; + } + + if (ch2 === 42 /* asterisk */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanMultiLineCommentTriviaLength(diagnostics); + continue; + } + + break; + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + hasCommentOrNewLine |= 1 /* TriviaNewLineMask */; + width += this.scanLineTerminatorSequenceLength(ch); + + if (!isTrailing) { + continue; + } + + break; + } + + return (width << 2 /* TriviaFullWidthShift */) | hasCommentOrNewLine; + } + }; + + Scanner.prototype.isNewLineCharacter = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + }; + + Scanner.prototype.scanWhitespaceTrivia = function () { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var width = 0; + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + } + + break; + } + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.whitespace(text); + }; + + Scanner.prototype.scanSingleLineCommentTrivia = function () { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanSingleLineCommentTriviaLength(); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.singleLineComment(text); + }; + + Scanner.prototype.scanSingleLineCommentTriviaLength = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource() || this.isNewLineCharacter(this.currentCharCode())) { + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanMultiLineCommentTrivia = function () { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanMultiLineCommentTriviaLength(null); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.multiLineComment(text); + }; + + Scanner.prototype.scanMultiLineCommentTriviaLength = function (diagnostics) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource()) { + if (diagnostics !== null) { + diagnostics.push(new TypeScript.SyntaxDiagnostic(this.fileName, this.slidingWindow.absoluteIndex(), 0, 14 /* _StarSlash__expected */, null)); + } + + return width; + } + + var ch = this.currentCharCode(); + if (ch === 42 /* asterisk */ && this.slidingWindow.peekItemN(1) === 47 /* slash */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + width += 2; + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanLineTerminatorSequenceTrivia = function (ch) { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanLineTerminatorSequenceLength(ch); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.trivia(5 /* NewLineTrivia */, text); + }; + + Scanner.prototype.scanLineTerminatorSequenceLength = function (ch) { + this.slidingWindow.moveToNextItem(); + + if (ch === 13 /* carriageReturn */ && this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + return 2; + } else { + return 1; + } + }; + + Scanner.prototype.scanSyntaxToken = function (diagnostics, allowRegularExpression) { + if (this.slidingWindow.isAtEndOfSource()) { + return 10 /* EndOfFileToken */; + } + + var character = this.currentCharCode(); + + switch (character) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + return this.scanStringLiteral(diagnostics); + + case 47 /* slash */: + return this.scanSlashToken(allowRegularExpression); + + case 46 /* dot */: + return this.scanDotToken(); + + case 45 /* minus */: + return this.scanMinusToken(); + + case 33 /* exclamation */: + return this.scanExclamationToken(); + + case 61 /* equals */: + return this.scanEqualsToken(); + + case 124 /* bar */: + return this.scanBarToken(); + + case 42 /* asterisk */: + return this.scanAsteriskToken(); + + case 43 /* plus */: + return this.scanPlusToken(); + + case 37 /* percent */: + return this.scanPercentToken(); + + case 38 /* ampersand */: + return this.scanAmpersandToken(); + + case 94 /* caret */: + return this.scanCaretToken(); + + case 60 /* lessThan */: + return this.scanLessThanToken(); + + case 62 /* greaterThan */: + return this.advanceAndSetTokenKind(82 /* GreaterThanToken */); + + case 44 /* comma */: + return this.advanceAndSetTokenKind(80 /* CommaToken */); + + case 58 /* colon */: + return this.advanceAndSetTokenKind(107 /* ColonToken */); + + case 59 /* semicolon */: + return this.advanceAndSetTokenKind(79 /* SemicolonToken */); + + case 126 /* tilde */: + return this.advanceAndSetTokenKind(103 /* TildeToken */); + + case 40 /* openParen */: + return this.advanceAndSetTokenKind(73 /* OpenParenToken */); + + case 41 /* closeParen */: + return this.advanceAndSetTokenKind(74 /* CloseParenToken */); + + case 123 /* openBrace */: + return this.advanceAndSetTokenKind(71 /* OpenBraceToken */); + + case 125 /* closeBrace */: + return this.advanceAndSetTokenKind(72 /* CloseBraceToken */); + + case 91 /* openBracket */: + return this.advanceAndSetTokenKind(75 /* OpenBracketToken */); + + case 93 /* closeBracket */: + return this.advanceAndSetTokenKind(76 /* CloseBracketToken */); + + case 63 /* question */: + return this.advanceAndSetTokenKind(106 /* QuestionToken */); + } + + if (Scanner.isNumericLiteralStart[character]) { + return this.scanNumericLiteral(); + } + + if (Scanner.isIdentifierStartCharacter[character]) { + var result = this.tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + + if (this.isIdentifierStart(this.peekCharOrUnicodeEscape())) { + return this.slowScanIdentifier(diagnostics); + } + + return this.scanDefaultCharacter(character, diagnostics); + }; + + Scanner.prototype.isIdentifierStart = function (interpretedChar) { + if (Scanner.isIdentifierStartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.isIdentifierPart = function (interpretedChar) { + if (Scanner.isIdentifierPartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.tryFastScanIdentifierOrKeyword = function (firstCharacter) { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + while (true) { + var character = this.currentCharCode(); + if (Scanner.isIdentifierPartCharacter[character]) { + this.slidingWindow.moveToNextItem(); + } else if (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 0 /* None */; + } else { + var endIndex = this.slidingWindow.absoluteIndex(); + + var kind; + if (Scanner.isKeywordStartCharacter[firstCharacter]) { + var offset = startIndex - this.slidingWindow.windowAbsoluteStartIndex; + kind = TypeScript.ScannerUtilities.identifierKind(this.slidingWindow.window, offset, endIndex - startIndex); + } else { + kind = 11 /* IdentifierName */; + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return kind; + } + } + }; + + Scanner.prototype.slowScanIdentifier = function (diagnostics) { + var startIndex = this.slidingWindow.absoluteIndex(); + + do { + this.scanCharOrUnicodeEscape(diagnostics); + } while(this.isIdentifierPart(this.peekCharOrUnicodeEscape())); + + return 11 /* IdentifierName */; + }; + + Scanner.prototype.scanNumericLiteral = function () { + if (this.isHexNumericLiteral()) { + return this.scanHexNumericLiteral(); + } else { + return this.scanDecimalNumericLiteral(); + } + }; + + Scanner.prototype.scanDecimalNumericLiteral = function () { + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + if (this.currentCharCode() === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + } + + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + var ch = this.currentCharCode(); + if (ch === 101 /* e */ || ch === 69 /* E */) { + this.slidingWindow.moveToNextItem(); + + ch = this.currentCharCode(); + if (ch === 45 /* minus */ || ch === 43 /* plus */) { + if (TypeScript.CharacterInfo.isDecimalDigit(this.slidingWindow.peekItemN(1))) { + this.slidingWindow.moveToNextItem(); + } + } + } + + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.scanHexNumericLiteral = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + while (TypeScript.CharacterInfo.isHexDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.isHexNumericLiteral = function () { + if (this.currentCharCode() === 48 /* _0 */) { + var ch = this.slidingWindow.peekItemN(1); + + if (ch === 120 /* x */ || ch === 88 /* X */) { + ch = this.slidingWindow.peekItemN(2); + + return TypeScript.CharacterInfo.isHexDigit(ch); + } + } + + return false; + }; + + Scanner.prototype.advanceAndSetTokenKind = function (kind) { + this.slidingWindow.moveToNextItem(); + return kind; + }; + + Scanner.prototype.scanLessThanToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 83 /* LessThanEqualsToken */; + } else if (this.currentCharCode() === 60 /* lessThan */) { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 113 /* LessThanLessThanEqualsToken */; + } else { + return 96 /* LessThanLessThanToken */; + } + } else { + return 81 /* LessThanToken */; + } + }; + + Scanner.prototype.scanBarToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 117 /* BarEqualsToken */; + } else if (this.currentCharCode() === 124 /* bar */) { + this.slidingWindow.moveToNextItem(); + return 105 /* BarBarToken */; + } else { + return 100 /* BarToken */; + } + }; + + Scanner.prototype.scanCaretToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 118 /* CaretEqualsToken */; + } else { + return 101 /* CaretToken */; + } + }; + + Scanner.prototype.scanAmpersandToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 116 /* AmpersandEqualsToken */; + } else if (this.currentCharCode() === 38 /* ampersand */) { + this.slidingWindow.moveToNextItem(); + return 104 /* AmpersandAmpersandToken */; + } else { + return 99 /* AmpersandToken */; + } + }; + + Scanner.prototype.scanPercentToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 112 /* PercentEqualsToken */; + } else { + return 93 /* PercentToken */; + } + }; + + Scanner.prototype.scanMinusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 110 /* MinusEqualsToken */; + } else if (character === 45 /* minus */) { + this.slidingWindow.moveToNextItem(); + return 95 /* MinusMinusToken */; + } else { + return 91 /* MinusToken */; + } + }; + + Scanner.prototype.scanPlusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 109 /* PlusEqualsToken */; + } else if (character === 43 /* plus */) { + this.slidingWindow.moveToNextItem(); + return 94 /* PlusPlusToken */; + } else { + return 90 /* PlusToken */; + } + }; + + Scanner.prototype.scanAsteriskToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 111 /* AsteriskEqualsToken */; + } else { + return 92 /* AsteriskToken */; + } + }; + + Scanner.prototype.scanEqualsToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 88 /* EqualsEqualsEqualsToken */; + } else { + return 85 /* EqualsEqualsToken */; + } + } else if (character === 62 /* greaterThan */) { + this.slidingWindow.moveToNextItem(); + return 86 /* EqualsGreaterThanToken */; + } else { + return 108 /* EqualsToken */; + } + }; + + Scanner.prototype.isDotPrefixedNumericLiteral = function () { + if (this.currentCharCode() === 46 /* dot */) { + var ch = this.slidingWindow.peekItemN(1); + return TypeScript.CharacterInfo.isDecimalDigit(ch); + } + + return false; + }; + + Scanner.prototype.scanDotToken = function () { + if (this.isDotPrefixedNumericLiteral()) { + return this.scanNumericLiteral(); + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 46 /* dot */ && this.slidingWindow.peekItemN(1) === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + return 78 /* DotDotDotToken */; + } else { + return 77 /* DotToken */; + } + }; + + Scanner.prototype.scanSlashToken = function (allowRegularExpression) { + if (allowRegularExpression) { + var result = this.tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 120 /* SlashEqualsToken */; + } else { + return 119 /* SlashToken */; + } + }; + + Scanner.prototype.tryScanRegularExpressionToken = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + try { + this.slidingWindow.moveToNextItem(); + + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = this.currentCharCode(); + if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + return 0 /* None */; + } + + this.slidingWindow.moveToNextItem(); + if (inEscape) { + inEscape = false; + continue; + } + + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + + case 91 /* openBracket */: + inCharacterClass = true; + continue; + + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + + break; + + default: + continue; + } + + break; + } + + while (Scanner.isIdentifierPartCharacter[this.currentCharCode()]) { + this.slidingWindow.moveToNextItem(); + } + + return 12 /* RegularExpressionLiteral */; + } finally { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + } + }; + + Scanner.prototype.scanExclamationToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 89 /* ExclamationEqualsEqualsToken */; + } else { + return 87 /* ExclamationEqualsToken */; + } + } else { + return 102 /* ExclamationToken */; + } + }; + + Scanner.prototype.scanDefaultCharacter = function (character, diagnostics) { + var position = this.slidingWindow.absoluteIndex(); + this.slidingWindow.moveToNextItem(); + + var text = String.fromCharCode(character); + var messageText = this.getErrorMessageText(text); + diagnostics.push(new TypeScript.SyntaxDiagnostic(this.fileName, position, 1, 5 /* Unexpected_character_0 */, [messageText])); + + return 9 /* ErrorToken */; + }; + + Scanner.prototype.getErrorMessageText = function (text) { + if (text === "\\") { + return '"\\"'; + } + + return JSON.stringify(text); + }; + + Scanner.prototype.skipEscapeSequence = function (diagnostics) { + var rewindPoint = this.slidingWindow.getAndPinAbsoluteIndex(); + try { + this.slidingWindow.moveToNextItem(); + + var ch = this.currentCharCode(); + this.slidingWindow.moveToNextItem(); + switch (ch) { + case 120 /* x */: + case 117 /* u */: + this.slidingWindow.rewindToPinnedIndex(rewindPoint); + var value = this.scanUnicodeOrHexEscape(diagnostics); + return; + + case 13 /* carriageReturn */: + if (this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + } + return; + + default: + return; + } + } finally { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint); + } + }; + + Scanner.prototype.scanStringLiteral = function (diagnostics) { + var quoteCharacter = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + while (true) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + this.skipEscapeSequence(diagnostics); + } else if (ch === quoteCharacter) { + this.slidingWindow.moveToNextItem(); + break; + } else if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + diagnostics.push(new TypeScript.SyntaxDiagnostic(this.fileName, this.slidingWindow.absoluteIndex(), 1, 6 /* Missing_closing_quote_character */, null)); + break; + } else { + this.slidingWindow.moveToNextItem(); + } + } + + return 14 /* StringLiteral */; + }; + + Scanner.prototype.isUnicodeOrHexEscape = function (character) { + return this.isUnicodeEscape(character) || this.isHexEscape(character); + }; + + Scanner.prototype.isUnicodeEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.isHexEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 120 /* x */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.peekCharOrUnicodeOrHexEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeOrHexEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekCharOrUnicodeEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekUnicodeOrHexEscape = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var ch = this.scanUnicodeOrHexEscape(null); + + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return this.scanUnicodeOrHexEscape(errors); + } + } + + this.slidingWindow.moveToNextItem(); + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeOrHexEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */ || ch2 === 120 /* x */) { + return this.scanUnicodeOrHexEscape(errors); + } + } + + this.slidingWindow.moveToNextItem(); + return ch; + }; + + Scanner.prototype.scanUnicodeOrHexEscape = function (errors) { + var start = this.slidingWindow.absoluteIndex(); + var character = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + character = this.currentCharCode(); + + var intChar = 0; + this.slidingWindow.moveToNextItem(); + + var count = character === 117 /* u */ ? 4 : 2; + + for (var i = 0; i < count; i++) { + var ch2 = this.currentCharCode(); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (errors !== null) { + var end = this.slidingWindow.absoluteIndex(); + var info = this.createIllegalEscapeDiagnostic(start, end); + errors.push(info); + } + + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + this.slidingWindow.moveToNextItem(); + } + + return intChar; + }; + + Scanner.prototype.substring = function (start, end, intern) { + var length = end - start; + var offset = start - this.slidingWindow.windowAbsoluteStartIndex; + + if (intern) { + return TypeScript.Collections.DefaultStringTable.addCharArray(this.slidingWindow.window, offset, length); + } else { + return TypeScript.StringUtilities.fromCharCodeArray(this.slidingWindow.window.slice(offset, offset + length)); + } + }; + + Scanner.prototype.createIllegalEscapeDiagnostic = function (start, end) { + return new TypeScript.SyntaxDiagnostic(this.fileName, start, end - start, 4 /* Unrecognized_escape_sequence */, null); + }; + + Scanner.isValidIdentifier = function (text, languageVersion) { + var scanner = new Scanner(null, text, TypeScript.LanguageVersion, Scanner.triviaWindow); + var errors = []; + var token = scanner.scan(errors, false); + + return errors.length === 0 && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && token.width() === text.length(); + }; + Scanner.isKeywordStartCharacter = []; + Scanner.isIdentifierStartCharacter = []; + Scanner.isIdentifierPartCharacter = []; + Scanner.isNumericLiteralStart = []; + + Scanner.triviaWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + return Scanner; + })(); + TypeScript.Scanner = Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (array, startIndex, length) { + switch (length) { + case 2: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (array[startIndex + 1]) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 3: + switch (array[startIndex]) { + case 102 /* f */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 97 /* a */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 65 /* GetKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 69 /* SetKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 4: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (array[startIndex + 1]) { + case 108 /* l */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 1]) { + case 104 /* h */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 118 /* v */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */) ? 62 /* BoolKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 5: + switch (array[startIndex]) { + case 98 /* b */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 2] === 97 /* a */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 114 /* r */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 6: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (array[startIndex + 1]) { + case 119 /* w */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 99 /* c */ && array[startIndex + 5] === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 2]) { + case 97 /* a */: + return (array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 3] === 105 /* i */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 103 /* g */) ? 70 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 116 /* t */: + return (array[startIndex + 1] === 121 /* y */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 111 /* o */ && array[startIndex + 5] === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (array[startIndex + 1] === 109 /* m */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 100 /* d */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 101 /* e */) ? 66 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 109 /* m */ && array[startIndex + 3] === 98 /* b */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 114 /* r */) ? 68 /* NumberKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 7: + switch (array[startIndex]) { + case 100 /* d */: + switch (array[startIndex + 1]) { + case 101 /* e */: + switch (array[startIndex + 2]) { + case 102 /* f */: + return (array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 117 /* u */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + return (array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 64 /* DeclareKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 100 /* d */ && array[startIndex + 6] === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 99 /* c */ && array[startIndex + 3] === 107 /* k */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 118 /* v */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 116 /* t */ && array[startIndex + 6] === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 97 /* a */ && array[startIndex + 6] === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 113 /* q */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 67 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 8: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 103 /* g */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 105 /* i */ && array[startIndex + 6] === 111 /* o */ && array[startIndex + 7] === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 9: + switch (array[startIndex]) { + case 105 /* i */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 102 /* f */ && array[startIndex + 6] === 97 /* a */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 99 /* c */ && array[startIndex + 6] === 116 /* t */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 10: + switch (array[startIndex]) { + case 105 /* i */: + switch (array[startIndex + 1]) { + case 110 /* n */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 99 /* c */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 111 /* o */ && array[startIndex + 9] === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 109 /* m */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 110 /* n */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 11: + return (array[startIndex] === 99 /* c */ && array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 111 /* o */ && array[startIndex + 10] === 114 /* r */) ? 63 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySeparatedSyntaxList = (function () { + function EmptySeparatedSyntaxList() { + } + EmptySeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + EmptySeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isList = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + EmptySeparatedSyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySeparatedSyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySeparatedSyntaxList.prototype.width = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + + EmptySeparatedSyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + return EmptySeparatedSyntaxList; + })(); + + Syntax.emptySeparatedList = new EmptySeparatedSyntaxList(); + + var SingletonSeparatedSyntaxList = (function () { + function SingletonSeparatedSyntaxList(item) { + this.item = item; + } + SingletonSeparatedSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + SingletonSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + SingletonSeparatedSyntaxList.prototype.childCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + SingletonSeparatedSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + SingletonSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSeparatedSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSeparatedSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSeparatedSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSeparatedSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return (this.item).findTokenInternal(new TypeScript.PositionedSeparatedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSeparatedSyntaxList; + })(); + + var NormalSeparatedSyntaxList = (function () { + function NormalSeparatedSyntaxList(elements) { + this._data = 0; + this.elements = elements; + } + NormalSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + NormalSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + NormalSeparatedSyntaxList.prototype.toJSON = function (key) { + return this.elements; + }; + + NormalSeparatedSyntaxList.prototype.childCount = function () { + return this.elements.length; + }; + NormalSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length + 1, 2); + }; + NormalSeparatedSyntaxList.prototype.separatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length, 2); + }; + + NormalSeparatedSyntaxList.prototype.toArray = function () { + return this.elements.slice(0); + }; + + NormalSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + var result = []; + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + result.push(this.nonSeparatorAt(i)); + } + + return result; + }; + + NormalSeparatedSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[index]; + }; + + NormalSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + var value = index * 2; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.separatorAt = function (index) { + var value = index * 2 + 1; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.firstToken = function () { + var token; + for (var i = 0, n = this.elements.length; i < n; i++) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.firstToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.lastToken = function () { + var token; + for (var i = this.elements.length - 1; i >= 0; i--) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.lastToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i).isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSeparatedSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSeparatedSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + fullWidth += childWidth; + + isIncrementallyUnusable = isIncrementallyUnusable || element.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSeparatedSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedSeparatedList(parent, this, fullStart); + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + if (position < childWidth) { + return (element).findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + element.collectTextElements(elements); + } + }; + + NormalSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.elements); + } else { + array.splice.apply(array, [index, 0].concat(this.elements)); + } + }; + return NormalSeparatedSyntaxList; + })(); + + function separatedList(nodes) { + return separatedListAndValidate(nodes, false); + } + Syntax.separatedList = separatedList; + + function separatedListAndValidate(nodes, validate) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptySeparatedList; + } + + if (validate) { + for (var i = 0; i < nodes.length; i++) { + var item = nodes[i]; + + if (i % 2 === 1) { + } + } + } + + if (nodes.length === 1) { + return new SingletonSeparatedSyntaxList(nodes[0]); + } + + return new NormalSeparatedSyntaxList(nodes); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(source, window, defaultValue, sourceLength) { + if (typeof sourceLength === "undefined") { sourceLength = -1; } + this.source = source; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.windowAbsoluteEndIndex = function () { + return this.windowAbsoluteStartIndex + this.windowCount; + }; + + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + if (this.sourceLength >= 0 && this.absoluteIndex() >= this.sourceLength) { + return false; + } + + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + + var spaceAvailable = this.window.length - this.windowCount; + var amountFetched = this.source.fetchMoreItems(argument, this.windowAbsoluteEndIndex(), this.window, this.windowCount, spaceAvailable); + + this.windowCount += amountFetched; + return amountFetched > 0; + }; + + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + + var shiftCount = this.windowCount - shiftStartIndex; + + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + + this.windowAbsoluteStartIndex += shiftStartIndex; + + this.windowCount -= shiftStartIndex; + + this.currentRelativeItemIndex -= shiftStartIndex; + } else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + + return absoluteIndex; + }; + + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + + this.currentRelativeItemIndex = relativeIndex; + }; + + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex]; + }; + + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex + n]; + }; + + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.setAbsoluteIndex = function (absoluteIndex) { + if (this.absoluteIndex() === absoluteIndex) { + return; + } + + if (this._pinCount > 0) { + } + + if (absoluteIndex >= this.windowAbsoluteStartIndex && absoluteIndex < this.windowAbsoluteEndIndex()) { + this.currentRelativeItemIndex = (absoluteIndex - this.windowAbsoluteStartIndex); + } else { + this.windowAbsoluteStartIndex = absoluteIndex; + + this.windowCount = 0; + + this.currentRelativeItemIndex = 0; + } + }; + + SlidingWindow.prototype.pinCount = function () { + return this._pinCount; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Strings = (function () { + function Strings() { + } + Strings.module__class__interface__enum__import_or_statement = "module, class, interface, enum, import or statement"; + Strings.constructor__function__accessor_or_variable = "constructor, function, accessor or variable"; + Strings.statement = "statement"; + Strings.case_or_default_clause = "case or default clause"; + Strings.identifier = "identifier"; + Strings.call__construct__index__property_or_function_signature = "call, construct, index, property or function signature"; + Strings.expression = "expression"; + Strings.type_name = "type name"; + Strings.property_or_accessor = "property or accessor"; + Strings.parameter = "parameter"; + Strings.type = "type"; + Strings.type_parameter = "type parameter"; + return Strings; + })(); + TypeScript.Strings = Strings; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function emptySourceUnit() { + return TypeScript.Syntax.normalModeFactory.sourceUnit(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(10 /* EndOfFileToken */, { text: "" })); + } + Syntax.emptySourceUnit = emptySourceUnit; + + function getStandaloneExpression(positionedToken) { + var token = positionedToken.token(); + if (positionedToken !== null && positionedToken.kind() === 11 /* IdentifierName */) { + var parentPositionedNode = positionedToken.containingNode(); + var parentNode = parentPositionedNode.node(); + + if (parentNode.kind() === 122 /* QualifiedName */ && (parentNode).right === token) { + return parentPositionedNode; + } else if (parentNode.kind() === 211 /* MemberAccessExpression */ && (parentNode).name === token) { + return parentPositionedNode; + } + } + + return positionedToken; + } + Syntax.getStandaloneExpression = getStandaloneExpression; + + function isInModuleOrTypeContext(positionedToken) { + if (positionedToken !== null) { + var positionedNodeOrToken = TypeScript.Syntax.getStandaloneExpression(positionedToken); + var parent = positionedNodeOrToken.containingNode(); + + if (parent !== null) { + switch (parent.kind()) { + case 246 /* ModuleNameModuleReference */: + return true; + case 122 /* QualifiedName */: + return true; + default: + return isInTypeOnlyContext(positionedToken); + } + } + } + + return false; + } + Syntax.isInModuleOrTypeContext = isInModuleOrTypeContext; + + function isInTypeOnlyContext(positionedToken) { + var positionedNodeOrToken = TypeScript.Syntax.getStandaloneExpression(positionedToken); + var positionedParent = positionedNodeOrToken.containingNode(); + + var parent = positionedParent.node(); + var nodeOrToken = positionedNodeOrToken.nodeOrToken(); + + if (parent !== null) { + switch (parent.kind()) { + case 125 /* ArrayType */: + return (parent).type === nodeOrToken; + case 219 /* CastExpression */: + return (parent).type === nodeOrToken; + case 244 /* TypeAnnotation */: + case 229 /* HeritageClause */: + case 227 /* TypeArgumentList */: + return true; + } + } + + return false; + } + Syntax.isInTypeOnlyContext = isInTypeOnlyContext; + + function childOffset(parent, child) { + var offset = 0; + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return offset; + } + + if (current !== null) { + offset += current.fullWidth(); + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childOffset = childOffset; + + function childOffsetAt(parent, index) { + var offset = 0; + for (var i = 0; i < index; i++) { + var current = parent.childAt(i); + if (current !== null) { + offset += current.fullWidth(); + } + } + + return offset; + } + Syntax.childOffsetAt = childOffsetAt; + + function childIndex(parent, child) { + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return i; + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + + function nodeStructuralEquals(node1, node2) { + if (node1 === null) { + return node2 === null; + } + + return node1.structuralEquals(node2); + } + Syntax.nodeStructuralEquals = nodeStructuralEquals; + + function nodeOrTokenStructuralEquals(node1, node2) { + if (node1 === node2) { + return true; + } + + if (node1 === null || node2 === null) { + return false; + } + + if (node1.isToken()) { + return node2.isToken() ? tokenStructuralEquals(node1, node2) : false; + } + + return node2.isNode() ? nodeStructuralEquals(node1, node2) : false; + } + Syntax.nodeOrTokenStructuralEquals = nodeOrTokenStructuralEquals; + + function tokenStructuralEquals(token1, token2) { + if (token1 === token2) { + return true; + } + + if (token1 === null || token2 === null) { + return false; + } + + return token1.kind() === token2.kind() && token1.width() === token2.width() && token1.fullWidth() === token2.fullWidth() && token1.text() === token2.text() && TypeScript.Syntax.triviaListStructuralEquals(token1.leadingTrivia(), token2.leadingTrivia()) && TypeScript.Syntax.triviaListStructuralEquals(token1.trailingTrivia(), token2.trailingTrivia()); + } + Syntax.tokenStructuralEquals = tokenStructuralEquals; + + function triviaListStructuralEquals(triviaList1, triviaList2) { + if (triviaList1.count() !== triviaList2.count()) { + return false; + } + + for (var i = 0, n = triviaList1.count(); i < n; i++) { + if (!TypeScript.Syntax.triviaStructuralEquals(triviaList1.syntaxTriviaAt(i), triviaList2.syntaxTriviaAt(i))) { + return false; + } + } + + return true; + } + Syntax.triviaListStructuralEquals = triviaListStructuralEquals; + + function triviaStructuralEquals(trivia1, trivia2) { + return trivia1.kind() === trivia2.kind() && trivia1.fullWidth() === trivia2.fullWidth() && trivia1.fullText() === trivia2.fullText(); + } + Syntax.triviaStructuralEquals = triviaStructuralEquals; + + function listStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var child1 = list1.childAt(i); + var child2 = list2.childAt(i); + + if (!TypeScript.Syntax.nodeOrTokenStructuralEquals(child1, child2)) { + return false; + } + } + + return true; + } + Syntax.listStructuralEquals = listStructuralEquals; + + function separatedListStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var element1 = list1.childAt(i); + var element2 = list2.childAt(i); + if (!TypeScript.Syntax.nodeOrTokenStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + } + Syntax.separatedListStructuralEquals = separatedListStructuralEquals; + + function elementStructuralEquals(element1, element2) { + if (element1 === element2) { + return true; + } + + if (element1 === null || element2 === null) { + return false; + } + + if (element2.kind() !== element2.kind()) { + return false; + } + + if (element1.isToken()) { + return tokenStructuralEquals(element1, element2); + } else if (element1.isNode()) { + return nodeStructuralEquals(element1, element2); + } else if (element1.isList()) { + return listStructuralEquals(element1, element2); + } else if (element1.isSeparatedList()) { + return separatedListStructuralEquals(element1, element2); + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.elementStructuralEquals = elementStructuralEquals; + + function identifierName(text, info) { + if (typeof info === "undefined") { info = null; } + return Syntax.identifier(text); + } + Syntax.identifierName = identifierName; + + function trueExpression() { + return TypeScript.Syntax.token(37 /* TrueKeyword */); + } + Syntax.trueExpression = trueExpression; + + function falseExpression() { + return TypeScript.Syntax.token(24 /* FalseKeyword */); + } + Syntax.falseExpression = falseExpression; + + function numericLiteralExpression(text) { + return TypeScript.Syntax.token(13 /* NumericLiteral */, { text: text }); + } + Syntax.numericLiteralExpression = numericLiteralExpression; + + function stringLiteralExpression(text) { + return TypeScript.Syntax.token(14 /* StringLiteral */, { text: text }); + } + Syntax.stringLiteralExpression = stringLiteralExpression; + + function isSuperInvocationExpression(node) { + return node.kind() === 212 /* InvocationExpression */ && (node).expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperInvocationExpression = isSuperInvocationExpression; + + function isSuperInvocationExpressionStatement(node) { + return node.kind() === 148 /* ExpressionStatement */ && isSuperInvocationExpression((node).expression); + } + Syntax.isSuperInvocationExpressionStatement = isSuperInvocationExpressionStatement; + + function isSuperMemberAccessExpression(node) { + return node.kind() === 211 /* MemberAccessExpression */ && (node).expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperMemberAccessExpression = isSuperMemberAccessExpression; + + function isSuperMemberAccessInvocationExpression(node) { + return node.kind() === 212 /* InvocationExpression */ && isSuperMemberAccessExpression((node).expression); + } + Syntax.isSuperMemberAccessInvocationExpression = isSuperMemberAccessInvocationExpression; + + function assignmentExpression(left, token, right) { + return TypeScript.Syntax.normalModeFactory.binaryExpression(173 /* AssignmentExpression */, left, token, right); + } + Syntax.assignmentExpression = assignmentExpression; + + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < node.childCount(); i++) { + var child = node.childAt(i); + if (child !== null && child.isToken()) { + var token = child; + + if (token.hasSkippedToken() || (token.width() === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.token().hasLeadingTrivia()) { + triviaList = positionedToken.token().leadingTrivia(); + } else { + positionedToken = positionedToken.previousToken(); + if (positionedToken) { + if (positionedToken && positionedToken.token().hasTrailingTrivia()) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + } + } else { + if (position <= (fullStart + positionedToken.token().leadingTriviaWidth())) { + triviaList = positionedToken.token().leadingTrivia(); + } else if (position >= (fullStart + positionedToken.token().width())) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + + fullStart += trivia.fullWidth(); + } + } + + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = positionedToken.previousToken(); + return positionedToken && positionedToken.token().trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken.token()); + } else if (position > positionedToken.start()) { + return (position < positionedToken.end() && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= positionedToken.end() && isUnterminatedStringLiteral(positionedToken.token())); + } + } + + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullStart = positionedToken.fullStart(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullStart); + } + + fullStart += triviaWidth; + } + } + + return null; + } + + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + Syntax.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + Syntax.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent()) { + if (positionedToken.parent().kind() === kind) { + return positionedToken.parent(); + } + + positionedToken = positionedToken.parent(); + } + + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + + function hasAncestorOfKind(positionedToken, kind) { + return TypeScript.Syntax.getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDiagnostic = (function (_super) { + __extends(SyntaxDiagnostic, _super); + function SyntaxDiagnostic() { + _super.apply(this, arguments); + } + SyntaxDiagnostic.equals = function (diagnostic1, diagnostic2) { + return TypeScript.Diagnostic.equals(diagnostic1, diagnostic2); + }; + return SyntaxDiagnostic; + })(TypeScript.Diagnostic); + TypeScript.SyntaxDiagnostic = SyntaxDiagnostic; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var NormalModeFactory = (function () { + function NormalModeFactory() { + } + NormalModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, false); + }; + NormalModeFactory.prototype.externalModuleReference = function (moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, false); + }; + NormalModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, false); + }; + NormalModeFactory.prototype.importDeclaration = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + NormalModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, false); + }; + NormalModeFactory.prototype.heritageClause = function (extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, false); + }; + NormalModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, false); + }; + NormalModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, false); + }; + NormalModeFactory.prototype.variableDeclarator = function (identifier, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, false); + }; + NormalModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, false); + }; + NormalModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, false); + }; + NormalModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(false); + }; + NormalModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, false); + }; + NormalModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, body) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, false); + }; + NormalModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, body) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, false); + }; + NormalModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, false); + }; + NormalModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, false); + }; + NormalModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, false); + }; + NormalModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, false); + }; + NormalModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, false); + }; + NormalModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, false); + }; + NormalModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, false); + }; + NormalModeFactory.prototype.parameter = function (dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, false); + }; + NormalModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, false); + }; + NormalModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, false); + }; + NormalModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, false); + }; + NormalModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, false); + }; + NormalModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, false); + }; + NormalModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, false); + }; + NormalModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, false); + }; + NormalModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, false); + }; + NormalModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, false); + }; + NormalModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, false); + }; + NormalModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, false); + }; + NormalModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, false); + }; + NormalModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, false); + }; + NormalModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, false); + }; + NormalModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, false); + }; + NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); + }; + NormalModeFactory.prototype.constructorDeclaration = function (constructorKeyword, parameterList, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, false); + }; + NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.getMemberAccessorDeclaration = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setMemberAccessorDeclaration = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, false); + }; + NormalModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, false); + }; + NormalModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, false); + }; + NormalModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, false); + }; + NormalModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, false); + }; + NormalModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, false); + }; + NormalModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, false); + }; + NormalModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, false); + }; + NormalModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, false); + }; + NormalModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, false); + }; + NormalModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, false); + }; + NormalModeFactory.prototype.getAccessorPropertyAssignment = function (getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block) { + return new TypeScript.GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setAccessorPropertyAssignment = function (setKeyword, propertyName, openParenToken, parameter, closeParenToken, block) { + return new TypeScript.SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, false); + }; + NormalModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, false); + }; + NormalModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, false); + }; + NormalModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, false); + }; + NormalModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, false); + }; + NormalModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, false); + }; + NormalModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, false); + }; + NormalModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, false); + }; + NormalModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, false); + }; + NormalModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, false); + }; + NormalModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, false); + }; + NormalModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, false); + }; + return NormalModeFactory; + })(); + Syntax.NormalModeFactory = NormalModeFactory; + + var StrictModeFactory = (function () { + function StrictModeFactory() { + } + StrictModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, true); + }; + StrictModeFactory.prototype.externalModuleReference = function (moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, true); + }; + StrictModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, true); + }; + StrictModeFactory.prototype.importDeclaration = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, true); + }; + StrictModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, true); + }; + StrictModeFactory.prototype.heritageClause = function (extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, true); + }; + StrictModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, true); + }; + StrictModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, true); + }; + StrictModeFactory.prototype.variableDeclarator = function (identifier, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, true); + }; + StrictModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, true); + }; + StrictModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, true); + }; + StrictModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(true); + }; + StrictModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, true); + }; + StrictModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, body) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, true); + }; + StrictModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, body) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, true); + }; + StrictModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, true); + }; + StrictModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, true); + }; + StrictModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, true); + }; + StrictModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, true); + }; + StrictModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, true); + }; + StrictModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, true); + }; + StrictModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, true); + }; + StrictModeFactory.prototype.parameter = function (dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, true); + }; + StrictModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, true); + }; + StrictModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, true); + }; + StrictModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, true); + }; + StrictModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, true); + }; + StrictModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, true); + }; + StrictModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, true); + }; + StrictModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, true); + }; + StrictModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, true); + }; + StrictModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, true); + }; + StrictModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, true); + }; + StrictModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, true); + }; + StrictModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, true); + }; + StrictModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, true); + }; + StrictModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, true); + }; + StrictModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, true); + }; + StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); + }; + StrictModeFactory.prototype.constructorDeclaration = function (constructorKeyword, parameterList, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, true); + }; + StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.getMemberAccessorDeclaration = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setMemberAccessorDeclaration = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, true); + }; + StrictModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, true); + }; + StrictModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, true); + }; + StrictModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, true); + }; + StrictModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, true); + }; + StrictModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, true); + }; + StrictModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, true); + }; + StrictModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, true); + }; + StrictModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, true); + }; + StrictModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, true); + }; + StrictModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, true); + }; + StrictModeFactory.prototype.getAccessorPropertyAssignment = function (getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block) { + return new TypeScript.GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setAccessorPropertyAssignment = function (setKeyword, propertyName, openParenToken, parameter, closeParenToken, block) { + return new TypeScript.SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, true); + }; + StrictModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, true); + }; + StrictModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, true); + }; + StrictModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, true); + }; + StrictModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, true); + }; + StrictModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, true); + }; + StrictModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, true); + }; + StrictModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, true); + }; + StrictModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, true); + }; + StrictModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, true); + }; + StrictModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, true); + }; + StrictModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, true); + }; + return StrictModeFactory; + })(); + Syntax.StrictModeFactory = StrictModeFactory; + + Syntax.normalModeFactory = new NormalModeFactory(); + Syntax.strictModeFactory = new StrictModeFactory(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["BoolKeyword"] = 62] = "BoolKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 63] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 64] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 65] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 66] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 67] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 68] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 69] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 70] = "StringKeyword"; + + SyntaxKind[SyntaxKind["OpenBraceToken"] = 71] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 72] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 73] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 74] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 75] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 76] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 77] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 78] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 79] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 80] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 81] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 82] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 83] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 84] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 85] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 86] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 87] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 88] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 89] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 90] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 91] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 92] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 93] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 94] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 95] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 96] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 98] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 99] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 100] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 101] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 102] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 103] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 104] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 105] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 106] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 107] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 108] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 109] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 110] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 111] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 112] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 113] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 115] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 116] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 117] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 118] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 119] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 120] = "SlashEqualsToken"; + + SyntaxKind[SyntaxKind["SourceUnit"] = 121] = "SourceUnit"; + + SyntaxKind[SyntaxKind["QualifiedName"] = 122] = "QualifiedName"; + + SyntaxKind[SyntaxKind["ObjectType"] = 123] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 124] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 125] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 126] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 127] = "GenericType"; + + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["GetMemberAccessorDeclaration"] = 138] = "GetMemberAccessorDeclaration"; + SyntaxKind[SyntaxKind["SetMemberAccessorDeclaration"] = 139] = "SetMemberAccessorDeclaration"; + + SyntaxKind[SyntaxKind["PropertySignature"] = 140] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 141] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 142] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 143] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 144] = "MethodSignature"; + + SyntaxKind[SyntaxKind["Block"] = 145] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 146] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 147] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 148] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 149] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 150] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 151] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 152] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 153] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 154] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 155] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 156] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 157] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 158] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 159] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 160] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 161] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 162] = "WithStatement"; + + SyntaxKind[SyntaxKind["PlusExpression"] = 163] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 164] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 165] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 166] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 167] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 168] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 169] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 170] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 171] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 172] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 173] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 174] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 175] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 176] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 177] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 178] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 179] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 180] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 181] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 182] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 183] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 184] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 185] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 186] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 187] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 188] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 189] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 190] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 191] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 192] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 193] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 194] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 195] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 196] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 197] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 198] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 199] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 200] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 201] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 202] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 203] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 204] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 205] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 206] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 207] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 208] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 209] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 210] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 211] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 212] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 213] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 214] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 215] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 216] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 217] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 218] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 219] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 220] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 221] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; + + SyntaxKind[SyntaxKind["VariableDeclaration"] = 223] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 224] = "VariableDeclarator"; + + SyntaxKind[SyntaxKind["ArgumentList"] = 225] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 226] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 227] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 228] = "TypeParameterList"; + + SyntaxKind[SyntaxKind["HeritageClause"] = 229] = "HeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 230] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 231] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 232] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 233] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 234] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 235] = "FinallyClause"; + + SyntaxKind[SyntaxKind["TypeParameter"] = 236] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 237] = "Constraint"; + + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 238] = "SimplePropertyAssignment"; + SyntaxKind[SyntaxKind["GetAccessorPropertyAssignment"] = 239] = "GetAccessorPropertyAssignment"; + SyntaxKind[SyntaxKind["SetAccessorPropertyAssignment"] = 240] = "SetAccessorPropertyAssignment"; + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "bool": 62 /* BoolKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 63 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 64 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 65 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 66 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 68 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 67 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 69 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 70 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 71 /* OpenBraceToken */, + "}": 72 /* CloseBraceToken */, + "(": 73 /* OpenParenToken */, + ")": 74 /* CloseParenToken */, + "[": 75 /* OpenBracketToken */, + "]": 76 /* CloseBracketToken */, + ".": 77 /* DotToken */, + "...": 78 /* DotDotDotToken */, + ";": 79 /* SemicolonToken */, + ",": 80 /* CommaToken */, + "<": 81 /* LessThanToken */, + ">": 82 /* GreaterThanToken */, + "<=": 83 /* LessThanEqualsToken */, + ">=": 84 /* GreaterThanEqualsToken */, + "==": 85 /* EqualsEqualsToken */, + "=>": 86 /* EqualsGreaterThanToken */, + "!=": 87 /* ExclamationEqualsToken */, + "===": 88 /* EqualsEqualsEqualsToken */, + "!==": 89 /* ExclamationEqualsEqualsToken */, + "+": 90 /* PlusToken */, + "-": 91 /* MinusToken */, + "*": 92 /* AsteriskToken */, + "%": 93 /* PercentToken */, + "++": 94 /* PlusPlusToken */, + "--": 95 /* MinusMinusToken */, + "<<": 96 /* LessThanLessThanToken */, + ">>": 97 /* GreaterThanGreaterThanToken */, + ">>>": 98 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 99 /* AmpersandToken */, + "|": 100 /* BarToken */, + "^": 101 /* CaretToken */, + "!": 102 /* ExclamationToken */, + "~": 103 /* TildeToken */, + "&&": 104 /* AmpersandAmpersandToken */, + "||": 105 /* BarBarToken */, + "?": 106 /* QuestionToken */, + ":": 107 /* ColonToken */, + "=": 108 /* EqualsToken */, + "+=": 109 /* PlusEqualsToken */, + "-=": 110 /* MinusEqualsToken */, + "*=": 111 /* AsteriskEqualsToken */, + "%=": 112 /* PercentEqualsToken */, + "<<=": 113 /* LessThanLessThanEqualsToken */, + ">>=": 114 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 116 /* AmpersandEqualsToken */, + "|=": 117 /* BarEqualsToken */, + "^=": 118 /* CaretEqualsToken */, + "/": 119 /* SlashToken */, + "/=": 120 /* SlashEqualsToken */ + }; + + var kindToText = []; + + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + + kindToText[63 /* ConstructorKeyword */] = "constructor"; + + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + + function isTokenKind(kind) { + return kind >= 9 /* FirstToken */ && kind <= 120 /* LastToken */; + } + SyntaxFacts.isTokenKind = isTokenKind; + + function isAnyKeyword(kind) { + return kind >= TypeScript.SyntaxKind.FirstKeyword && kind <= TypeScript.SyntaxKind.LastKeyword; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + + function isStandardKeyword(kind) { + return kind >= 15 /* FirstStandardKeyword */ && kind <= 43 /* LastStandardKeyword */; + } + SyntaxFacts.isStandardKeyword = isStandardKeyword; + + function isFutureReservedKeyword(kind) { + return kind >= 44 /* FirstFutureReservedKeyword */ && kind <= 50 /* LastFutureReservedKeyword */; + } + SyntaxFacts.isFutureReservedKeyword = isFutureReservedKeyword; + + function isFutureReservedStrictKeyword(kind) { + return kind >= 51 /* FirstFutureReservedStrictKeyword */ && kind <= 59 /* LastFutureReservedStrictKeyword */; + } + SyntaxFacts.isFutureReservedStrictKeyword = isFutureReservedStrictKeyword; + + function isAnyPunctuation(kind) { + return kind >= 71 /* FirstPunctuation */ && kind <= 120 /* LastPunctuation */; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 90 /* PlusToken */: + return 163 /* PlusExpression */; + case 91 /* MinusToken */: + return 164 /* NegateExpression */; + case 103 /* TildeToken */: + return 165 /* BitwiseNotExpression */; + case 102 /* ExclamationToken */: + return 166 /* LogicalNotExpression */; + case 94 /* PlusPlusToken */: + return 167 /* PreIncrementExpression */; + case 95 /* MinusMinusToken */: + return 168 /* PreDecrementExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 94 /* PlusPlusToken */: + return 209 /* PostIncrementExpression */; + case 95 /* MinusMinusToken */: + return 210 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 92 /* AsteriskToken */: + return 204 /* MultiplyExpression */; + + case 119 /* SlashToken */: + return 205 /* DivideExpression */; + + case 93 /* PercentToken */: + return 206 /* ModuloExpression */; + + case 90 /* PlusToken */: + return 207 /* AddExpression */; + + case 91 /* MinusToken */: + return 208 /* SubtractExpression */; + + case 96 /* LessThanLessThanToken */: + return 201 /* LeftShiftExpression */; + + case 97 /* GreaterThanGreaterThanToken */: + return 202 /* SignedRightShiftExpression */; + + case 98 /* GreaterThanGreaterThanGreaterThanToken */: + return 203 /* UnsignedRightShiftExpression */; + + case 81 /* LessThanToken */: + return 195 /* LessThanExpression */; + + case 82 /* GreaterThanToken */: + return 196 /* GreaterThanExpression */; + + case 83 /* LessThanEqualsToken */: + return 197 /* LessThanOrEqualExpression */; + + case 84 /* GreaterThanEqualsToken */: + return 198 /* GreaterThanOrEqualExpression */; + + case 30 /* InstanceOfKeyword */: + return 199 /* InstanceOfExpression */; + + case 29 /* InKeyword */: + return 200 /* InExpression */; + + case 85 /* EqualsEqualsToken */: + return 191 /* EqualsWithTypeConversionExpression */; + + case 87 /* ExclamationEqualsToken */: + return 192 /* NotEqualsWithTypeConversionExpression */; + + case 88 /* EqualsEqualsEqualsToken */: + return 193 /* EqualsExpression */; + + case 89 /* ExclamationEqualsEqualsToken */: + return 194 /* NotEqualsExpression */; + + case 99 /* AmpersandToken */: + return 190 /* BitwiseAndExpression */; + + case 101 /* CaretToken */: + return 189 /* BitwiseExclusiveOrExpression */; + + case 100 /* BarToken */: + return 188 /* BitwiseOrExpression */; + + case 104 /* AmpersandAmpersandToken */: + return 187 /* LogicalAndExpression */; + + case 105 /* BarBarToken */: + return 186 /* LogicalOrExpression */; + + case 117 /* BarEqualsToken */: + return 181 /* OrAssignmentExpression */; + + case 116 /* AmpersandEqualsToken */: + return 179 /* AndAssignmentExpression */; + + case 118 /* CaretEqualsToken */: + return 180 /* ExclusiveOrAssignmentExpression */; + + case 113 /* LessThanLessThanEqualsToken */: + return 182 /* LeftShiftAssignmentExpression */; + + case 114 /* GreaterThanGreaterThanEqualsToken */: + return 183 /* SignedRightShiftAssignmentExpression */; + + case 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 184 /* UnsignedRightShiftAssignmentExpression */; + + case 109 /* PlusEqualsToken */: + return 174 /* AddAssignmentExpression */; + + case 110 /* MinusEqualsToken */: + return 175 /* SubtractAssignmentExpression */; + + case 111 /* AsteriskEqualsToken */: + return 176 /* MultiplyAssignmentExpression */; + + case 120 /* SlashEqualsToken */: + return 177 /* DivideAssignmentExpression */; + + case 112 /* PercentEqualsToken */: + return 178 /* ModuloAssignmentExpression */; + + case 108 /* EqualsToken */: + return 173 /* AssignmentExpression */; + + case 80 /* CommaToken */: + return 172 /* CommaExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + + function isAnyDivideToken(kind) { + switch (kind) { + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideToken = isAnyDivideToken; + + function isAnyDivideOrRegularExpressionToken(kind) { + switch (kind) { + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + case 12 /* RegularExpressionLiteral */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideOrRegularExpressionToken = isAnyDivideOrRegularExpressionToken; + + function isParserGenerated(kind) { + switch (kind) { + case 97 /* GreaterThanGreaterThanToken */: + case 98 /* GreaterThanGreaterThanGreaterThanToken */: + case 84 /* GreaterThanEqualsToken */: + case 114 /* GreaterThanGreaterThanEqualsToken */: + case 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isParserGenerated = isParserGenerated; + + function isAnyBinaryExpression(kind) { + switch (kind) { + case 172 /* CommaExpression */: + case 173 /* AssignmentExpression */: + case 174 /* AddAssignmentExpression */: + case 175 /* SubtractAssignmentExpression */: + case 176 /* MultiplyAssignmentExpression */: + case 177 /* DivideAssignmentExpression */: + case 178 /* ModuloAssignmentExpression */: + case 179 /* AndAssignmentExpression */: + case 180 /* ExclusiveOrAssignmentExpression */: + case 181 /* OrAssignmentExpression */: + case 182 /* LeftShiftAssignmentExpression */: + case 183 /* SignedRightShiftAssignmentExpression */: + case 184 /* UnsignedRightShiftAssignmentExpression */: + case 186 /* LogicalOrExpression */: + case 187 /* LogicalAndExpression */: + case 188 /* BitwiseOrExpression */: + case 189 /* BitwiseExclusiveOrExpression */: + case 190 /* BitwiseAndExpression */: + case 191 /* EqualsWithTypeConversionExpression */: + case 192 /* NotEqualsWithTypeConversionExpression */: + case 193 /* EqualsExpression */: + case 194 /* NotEqualsExpression */: + case 195 /* LessThanExpression */: + case 196 /* GreaterThanExpression */: + case 197 /* LessThanOrEqualExpression */: + case 198 /* GreaterThanOrEqualExpression */: + case 199 /* InstanceOfExpression */: + case 200 /* InExpression */: + case 201 /* LeftShiftExpression */: + case 202 /* SignedRightShiftExpression */: + case 203 /* UnsignedRightShiftExpression */: + case 204 /* MultiplyExpression */: + case 205 /* DivideExpression */: + case 206 /* ModuloExpression */: + case 207 /* AddExpression */: + case 208 /* SubtractExpression */: + return true; + } + + return false; + } + SyntaxFacts.isAnyBinaryExpression = isAnyBinaryExpression; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 148 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.tokenKind; + return tokenKind === 11 /* IdentifierName */ || TypeScript.SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySyntaxList = (function () { + function EmptySyntaxList() { + } + EmptySyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + EmptySyntaxList.prototype.isNode = function () { + return false; + }; + EmptySyntaxList.prototype.isToken = function () { + return false; + }; + EmptySyntaxList.prototype.isList = function () { + return true; + }; + EmptySyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + EmptySyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.width = function () { + return 0; + }; + + EmptySyntaxList.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + return EmptySyntaxList; + })(); + Syntax.EmptySyntaxList = EmptySyntaxList; + + Syntax.emptyList = new EmptySyntaxList(); + + var SingletonSyntaxList = (function () { + function SingletonSyntaxList(item) { + this.item = item; + } + SingletonSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + SingletonSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSyntaxList.prototype.isList = function () { + return true; + }; + SingletonSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + SingletonSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxList.prototype.childCount = function () { + return 1; + }; + + SingletonSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return (this.item).findTokenInternal(new TypeScript.PositionedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSyntaxList; + })(); + + var NormalSyntaxList = (function () { + function NormalSyntaxList(nodeOrTokens) { + this._data = 0; + this.nodeOrTokens = nodeOrTokens; + } + NormalSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + NormalSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSyntaxList.prototype.isList = function () { + return true; + }; + NormalSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + NormalSyntaxList.prototype.toJSON = function (key) { + return this.nodeOrTokens; + }; + + NormalSyntaxList.prototype.childCount = function () { + return this.nodeOrTokens.length; + }; + + NormalSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.nodeOrTokens.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.nodeOrTokens[index]; + }; + + NormalSyntaxList.prototype.toArray = function () { + return this.nodeOrTokens.slice(0); + }; + + NormalSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var element = this.nodeOrTokens[i]; + element.collectTextElements(elements); + } + }; + + NormalSyntaxList.prototype.firstToken = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var token = this.nodeOrTokens[i].firstToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.lastToken = function () { + for (var i = this.nodeOrTokens.length - 1; i >= 0; i--) { + var token = this.nodeOrTokens[i].lastToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + if (this.nodeOrTokens[i].isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var node = this.nodeOrTokens[i]; + fullWidth += node.fullWidth(); + isIncrementallyUnusable = isIncrementallyUnusable || node.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedList(parent, this, fullStart); + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var nodeOrToken = this.nodeOrTokens[i]; + + var childWidth = nodeOrToken.fullWidth(); + if (position < childWidth) { + return (nodeOrToken).findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.nodeOrTokens); + } else { + array.splice.apply(array, [index, 0].concat(this.nodeOrTokens)); + } + }; + return NormalSyntaxList; + })(); + + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptyList; + } + + if (nodes.length === 1) { + var item = nodes[0]; + return new SingletonSyntaxList(item); + } + + return new NormalSyntaxList(nodes); + } + Syntax.list = list; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(parsedInStrictMode) { + this._data = parsedInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + SyntaxNode.prototype.isNode = function () { + return true; + }; + SyntaxNode.prototype.isToken = function () { + return false; + }; + SyntaxNode.prototype.isList = function () { + return false; + }; + SyntaxNode.prototype.isSeparatedList = function () { + return false; + }; + + SyntaxNode.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childCount = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childAt = function (slot) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.firstToken = function () { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.firstToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.lastToken = function () { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.lastToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.insertChildrenInto = function (array, index) { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.isNode() || element.isToken()) { + array.splice(index, 0, element); + } else if (element.isList()) { + (element).insertChildrenInto(array, index); + } else if (element.isSeparatedList()) { + (element).insertChildrenInto(array, index); + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + } + }; + + SyntaxNode.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + SyntaxNode.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + SyntaxNode.prototype.toJSON = function (key) { + var result = { + kind: TypeScript.SyntaxKind[this.kind()], + fullWidth: this.fullWidth() + }; + + if (this.isIncrementallyUnusable()) { + result.isIncrementallyUnusable = true; + } + + if (this.parsedInStrictMode()) { + result.parsedInStrictMode = true; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var value = this.childAt(i); + + if (value) { + for (var name in this) { + if (value === this[name]) { + result[name] = value; + break; + } + } + } + } + + return result; + }; + + SyntaxNode.prototype.accept = function (visitor) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + SyntaxNode.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + element.collectTextElements(elements); + } + } + }; + + SyntaxNode.prototype.replaceToken = function (token1, token2) { + if (token1 === token2) { + return this; + } + + return this.accept(new TypeScript.SyntaxTokenReplacer(token1, token2)); + }; + + SyntaxNode.prototype.withLeadingTrivia = function (trivia) { + return this.replaceToken(this.firstToken(), this.firstToken().withLeadingTrivia(trivia)); + }; + + SyntaxNode.prototype.withTrailingTrivia = function (trivia) { + return this.replaceToken(this.lastToken(), this.lastToken().withTrailingTrivia(trivia)); + }; + + SyntaxNode.prototype.hasLeadingTrivia = function () { + return this.lastToken().hasLeadingTrivia(); + }; + + SyntaxNode.prototype.hasTrailingTrivia = function () { + return this.lastToken().hasTrailingTrivia(); + }; + + SyntaxNode.prototype.isTypeScriptSpecific = function () { + return false; + }; + + SyntaxNode.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + SyntaxNode.prototype.parsedInStrictMode = function () { + return (this.data() & 4 /* NodeParsedInStrictModeMask */) !== 0; + }; + + SyntaxNode.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + SyntaxNode.prototype.computeData = function () { + var slotCount = this.childCount(); + + var fullWidth = 0; + var childWidth = 0; + + var isIncrementallyUnusable = ((this._data & 2 /* NodeIncrementallyUnusableMask */) !== 0) || slotCount === 0; + + for (var i = 0, n = slotCount; i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + childWidth = element.fullWidth(); + fullWidth += childWidth; + + if (!isIncrementallyUnusable) { + isIncrementallyUnusable = element.isIncrementallyUnusable(); + } + } + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + SyntaxNode.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data |= this.computeData(); + } + + return this._data; + }; + + SyntaxNode.prototype.findToken = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var endOfFileToken = this.tryGetEndOfFileAt(position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + + if (position < 0 || position >= this.fullWidth()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var positionedToken = this.findTokenInternal(null, position, 0); + + if (includeSkippedTokens) { + return TypeScript.Syntax.findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + + return positionedToken; + }; + + SyntaxNode.prototype.tryGetEndOfFileAt = function (position) { + if (this.kind() === 121 /* SourceUnit */ && position === this.fullWidth()) { + var sourceUnit = this; + return new TypeScript.PositionedToken(new TypeScript.PositionedNode(null, sourceUnit, 0), sourceUnit.endOfFileToken, sourceUnit.moduleElements.fullWidth()); + } + + return null; + }; + + SyntaxNode.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedNode(parent, this, fullStart); + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + var childWidth = element.fullWidth(); + + if (position < childWidth) { + return (element).findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxNode.prototype.findTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, includeSkippedTokens); + var start = positionedToken.start(); + + if (position > start) { + return positionedToken; + } + + if (positionedToken.fullStart() === 0) { + return null; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.findCompleteTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, includeSkippedTokens); + + if (positionedToken.token().width() > 0 && position >= positionedToken.end()) { + return positionedToken; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.isModuleElement = function () { + return false; + }; + + SyntaxNode.prototype.isClassElement = function () { + return false; + }; + + SyntaxNode.prototype.isTypeMember = function () { + return false; + }; + + SyntaxNode.prototype.isStatement = function () { + return false; + }; + + SyntaxNode.prototype.isSwitchClause = function () { + return false; + }; + + SyntaxNode.prototype.structuralEquals = function (node) { + if (this === node) { + return true; + } + if (node === null) { + return false; + } + if (this.kind() !== node.kind()) { + return false; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var element1 = this.childAt(i); + var element2 = node.childAt(i); + + if (!TypeScript.Syntax.elementStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + }; + + SyntaxNode.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + SyntaxNode.prototype.leadingTriviaWidth = function () { + var firstToken = this.firstToken(); + return firstToken === null ? 0 : firstToken.leadingTriviaWidth(); + }; + + SyntaxNode.prototype.trailingTriviaWidth = function () { + var lastToken = this.lastToken(); + return lastToken === null ? 0 : lastToken.trailingTriviaWidth(); + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(moduleElements, endOfFileToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleElements = moduleElements; + this.endOfFileToken = endOfFileToken; + } + SourceUnitSyntax.prototype.accept = function (visitor) { + return visitor.visitSourceUnit(this); + }; + + SourceUnitSyntax.prototype.kind = function () { + return 121 /* SourceUnit */; + }; + + SourceUnitSyntax.prototype.childCount = function () { + return 2; + }; + + SourceUnitSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleElements; + case 1: + return this.endOfFileToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SourceUnitSyntax.prototype.update = function (moduleElements, endOfFileToken) { + if (this.moduleElements === moduleElements && this.endOfFileToken === endOfFileToken) { + return this; + } + + return new SourceUnitSyntax(moduleElements, endOfFileToken, this.parsedInStrictMode()); + }; + + SourceUnitSyntax.create = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.create1 = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(moduleElements, this.endOfFileToken); + }; + + SourceUnitSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + SourceUnitSyntax.prototype.withEndOfFileToken = function (endOfFileToken) { + return this.update(this.moduleElements, endOfFileToken); + }; + + SourceUnitSyntax.prototype.isTypeScriptSpecific = function () { + if (this.moduleElements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SourceUnitSyntax = SourceUnitSyntax; + + var ModuleReferenceSyntax = (function (_super) { + __extends(ModuleReferenceSyntax, _super); + function ModuleReferenceSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + ModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleReferenceSyntax = ModuleReferenceSyntax; + + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleOrRequireKeyword = moduleOrRequireKeyword; + this.openParenToken = openParenToken; + this.stringLiteral = stringLiteral; + this.closeParenToken = closeParenToken; + } + ExternalModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitExternalModuleReference(this); + }; + + ExternalModuleReferenceSyntax.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + + ExternalModuleReferenceSyntax.prototype.childCount = function () { + return 4; + }; + + ExternalModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleOrRequireKeyword; + case 1: + return this.openParenToken; + case 2: + return this.stringLiteral; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExternalModuleReferenceSyntax.prototype.update = function (moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken) { + if (this.moduleOrRequireKeyword === moduleOrRequireKeyword && this.openParenToken === openParenToken && this.stringLiteral === stringLiteral && this.closeParenToken === closeParenToken) { + return this; + } + + return new ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, this.parsedInStrictMode()); + }; + + ExternalModuleReferenceSyntax.create1 = function (moduleOrRequireKeyword, stringLiteral) { + return new ExternalModuleReferenceSyntax(moduleOrRequireKeyword, TypeScript.Syntax.token(73 /* OpenParenToken */), stringLiteral, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ExternalModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withModuleOrRequireKeyword = function (moduleOrRequireKeyword) { + return this.update(moduleOrRequireKeyword, this.openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.moduleOrRequireKeyword, openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.moduleOrRequireKeyword, this.openParenToken, stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.moduleOrRequireKeyword, this.openParenToken, this.stringLiteral, closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExternalModuleReferenceSyntax; + })(ModuleReferenceSyntax); + TypeScript.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(moduleName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleName = moduleName; + } + ModuleNameModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleNameModuleReference(this); + }; + + ModuleNameModuleReferenceSyntax.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + + ModuleNameModuleReferenceSyntax.prototype.childCount = function () { + return 1; + }; + + ModuleNameModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleName; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleNameModuleReferenceSyntax.prototype.update = function (moduleName) { + if (this.moduleName === moduleName) { + return this; + } + + return new ModuleNameModuleReferenceSyntax(moduleName, this.parsedInStrictMode()); + }; + + ModuleNameModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withModuleName = function (moduleName) { + return this.update(moduleName); + }; + + ModuleNameModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleNameModuleReferenceSyntax; + })(ModuleReferenceSyntax); + TypeScript.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.importKeyword = importKeyword; + this.identifier = identifier; + this.equalsToken = equalsToken; + this.moduleReference = moduleReference; + this.semicolonToken = semicolonToken; + } + ImportDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitImportDeclaration(this); + }; + + ImportDeclarationSyntax.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + ImportDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.importKeyword; + case 1: + return this.identifier; + case 2: + return this.equalsToken; + case 3: + return this.moduleReference; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ImportDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ImportDeclarationSyntax.prototype.update = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + if (this.importKeyword === importKeyword && this.identifier === identifier && this.equalsToken === equalsToken && this.moduleReference === moduleReference && this.semicolonToken === semicolonToken) { + return this; + } + + return new ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, this.parsedInStrictMode()); + }; + + ImportDeclarationSyntax.create1 = function (identifier, moduleReference) { + return new ImportDeclarationSyntax(TypeScript.Syntax.token(49 /* ImportKeyword */), identifier, TypeScript.Syntax.token(108 /* EqualsToken */), moduleReference, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ImportDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withImportKeyword = function (importKeyword) { + return this.update(importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.importKeyword, identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.importKeyword, this.identifier, equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModuleReference = function (moduleReference) { + return this.update(this.importKeyword, this.identifier, this.equalsToken, moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, semicolonToken); + }; + + ImportDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ImportDeclarationSyntax = ImportDeclarationSyntax; + + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.exportKeyword = exportKeyword; + this.equalsToken = equalsToken; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ExportAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitExportAssignment(this); + }; + + ExportAssignmentSyntax.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignmentSyntax.prototype.childCount = function () { + return 4; + }; + + ExportAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.exportKeyword; + case 1: + return this.equalsToken; + case 2: + return this.identifier; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExportAssignmentSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExportAssignmentSyntax.prototype.update = function (exportKeyword, equalsToken, identifier, semicolonToken) { + if (this.exportKeyword === exportKeyword && this.equalsToken === equalsToken && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ExportAssignmentSyntax.create1 = function (identifier) { + return new ExportAssignmentSyntax(TypeScript.Syntax.token(47 /* ExportKeyword */), TypeScript.Syntax.token(108 /* EqualsToken */), identifier, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ExportAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withExportKeyword = function (exportKeyword) { + return this.update(exportKeyword, this.equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.exportKeyword, equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.exportKeyword, this.equalsToken, identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.exportKeyword, this.equalsToken, this.identifier, semicolonToken); + }; + + ExportAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExportAssignmentSyntax = ExportAssignmentSyntax; + + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.classKeyword = classKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.openBraceToken = openBraceToken; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + } + ClassDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitClassDeclaration(this); + }; + + ClassDeclarationSyntax.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclarationSyntax.prototype.childCount = function () { + return 8; + }; + + ClassDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.classKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.openBraceToken; + case 6: + return this.classElements; + case 7: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ClassDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ClassDeclarationSyntax.prototype.update = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + if (this.modifiers === modifiers && this.classKeyword === classKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.openBraceToken === openBraceToken && this.classElements === classElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ClassDeclarationSyntax.create = function (classKeyword, identifier, openBraceToken, closeBraceToken) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, classKeyword, identifier, null, TypeScript.Syntax.emptyList, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ClassDeclarationSyntax.create1 = function (identifier) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(44 /* ClassKeyword */), identifier, null, TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ClassDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ClassDeclarationSyntax.prototype.withClassKeyword = function (classKeyword) { + return this.update(this.modifiers, classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.classKeyword, identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.classKeyword, this.identifier, typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + ClassDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElements = function (classElements) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElement = function (classElement) { + return this.withClassElements(TypeScript.Syntax.list([classElement])); + }; + + ClassDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ClassDeclarationSyntax = ClassDeclarationSyntax; + + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.interfaceKeyword = interfaceKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + } + InterfaceDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitInterfaceDeclaration(this); + }; + + InterfaceDeclarationSyntax.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + InterfaceDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.interfaceKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InterfaceDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + InterfaceDeclarationSyntax.prototype.update = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + if (this.modifiers === modifiers && this.interfaceKeyword === interfaceKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.body === body) { + return this; + } + + return new InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, this.parsedInStrictMode()); + }; + + InterfaceDeclarationSyntax.create = function (interfaceKeyword, identifier, body) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, interfaceKeyword, identifier, null, TypeScript.Syntax.emptyList, body, false); + }; + + InterfaceDeclarationSyntax.create1 = function (identifier) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(52 /* InterfaceKeyword */), identifier, null, TypeScript.Syntax.emptyList, ObjectTypeSyntax.create1(), false); + }; + + InterfaceDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + InterfaceDeclarationSyntax.prototype.withInterfaceKeyword = function (interfaceKeyword) { + return this.update(this.modifiers, interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.interfaceKeyword, identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + InterfaceDeclarationSyntax.prototype.withBody = function (body) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, body); + }; + + InterfaceDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword; + this.typeNames = typeNames; + } + HeritageClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitHeritageClause(this); + }; + + HeritageClauseSyntax.prototype.kind = function () { + return 229 /* HeritageClause */; + }; + + HeritageClauseSyntax.prototype.childCount = function () { + return 2; + }; + + HeritageClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsOrImplementsKeyword; + case 1: + return this.typeNames; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + HeritageClauseSyntax.prototype.update = function (extendsOrImplementsKeyword, typeNames) { + if (this.extendsOrImplementsKeyword === extendsOrImplementsKeyword && this.typeNames === typeNames) { + return this; + } + + return new HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, this.parsedInStrictMode()); + }; + + HeritageClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withExtendsOrImplementsKeyword = function (extendsOrImplementsKeyword) { + return this.update(extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeNames = function (typeNames) { + return this.update(this.extendsOrImplementsKeyword, typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeName = function (typeName) { + return this.withTypeNames(TypeScript.Syntax.separatedList([typeName])); + }; + + HeritageClauseSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.HeritageClauseSyntax = HeritageClauseSyntax; + + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.moduleKeyword = moduleKeyword; + this.moduleName = moduleName; + this.stringLiteral = stringLiteral; + this.openBraceToken = openBraceToken; + this.moduleElements = moduleElements; + this.closeBraceToken = closeBraceToken; + } + ModuleDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleDeclaration(this); + }; + + ModuleDeclarationSyntax.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclarationSyntax.prototype.childCount = function () { + return 7; + }; + + ModuleDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.moduleKeyword; + case 2: + return this.moduleName; + case 3: + return this.stringLiteral; + case 4: + return this.openBraceToken; + case 5: + return this.moduleElements; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ModuleDeclarationSyntax.prototype.update = function (modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + if (this.modifiers === modifiers && this.moduleKeyword === moduleKeyword && this.moduleName === moduleName && this.stringLiteral === stringLiteral && this.openBraceToken === openBraceToken && this.moduleElements === moduleElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ModuleDeclarationSyntax.create = function (moduleKeyword, openBraceToken, closeBraceToken) { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, moduleKeyword, null, null, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ModuleDeclarationSyntax.create1 = function () { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(66 /* ModuleKeyword */), null, null, TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ModuleDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ModuleDeclarationSyntax.prototype.withModuleKeyword = function (moduleKeyword) { + return this.update(this.modifiers, moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleName = function (moduleName) { + return this.update(this.modifiers, this.moduleKeyword, moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + ModuleDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + FunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionDeclaration(this); + }; + + FunctionDeclarationSyntax.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + FunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.functionKeyword; + case 2: + return this.identifier; + case 3: + return this.callSignature; + case 4: + return this.block; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionDeclarationSyntax.prototype.isStatement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.update = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + FunctionDeclarationSyntax.create = function (functionKeyword, identifier, callSignature) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, functionKeyword, identifier, callSignature, null, null, false); + }; + + FunctionDeclarationSyntax.create1 = function (identifier) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(27 /* FunctionKeyword */), identifier, CallSignatureSyntax.create1(), null, null, false); + }; + + FunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + FunctionDeclarationSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(this.modifiers, functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.functionKeyword, identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block !== null && this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclaration = variableDeclaration; + this.semicolonToken = semicolonToken; + } + VariableStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableStatement(this); + }; + + VariableStatementSyntax.prototype.kind = function () { + return 147 /* VariableStatement */; + }; + + VariableStatementSyntax.prototype.childCount = function () { + return 3; + }; + + VariableStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclaration; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableStatementSyntax.prototype.isStatement = function () { + return true; + }; + + VariableStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + VariableStatementSyntax.prototype.update = function (modifiers, variableDeclaration, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclaration === variableDeclaration && this.semicolonToken === semicolonToken) { + return this; + } + + return new VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, this.parsedInStrictMode()); + }; + + VariableStatementSyntax.create = function (variableDeclaration, semicolonToken) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, semicolonToken, false); + }; + + VariableStatementSyntax.create1 = function (variableDeclaration) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + VariableStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + VariableStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.modifiers, variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclaration, semicolonToken); + }; + + VariableStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableStatementSyntax = VariableStatementSyntax; + + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(varKeyword, variableDeclarators, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.varKeyword = varKeyword; + this.variableDeclarators = variableDeclarators; + } + VariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclaration(this); + }; + + VariableDeclarationSyntax.prototype.kind = function () { + return 223 /* VariableDeclaration */; + }; + + VariableDeclarationSyntax.prototype.childCount = function () { + return 2; + }; + + VariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.varKeyword; + case 1: + return this.variableDeclarators; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclarationSyntax.prototype.update = function (varKeyword, variableDeclarators) { + if (this.varKeyword === varKeyword && this.variableDeclarators === variableDeclarators) { + return this; + } + + return new VariableDeclarationSyntax(varKeyword, variableDeclarators, this.parsedInStrictMode()); + }; + + VariableDeclarationSyntax.create1 = function (variableDeclarators) { + return new VariableDeclarationSyntax(TypeScript.Syntax.token(40 /* VarKeyword */), variableDeclarators, false); + }; + + VariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withVarKeyword = function (varKeyword) { + return this.update(varKeyword, this.variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarators = function (variableDeclarators) { + return this.update(this.varKeyword, variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.withVariableDeclarators(TypeScript.Syntax.separatedList([variableDeclarator])); + }; + + VariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclarators.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclarationSyntax = VariableDeclarationSyntax; + + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + VariableDeclaratorSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclarator(this); + }; + + VariableDeclaratorSyntax.prototype.kind = function () { + return 224 /* VariableDeclarator */; + }; + + VariableDeclaratorSyntax.prototype.childCount = function () { + return 3; + }; + + VariableDeclaratorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.typeAnnotation; + case 2: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclaratorSyntax.prototype.update = function (identifier, typeAnnotation, equalsValueClause) { + if (this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + VariableDeclaratorSyntax.create = function (identifier) { + return new VariableDeclaratorSyntax(identifier, null, null, false); + }; + + VariableDeclaratorSyntax.create1 = function (identifier) { + return new VariableDeclaratorSyntax(identifier, null, null, false); + }; + + VariableDeclaratorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.identifier, typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.identifier, this.typeAnnotation, equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(equalsToken, value, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsToken = equalsToken; + this.value = value; + } + EqualsValueClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitEqualsValueClause(this); + }; + + EqualsValueClauseSyntax.prototype.kind = function () { + return 230 /* EqualsValueClause */; + }; + + EqualsValueClauseSyntax.prototype.childCount = function () { + return 2; + }; + + EqualsValueClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.equalsToken; + case 1: + return this.value; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EqualsValueClauseSyntax.prototype.update = function (equalsToken, value) { + if (this.equalsToken === equalsToken && this.value === value) { + return this; + } + + return new EqualsValueClauseSyntax(equalsToken, value, this.parsedInStrictMode()); + }; + + EqualsValueClauseSyntax.create1 = function (value) { + return new EqualsValueClauseSyntax(TypeScript.Syntax.token(108 /* EqualsToken */), value, false); + }; + + EqualsValueClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(equalsToken, this.value); + }; + + EqualsValueClauseSyntax.prototype.withValue = function (value) { + return this.update(this.equalsToken, value); + }; + + EqualsValueClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.value.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(kind, operatorToken, operand, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operatorToken = operatorToken; + this.operand = operand; + + this._kind = kind; + } + PrefixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPrefixUnaryExpression(this); + }; + + PrefixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PrefixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operatorToken; + case 1: + return this.operand; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PrefixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PrefixUnaryExpressionSyntax.prototype.update = function (kind, operatorToken, operand) { + if (this._kind === kind && this.operatorToken === operatorToken && this.operand === operand) { + return this; + } + + return new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, this.parsedInStrictMode()); + }; + + PrefixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, this.operatorToken, operand); + }; + + PrefixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.expressions = expressions; + this.closeBracketToken = closeBracketToken; + } + ArrayLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayLiteralExpression(this); + }; + + ArrayLiteralExpressionSyntax.prototype.kind = function () { + return 213 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.expressions; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.update = function (openBracketToken, expressions, closeBracketToken) { + if (this.openBracketToken === openBracketToken && this.expressions === expressions && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayLiteralExpressionSyntax.create = function (openBracketToken, closeBracketToken) { + return new ArrayLiteralExpressionSyntax(openBracketToken, TypeScript.Syntax.emptySeparatedList, closeBracketToken, false); + }; + + ArrayLiteralExpressionSyntax.create1 = function () { + return new ArrayLiteralExpressionSyntax(TypeScript.Syntax.token(75 /* OpenBracketToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(76 /* CloseBracketToken */), false); + }; + + ArrayLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpressions = function (expressions) { + return this.update(this.openBracketToken, expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpression = function (expression) { + return this.withExpressions(TypeScript.Syntax.separatedList([expression])); + }; + + ArrayLiteralExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.expressions, closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expressions.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + OmittedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitOmittedExpression(this); + }; + + OmittedExpressionSyntax.prototype.kind = function () { + return 222 /* OmittedExpression */; + }; + + OmittedExpressionSyntax.prototype.childCount = function () { + return 0; + }; + + OmittedExpressionSyntax.prototype.childAt = function (slot) { + throw TypeScript.Errors.invalidOperation(); + }; + + OmittedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + OmittedExpressionSyntax.prototype.update = function () { + return this; + }; + + OmittedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.OmittedExpressionSyntax = OmittedExpressionSyntax; + + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + } + ParenthesizedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedExpression(this); + }; + + ParenthesizedExpressionSyntax.prototype.kind = function () { + return 216 /* ParenthesizedExpression */; + }; + + ParenthesizedExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.expression; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.update = function (openParenToken, expression, closeParenToken) { + if (this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, this.parsedInStrictMode()); + }; + + ParenthesizedExpressionSyntax.create1 = function (expression) { + return new ParenthesizedExpressionSyntax(TypeScript.Syntax.token(73 /* OpenParenToken */), expression, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ParenthesizedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.openParenToken, expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.expression, closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + + var ArrowFunctionExpressionSyntax = (function (_super) { + __extends(ArrowFunctionExpressionSyntax, _super); + function ArrowFunctionExpressionSyntax(equalsGreaterThanToken, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.body = body; + } + ArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrowFunctionExpressionSyntax = ArrowFunctionExpressionSyntax; + + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, parsedInStrictMode) { + _super.call(this, equalsGreaterThanToken, body, parsedInStrictMode); + this.identifier = identifier; + } + SimpleArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitSimpleArrowFunctionExpression(this); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.kind = function () { + return 218 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimpleArrowFunctionExpressionSyntax.prototype.update = function (identifier, equalsGreaterThanToken, body) { + if (this.identifier === identifier && this.equalsGreaterThanToken === equalsGreaterThanToken && this.body === body) { + return this; + } + + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, this.parsedInStrictMode()); + }; + + SimpleArrowFunctionExpressionSyntax.create1 = function (identifier, body) { + return new SimpleArrowFunctionExpressionSyntax(identifier, TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), body, false); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.equalsGreaterThanToken, this.body); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.identifier, equalsGreaterThanToken, this.body); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withBody = function (body) { + return this.update(this.identifier, this.equalsGreaterThanToken, body); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SimpleArrowFunctionExpressionSyntax; + })(ArrowFunctionExpressionSyntax); + TypeScript.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, parsedInStrictMode) { + _super.call(this, equalsGreaterThanToken, body, parsedInStrictMode); + this.callSignature = callSignature; + } + ParenthesizedArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedArrowFunctionExpression(this); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.kind = function () { + return 217 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.callSignature; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.update = function (callSignature, equalsGreaterThanToken, body) { + if (this.callSignature === callSignature && this.equalsGreaterThanToken === equalsGreaterThanToken && this.body === body) { + return this; + } + + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, this.parsedInStrictMode()); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create1 = function (body) { + return new ParenthesizedArrowFunctionExpressionSyntax(CallSignatureSyntax.create1(), TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), body, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(callSignature, this.equalsGreaterThanToken, this.body); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.callSignature, equalsGreaterThanToken, this.body); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withBody = function (body) { + return this.update(this.callSignature, this.equalsGreaterThanToken, body); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ParenthesizedArrowFunctionExpressionSyntax; + })(ArrowFunctionExpressionSyntax); + TypeScript.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(left, dotToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.dotToken = dotToken; + this.right = right; + } + QualifiedNameSyntax.prototype.accept = function (visitor) { + return visitor.visitQualifiedName(this); + }; + + QualifiedNameSyntax.prototype.kind = function () { + return 122 /* QualifiedName */; + }; + + QualifiedNameSyntax.prototype.childCount = function () { + return 3; + }; + + QualifiedNameSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.dotToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + QualifiedNameSyntax.prototype.isName = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isType = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isExpression = function () { + return true; + }; + + QualifiedNameSyntax.prototype.update = function (left, dotToken, right) { + if (this.left === left && this.dotToken === dotToken && this.right === right) { + return this; + } + + return new QualifiedNameSyntax(left, dotToken, right, this.parsedInStrictMode()); + }; + + QualifiedNameSyntax.create1 = function (left, right) { + return new QualifiedNameSyntax(left, TypeScript.Syntax.token(77 /* DotToken */), right, false); + }; + + QualifiedNameSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withLeft = function (left) { + return this.update(left, this.dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.left, dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withRight = function (right) { + return this.update(this.left, this.dotToken, right); + }; + + QualifiedNameSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + TypeScript.QualifiedNameSyntax = QualifiedNameSyntax; + + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeArguments = typeArguments; + this.greaterThanToken = greaterThanToken; + } + TypeArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeArgumentList(this); + }; + + TypeArgumentListSyntax.prototype.kind = function () { + return 227 /* TypeArgumentList */; + }; + + TypeArgumentListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeArguments; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeArgumentListSyntax.prototype.update = function (lessThanToken, typeArguments, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeArguments === typeArguments && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeArgumentListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeArgumentListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeArgumentListSyntax.create1 = function () { + return new TypeArgumentListSyntax(TypeScript.Syntax.token(81 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(82 /* GreaterThanToken */), false); + }; + + TypeArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArguments = function (typeArguments) { + return this.update(this.lessThanToken, typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArgument = function (typeArgument) { + return this.withTypeArguments(TypeScript.Syntax.separatedList([typeArgument])); + }; + + TypeArgumentListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeArguments, greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeArgumentListSyntax = TypeArgumentListSyntax; + + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + ConstructorTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorType(this); + }; + + ConstructorTypeSyntax.prototype.kind = function () { + return 126 /* ConstructorType */; + }; + + ConstructorTypeSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.typeParameterList; + case 2: + return this.parameterList; + case 3: + return this.equalsGreaterThanToken; + case 4: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorTypeSyntax.prototype.isType = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.isExpression = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.update = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.newKeyword === newKeyword && this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + ConstructorTypeSyntax.create = function (newKeyword, parameterList, equalsGreaterThanToken, type) { + return new ConstructorTypeSyntax(newKeyword, null, parameterList, equalsGreaterThanToken, type, false); + }; + + ConstructorTypeSyntax.create1 = function (type) { + return new ConstructorTypeSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), null, ParameterListSyntax.create1(), TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), type, false); + }; + + ConstructorTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.newKeyword, typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.newKeyword, this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withType = function (type) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + ConstructorTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorTypeSyntax = ConstructorTypeSyntax; + + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + FunctionTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionType(this); + }; + + FunctionTypeSyntax.prototype.kind = function () { + return 124 /* FunctionType */; + }; + + FunctionTypeSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.equalsGreaterThanToken; + case 3: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionTypeSyntax.prototype.isType = function () { + return true; + }; + + FunctionTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionTypeSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionTypeSyntax.prototype.update = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + FunctionTypeSyntax.create = function (parameterList, equalsGreaterThanToken, type) { + return new FunctionTypeSyntax(null, parameterList, equalsGreaterThanToken, type, false); + }; + + FunctionTypeSyntax.create1 = function (type) { + return new FunctionTypeSyntax(null, ParameterListSyntax.create1(), TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), type, false); + }; + + FunctionTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withType = function (type) { + return this.update(this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + FunctionTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionTypeSyntax = FunctionTypeSyntax; + + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.typeMembers = typeMembers; + this.closeBraceToken = closeBraceToken; + } + ObjectTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectType(this); + }; + + ObjectTypeSyntax.prototype.kind = function () { + return 123 /* ObjectType */; + }; + + ObjectTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.typeMembers; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectTypeSyntax.prototype.isType = function () { + return true; + }; + + ObjectTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectTypeSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectTypeSyntax.prototype.update = function (openBraceToken, typeMembers, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.typeMembers === typeMembers && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectTypeSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectTypeSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectTypeSyntax.create1 = function () { + return new ObjectTypeSyntax(TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ObjectTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMembers = function (typeMembers) { + return this.update(this.openBraceToken, typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMember = function (typeMember) { + return this.withTypeMembers(TypeScript.Syntax.separatedList([typeMember])); + }; + + ObjectTypeSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.typeMembers, closeBraceToken); + }; + + ObjectTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectTypeSyntax = ObjectTypeSyntax; + + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(type, openBracketToken, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.type = type; + this.openBracketToken = openBracketToken; + this.closeBracketToken = closeBracketToken; + } + ArrayTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayType(this); + }; + + ArrayTypeSyntax.prototype.kind = function () { + return 125 /* ArrayType */; + }; + + ArrayTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.type; + case 1: + return this.openBracketToken; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayTypeSyntax.prototype.isType = function () { + return true; + }; + + ArrayTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayTypeSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayTypeSyntax.prototype.update = function (type, openBracketToken, closeBracketToken) { + if (this.type === type && this.openBracketToken === openBracketToken && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayTypeSyntax(type, openBracketToken, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayTypeSyntax.create1 = function (type) { + return new ArrayTypeSyntax(type, TypeScript.Syntax.token(75 /* OpenBracketToken */), TypeScript.Syntax.token(76 /* CloseBracketToken */), false); + }; + + ArrayTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withType = function (type) { + return this.update(type, this.openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.type, openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.type, this.openBracketToken, closeBracketToken); + }; + + ArrayTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayTypeSyntax = ArrayTypeSyntax; + + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(name, typeArgumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.name = name; + this.typeArgumentList = typeArgumentList; + } + GenericTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitGenericType(this); + }; + + GenericTypeSyntax.prototype.kind = function () { + return 127 /* GenericType */; + }; + + GenericTypeSyntax.prototype.childCount = function () { + return 2; + }; + + GenericTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.name; + case 1: + return this.typeArgumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GenericTypeSyntax.prototype.isType = function () { + return true; + }; + + GenericTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + GenericTypeSyntax.prototype.isExpression = function () { + return true; + }; + + GenericTypeSyntax.prototype.update = function (name, typeArgumentList) { + if (this.name === name && this.typeArgumentList === typeArgumentList) { + return this; + } + + return new GenericTypeSyntax(name, typeArgumentList, this.parsedInStrictMode()); + }; + + GenericTypeSyntax.create1 = function (name) { + return new GenericTypeSyntax(name, TypeArgumentListSyntax.create1(), false); + }; + + GenericTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withName = function (name) { + return this.update(name, this.typeArgumentList); + }; + + GenericTypeSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(this.name, typeArgumentList); + }; + + GenericTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GenericTypeSyntax = GenericTypeSyntax; + + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(colonToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.type = type; + } + TypeAnnotationSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeAnnotation(this); + }; + + TypeAnnotationSyntax.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + + TypeAnnotationSyntax.prototype.childCount = function () { + return 2; + }; + + TypeAnnotationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.colonToken; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeAnnotationSyntax.prototype.update = function (colonToken, type) { + if (this.colonToken === colonToken && this.type === type) { + return this; + } + + return new TypeAnnotationSyntax(colonToken, type, this.parsedInStrictMode()); + }; + + TypeAnnotationSyntax.create1 = function (type) { + return new TypeAnnotationSyntax(TypeScript.Syntax.token(107 /* ColonToken */), type, false); + }; + + TypeAnnotationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withColonToken = function (colonToken) { + return this.update(colonToken, this.type); + }; + + TypeAnnotationSyntax.prototype.withType = function (type) { + return this.update(this.colonToken, type); + }; + + TypeAnnotationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeAnnotationSyntax = TypeAnnotationSyntax; + + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(openBraceToken, statements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.statements = statements; + this.closeBraceToken = closeBraceToken; + } + BlockSyntax.prototype.accept = function (visitor) { + return visitor.visitBlock(this); + }; + + BlockSyntax.prototype.kind = function () { + return 145 /* Block */; + }; + + BlockSyntax.prototype.childCount = function () { + return 3; + }; + + BlockSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.statements; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BlockSyntax.prototype.isStatement = function () { + return true; + }; + + BlockSyntax.prototype.isModuleElement = function () { + return true; + }; + + BlockSyntax.prototype.update = function (openBraceToken, statements, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.statements === statements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new BlockSyntax(openBraceToken, statements, closeBraceToken, this.parsedInStrictMode()); + }; + + BlockSyntax.create = function (openBraceToken, closeBraceToken) { + return new BlockSyntax(openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + BlockSyntax.create1 = function () { + return new BlockSyntax(TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + BlockSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatements = function (statements) { + return this.update(this.openBraceToken, statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + BlockSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.statements, closeBraceToken); + }; + + BlockSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BlockSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BlockSyntax = BlockSyntax; + + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.dotDotDotToken = dotDotDotToken; + this.publicOrPrivateKeyword = publicOrPrivateKeyword; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + ParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitParameter(this); + }; + + ParameterSyntax.prototype.kind = function () { + return 242 /* Parameter */; + }; + + ParameterSyntax.prototype.childCount = function () { + return 6; + }; + + ParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.dotDotDotToken; + case 1: + return this.publicOrPrivateKeyword; + case 2: + return this.identifier; + case 3: + return this.questionToken; + case 4: + return this.typeAnnotation; + case 5: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterSyntax.prototype.update = function (dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause) { + if (this.dotDotDotToken === dotDotDotToken && this.publicOrPrivateKeyword === publicOrPrivateKeyword && this.identifier === identifier && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + ParameterSyntax.create = function (identifier) { + return new ParameterSyntax(null, null, identifier, null, null, null, false); + }; + + ParameterSyntax.create1 = function (identifier) { + return new ParameterSyntax(null, null, identifier, null, null, null, false); + }; + + ParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withDotDotDotToken = function (dotDotDotToken) { + return this.update(dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withPublicOrPrivateKeyword = function (publicOrPrivateKeyword) { + return this.update(this.dotDotDotToken, publicOrPrivateKeyword, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, this.questionToken, typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, this.questionToken, this.typeAnnotation, equalsValueClause); + }; + + ParameterSyntax.prototype.isTypeScriptSpecific = function () { + if (this.dotDotDotToken !== null) { + return true; + } + if (this.publicOrPrivateKeyword !== null) { + return true; + } + if (this.questionToken !== null) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null) { + return true; + } + return false; + }; + return ParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterSyntax = ParameterSyntax; + + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(expression, dotToken, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.dotToken = dotToken; + this.name = name; + } + MemberAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberAccessExpression(this); + }; + + MemberAccessExpressionSyntax.prototype.kind = function () { + return 211 /* MemberAccessExpression */; + }; + + MemberAccessExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + MemberAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.dotToken; + case 2: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.update = function (expression, dotToken, name) { + if (this.expression === expression && this.dotToken === dotToken && this.name === name) { + return this; + } + + return new MemberAccessExpressionSyntax(expression, dotToken, name, this.parsedInStrictMode()); + }; + + MemberAccessExpressionSyntax.create1 = function (expression, name) { + return new MemberAccessExpressionSyntax(expression, TypeScript.Syntax.token(77 /* DotToken */), name, false); + }; + + MemberAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.expression, dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withName = function (name) { + return this.update(this.expression, this.dotToken, name); + }; + + MemberAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(kind, operand, operatorToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operand = operand; + this.operatorToken = operatorToken; + + this._kind = kind; + } + PostfixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPostfixUnaryExpression(this); + }; + + PostfixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PostfixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operand; + case 1: + return this.operatorToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PostfixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PostfixUnaryExpressionSyntax.prototype.update = function (kind, operand, operatorToken) { + if (this._kind === kind && this.operand === operand && this.operatorToken === operatorToken) { + return this; + } + + return new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, this.parsedInStrictMode()); + }; + + PostfixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.operand, operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.openBracketToken = openBracketToken; + this.argumentExpression = argumentExpression; + this.closeBracketToken = closeBracketToken; + } + ElementAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitElementAccessExpression(this); + }; + + ElementAccessExpressionSyntax.prototype.kind = function () { + return 220 /* ElementAccessExpression */; + }; + + ElementAccessExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ElementAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.openBracketToken; + case 2: + return this.argumentExpression; + case 3: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElementAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.update = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + if (this.expression === expression && this.openBracketToken === openBracketToken && this.argumentExpression === argumentExpression && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, this.parsedInStrictMode()); + }; + + ElementAccessExpressionSyntax.create1 = function (expression, argumentExpression) { + return new ElementAccessExpressionSyntax(expression, TypeScript.Syntax.token(75 /* OpenBracketToken */), argumentExpression, TypeScript.Syntax.token(76 /* CloseBracketToken */), false); + }; + + ElementAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.expression, openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withArgumentExpression = function (argumentExpression) { + return this.update(this.expression, this.openBracketToken, argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.expression, this.openBracketToken, this.argumentExpression, closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentExpression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.argumentList = argumentList; + } + InvocationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitInvocationExpression(this); + }; + + InvocationExpressionSyntax.prototype.kind = function () { + return 212 /* InvocationExpression */; + }; + + InvocationExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + InvocationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InvocationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.update = function (expression, argumentList) { + if (this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new InvocationExpressionSyntax(expression, argumentList, this.parsedInStrictMode()); + }; + + InvocationExpressionSyntax.create1 = function (expression) { + return new InvocationExpressionSyntax(expression, ArgumentListSyntax.create1(), false); + }; + + InvocationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.argumentList); + }; + + InvocationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.expression, argumentList); + }; + + InvocationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InvocationExpressionSyntax = InvocationExpressionSyntax; + + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(typeArgumentList, openParenToken, arguments, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeArgumentList = typeArgumentList; + this.openParenToken = openParenToken; + this.arguments = arguments; + this.closeParenToken = closeParenToken; + } + ArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitArgumentList(this); + }; + + ArgumentListSyntax.prototype.kind = function () { + return 225 /* ArgumentList */; + }; + + ArgumentListSyntax.prototype.childCount = function () { + return 4; + }; + + ArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeArgumentList; + case 1: + return this.openParenToken; + case 2: + return this.arguments; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArgumentListSyntax.prototype.update = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + if (this.typeArgumentList === typeArgumentList && this.openParenToken === openParenToken && this.arguments === _arguments && this.closeParenToken === closeParenToken) { + return this; + } + + return new ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, this.parsedInStrictMode()); + }; + + ArgumentListSyntax.create = function (openParenToken, closeParenToken) { + return new ArgumentListSyntax(null, openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ArgumentListSyntax.create1 = function () { + return new ArgumentListSyntax(null, TypeScript.Syntax.token(73 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(typeArgumentList, this.openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.typeArgumentList, openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArguments = function (_arguments) { + return this.update(this.typeArgumentList, this.openParenToken, _arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArgument = function (_argument) { + return this.withArguments(TypeScript.Syntax.separatedList([_argument])); + }; + + ArgumentListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.typeArgumentList, this.openParenToken, this.arguments, closeParenToken); + }; + + ArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeArgumentList !== null && this.typeArgumentList.isTypeScriptSpecific()) { + return true; + } + if (this.arguments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArgumentListSyntax = ArgumentListSyntax; + + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(kind, left, operatorToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.operatorToken = operatorToken; + this.right = right; + + this._kind = kind; + } + BinaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitBinaryExpression(this); + }; + + BinaryExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + BinaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.operatorToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BinaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + BinaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + BinaryExpressionSyntax.prototype.update = function (kind, left, operatorToken, right) { + if (this._kind === kind && this.left === left && this.operatorToken === operatorToken && this.right === right) { + return this; + } + + return new BinaryExpressionSyntax(kind, left, operatorToken, right, this.parsedInStrictMode()); + }; + + BinaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withLeft = function (left) { + return this.update(this._kind, left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.left, operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withRight = function (right) { + return this.update(this._kind, this.left, this.operatorToken, right); + }; + + BinaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.left.isTypeScriptSpecific()) { + return true; + } + if (this.right.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BinaryExpressionSyntax = BinaryExpressionSyntax; + + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.condition = condition; + this.questionToken = questionToken; + this.whenTrue = whenTrue; + this.colonToken = colonToken; + this.whenFalse = whenFalse; + } + ConditionalExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitConditionalExpression(this); + }; + + ConditionalExpressionSyntax.prototype.kind = function () { + return 185 /* ConditionalExpression */; + }; + + ConditionalExpressionSyntax.prototype.childCount = function () { + return 5; + }; + + ConditionalExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.condition; + case 1: + return this.questionToken; + case 2: + return this.whenTrue; + case 3: + return this.colonToken; + case 4: + return this.whenFalse; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConditionalExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ConditionalExpressionSyntax.prototype.update = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + if (this.condition === condition && this.questionToken === questionToken && this.whenTrue === whenTrue && this.colonToken === colonToken && this.whenFalse === whenFalse) { + return this; + } + + return new ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, this.parsedInStrictMode()); + }; + + ConditionalExpressionSyntax.create1 = function (condition, whenTrue, whenFalse) { + return new ConditionalExpressionSyntax(condition, TypeScript.Syntax.token(106 /* QuestionToken */), whenTrue, TypeScript.Syntax.token(107 /* ColonToken */), whenFalse, false); + }; + + ConditionalExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withCondition = function (condition) { + return this.update(condition, this.questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.condition, questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenTrue = function (whenTrue) { + return this.update(this.condition, this.questionToken, whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.condition, this.questionToken, this.whenTrue, colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenFalse = function (whenFalse) { + return this.update(this.condition, this.questionToken, this.whenTrue, this.colonToken, whenFalse); + }; + + ConditionalExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.whenTrue.isTypeScriptSpecific()) { + return true; + } + if (this.whenFalse.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(newKeyword, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.callSignature = callSignature; + } + ConstructSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructSignature(this); + }; + + ConstructSignatureSyntax.prototype.kind = function () { + return 142 /* ConstructSignature */; + }; + + ConstructSignatureSyntax.prototype.childCount = function () { + return 2; + }; + + ConstructSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + ConstructSignatureSyntax.prototype.update = function (newKeyword, callSignature) { + if (this.newKeyword === newKeyword && this.callSignature === callSignature) { + return this; + } + + return new ConstructSignatureSyntax(newKeyword, callSignature, this.parsedInStrictMode()); + }; + + ConstructSignatureSyntax.create1 = function () { + return new ConstructSignatureSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), CallSignatureSyntax.create1(), false); + }; + + ConstructSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.callSignature); + }; + + ConstructSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.newKeyword, callSignature); + }; + + ConstructSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructSignatureSyntax = ConstructSignatureSyntax; + + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(propertyName, questionToken, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + } + MethodSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitMethodSignature(this); + }; + + MethodSignatureSyntax.prototype.kind = function () { + return 144 /* MethodSignature */; + }; + + MethodSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + MethodSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MethodSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + MethodSignatureSyntax.prototype.update = function (propertyName, questionToken, callSignature) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.callSignature === callSignature) { + return this; + } + + return new MethodSignatureSyntax(propertyName, questionToken, callSignature, this.parsedInStrictMode()); + }; + + MethodSignatureSyntax.create = function (propertyName, callSignature) { + return new MethodSignatureSyntax(propertyName, null, callSignature, false); + }; + + MethodSignatureSyntax.create1 = function (propertyName) { + return new MethodSignatureSyntax(propertyName, null, CallSignatureSyntax.create1(), false); + }; + + MethodSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, this.questionToken, callSignature); + }; + + MethodSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MethodSignatureSyntax = MethodSignatureSyntax; + + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.parameter = parameter; + this.closeBracketToken = closeBracketToken; + this.typeAnnotation = typeAnnotation; + } + IndexSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexSignature(this); + }; + + IndexSignatureSyntax.prototype.kind = function () { + return 143 /* IndexSignature */; + }; + + IndexSignatureSyntax.prototype.childCount = function () { + return 4; + }; + + IndexSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.parameter; + case 2: + return this.closeBracketToken; + case 3: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + IndexSignatureSyntax.prototype.isClassElement = function () { + return true; + }; + + IndexSignatureSyntax.prototype.update = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + if (this.openBracketToken === openBracketToken && this.parameter === parameter && this.closeBracketToken === closeBracketToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, this.parsedInStrictMode()); + }; + + IndexSignatureSyntax.create = function (openBracketToken, parameter, closeBracketToken) { + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, null, false); + }; + + IndexSignatureSyntax.create1 = function (parameter) { + return new IndexSignatureSyntax(TypeScript.Syntax.token(75 /* OpenBracketToken */), parameter, TypeScript.Syntax.token(76 /* CloseBracketToken */), null, false); + }; + + IndexSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withParameter = function (parameter) { + return this.update(this.openBracketToken, parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.parameter, closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.openBracketToken, this.parameter, this.closeBracketToken, typeAnnotation); + }; + + IndexSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexSignatureSyntax = IndexSignatureSyntax; + + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + } + PropertySignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitPropertySignature(this); + }; + + PropertySignatureSyntax.prototype.kind = function () { + return 140 /* PropertySignature */; + }; + + PropertySignatureSyntax.prototype.childCount = function () { + return 3; + }; + + PropertySignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PropertySignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + PropertySignatureSyntax.prototype.update = function (propertyName, questionToken, typeAnnotation) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, this.parsedInStrictMode()); + }; + + PropertySignatureSyntax.create = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.create1 = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, this.questionToken, typeAnnotation); + }; + + PropertySignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertySignatureSyntax = PropertySignatureSyntax; + + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + } + CallSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitCallSignature(this); + }; + + CallSignatureSyntax.prototype.kind = function () { + return 141 /* CallSignature */; + }; + + CallSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + CallSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CallSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + CallSignatureSyntax.prototype.update = function (typeParameterList, parameterList, typeAnnotation) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, this.parsedInStrictMode()); + }; + + CallSignatureSyntax.create = function (parameterList) { + return new CallSignatureSyntax(null, parameterList, null, false); + }; + + CallSignatureSyntax.create1 = function () { + return new CallSignatureSyntax(null, ParameterListSyntax.create1(), null, false); + }; + + CallSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.typeParameterList, this.parameterList, typeAnnotation); + }; + + CallSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeParameterList !== null) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + return false; + }; + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CallSignatureSyntax = CallSignatureSyntax; + + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(openParenToken, parameters, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.parameters = parameters; + this.closeParenToken = closeParenToken; + } + ParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitParameterList(this); + }; + + ParameterListSyntax.prototype.kind = function () { + return 226 /* ParameterList */; + }; + + ParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + ParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.parameters; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterListSyntax.prototype.update = function (openParenToken, parameters, closeParenToken) { + if (this.openParenToken === openParenToken && this.parameters === parameters && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParameterListSyntax(openParenToken, parameters, closeParenToken, this.parsedInStrictMode()); + }; + + ParameterListSyntax.create = function (openParenToken, closeParenToken) { + return new ParameterListSyntax(openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ParameterListSyntax.create1 = function () { + return new ParameterListSyntax(TypeScript.Syntax.token(73 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameters = function (parameters) { + return this.update(this.openParenToken, parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameter = function (parameter) { + return this.withParameters(TypeScript.Syntax.separatedList([parameter])); + }; + + ParameterListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.parameters, closeParenToken); + }; + + ParameterListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameters.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterListSyntax = ParameterListSyntax; + + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeParameters = typeParameters; + this.greaterThanToken = greaterThanToken; + } + TypeParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameterList(this); + }; + + TypeParameterListSyntax.prototype.kind = function () { + return 228 /* TypeParameterList */; + }; + + TypeParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeParameters; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterListSyntax.prototype.update = function (lessThanToken, typeParameters, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeParameters === typeParameters && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeParameterListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeParameterListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeParameterListSyntax.create1 = function () { + return new TypeParameterListSyntax(TypeScript.Syntax.token(81 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(82 /* GreaterThanToken */), false); + }; + + TypeParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameters = function (typeParameters) { + return this.update(this.lessThanToken, typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameter = function (typeParameter) { + return this.withTypeParameters(TypeScript.Syntax.separatedList([typeParameter])); + }; + + TypeParameterListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeParameters, greaterThanToken); + }; + + TypeParameterListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterListSyntax = TypeParameterListSyntax; + + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(identifier, constraint, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.constraint = constraint; + } + TypeParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameter(this); + }; + + TypeParameterSyntax.prototype.kind = function () { + return 236 /* TypeParameter */; + }; + + TypeParameterSyntax.prototype.childCount = function () { + return 2; + }; + + TypeParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.constraint; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterSyntax.prototype.update = function (identifier, constraint) { + if (this.identifier === identifier && this.constraint === constraint) { + return this; + } + + return new TypeParameterSyntax(identifier, constraint, this.parsedInStrictMode()); + }; + + TypeParameterSyntax.create = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.create1 = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.constraint); + }; + + TypeParameterSyntax.prototype.withConstraint = function (constraint) { + return this.update(this.identifier, constraint); + }; + + TypeParameterSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterSyntax = TypeParameterSyntax; + + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(extendsKeyword, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsKeyword = extendsKeyword; + this.type = type; + } + ConstraintSyntax.prototype.accept = function (visitor) { + return visitor.visitConstraint(this); + }; + + ConstraintSyntax.prototype.kind = function () { + return 237 /* Constraint */; + }; + + ConstraintSyntax.prototype.childCount = function () { + return 2; + }; + + ConstraintSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsKeyword; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstraintSyntax.prototype.update = function (extendsKeyword, type) { + if (this.extendsKeyword === extendsKeyword && this.type === type) { + return this; + } + + return new ConstraintSyntax(extendsKeyword, type, this.parsedInStrictMode()); + }; + + ConstraintSyntax.create1 = function (type) { + return new ConstraintSyntax(TypeScript.Syntax.token(48 /* ExtendsKeyword */), type, false); + }; + + ConstraintSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withExtendsKeyword = function (extendsKeyword) { + return this.update(extendsKeyword, this.type); + }; + + ConstraintSyntax.prototype.withType = function (type) { + return this.update(this.extendsKeyword, type); + }; + + ConstraintSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstraintSyntax = ConstraintSyntax; + + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(elseKeyword, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.elseKeyword = elseKeyword; + this.statement = statement; + } + ElseClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitElseClause(this); + }; + + ElseClauseSyntax.prototype.kind = function () { + return 233 /* ElseClause */; + }; + + ElseClauseSyntax.prototype.childCount = function () { + return 2; + }; + + ElseClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.elseKeyword; + case 1: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElseClauseSyntax.prototype.update = function (elseKeyword, statement) { + if (this.elseKeyword === elseKeyword && this.statement === statement) { + return this; + } + + return new ElseClauseSyntax(elseKeyword, statement, this.parsedInStrictMode()); + }; + + ElseClauseSyntax.create1 = function (statement) { + return new ElseClauseSyntax(TypeScript.Syntax.token(23 /* ElseKeyword */), statement, false); + }; + + ElseClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withElseKeyword = function (elseKeyword) { + return this.update(elseKeyword, this.statement); + }; + + ElseClauseSyntax.prototype.withStatement = function (statement) { + return this.update(this.elseKeyword, statement); + }; + + ElseClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElseClauseSyntax = ElseClauseSyntax; + + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.ifKeyword = ifKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + this.elseClause = elseClause; + } + IfStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitIfStatement(this); + }; + + IfStatementSyntax.prototype.kind = function () { + return 146 /* IfStatement */; + }; + + IfStatementSyntax.prototype.childCount = function () { + return 6; + }; + + IfStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.ifKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + case 5: + return this.elseClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IfStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IfStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IfStatementSyntax.prototype.update = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + if (this.ifKeyword === ifKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement && this.elseClause === elseClause) { + return this; + } + + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, this.parsedInStrictMode()); + }; + + IfStatementSyntax.create = function (ifKeyword, openParenToken, condition, closeParenToken, statement) { + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, null, false); + }; + + IfStatementSyntax.create1 = function (condition, statement) { + return new IfStatementSyntax(TypeScript.Syntax.token(28 /* IfKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, null, false); + }; + + IfStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withIfKeyword = function (ifKeyword) { + return this.update(ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.ifKeyword, openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.ifKeyword, this.openParenToken, condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withElseClause = function (elseClause) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, elseClause); + }; + + IfStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.elseClause !== null && this.elseClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IfStatementSyntax = IfStatementSyntax; + + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ExpressionStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitExpressionStatement(this); + }; + + ExpressionStatementSyntax.prototype.kind = function () { + return 148 /* ExpressionStatement */; + }; + + ExpressionStatementSyntax.prototype.childCount = function () { + return 2; + }; + + ExpressionStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExpressionStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.update = function (expression, semicolonToken) { + if (this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExpressionStatementSyntax(expression, semicolonToken, this.parsedInStrictMode()); + }; + + ExpressionStatementSyntax.create1 = function (expression) { + return new ExpressionStatementSyntax(expression, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ExpressionStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.semicolonToken); + }; + + ExpressionStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.expression, semicolonToken); + }; + + ExpressionStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExpressionStatementSyntax = ExpressionStatementSyntax; + + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.constructorKeyword = constructorKeyword; + this.parameterList = parameterList; + this.block = block; + this.semicolonToken = semicolonToken; + } + ConstructorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorDeclaration(this); + }; + + ConstructorDeclarationSyntax.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + + ConstructorDeclarationSyntax.prototype.childCount = function () { + return 4; + }; + + ConstructorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.constructorKeyword; + case 1: + return this.parameterList; + case 2: + return this.block; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + ConstructorDeclarationSyntax.prototype.update = function (constructorKeyword, parameterList, block, semicolonToken) { + if (this.constructorKeyword === constructorKeyword && this.parameterList === parameterList && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, this.parsedInStrictMode()); + }; + + ConstructorDeclarationSyntax.create = function (constructorKeyword, parameterList) { + return new ConstructorDeclarationSyntax(constructorKeyword, parameterList, null, null, false); + }; + + ConstructorDeclarationSyntax.create1 = function () { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.token(63 /* ConstructorKeyword */), ParameterListSyntax.create1(), null, null, false); + }; + + ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { + return this.update(constructorKeyword, this.parameterList, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.constructorKeyword, parameterList, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.constructorKeyword, this.parameterList, block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.constructorKeyword, this.parameterList, this.block, semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + MemberFunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberFunctionDeclaration(this); + }; + + MemberFunctionDeclarationSyntax.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + + MemberFunctionDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + MemberFunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.propertyName; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberFunctionDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.update = function (modifiers, propertyName, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.propertyName === propertyName && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + MemberFunctionDeclarationSyntax.create = function (propertyName, callSignature) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, callSignature, null, null, false); + }; + + MemberFunctionDeclarationSyntax.create1 = function (propertyName) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, CallSignatureSyntax.create1(), null, null, false); + }; + + MemberFunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberFunctionDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.propertyName, callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.propertyName, this.callSignature, block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.propertyName, this.callSignature, this.block, semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + + var MemberAccessorDeclarationSyntax = (function (_super) { + __extends(MemberAccessorDeclarationSyntax, _super); + function MemberAccessorDeclarationSyntax(modifiers, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + } + MemberAccessorDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberAccessorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberAccessorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberAccessorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessorDeclarationSyntax = MemberAccessorDeclarationSyntax; + + var GetMemberAccessorDeclarationSyntax = (function (_super) { + __extends(GetMemberAccessorDeclarationSyntax, _super); + function GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, modifiers, propertyName, parameterList, block, parsedInStrictMode); + this.getKeyword = getKeyword; + this.typeAnnotation = typeAnnotation; + } + GetMemberAccessorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitGetMemberAccessorDeclaration(this); + }; + + GetMemberAccessorDeclarationSyntax.prototype.kind = function () { + return 138 /* GetMemberAccessorDeclaration */; + }; + + GetMemberAccessorDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + GetMemberAccessorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.getKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetMemberAccessorDeclarationSyntax.prototype.update = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + if (this.modifiers === modifiers && this.getKeyword === getKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetMemberAccessorDeclarationSyntax.create = function (getKeyword, propertyName, parameterList, block) { + return new GetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, getKeyword, propertyName, parameterList, null, block, false); + }; + + GetMemberAccessorDeclarationSyntax.create1 = function (propertyName) { + return new GetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(65 /* GetKeyword */), propertyName, ParameterListSyntax.create1(), null, BlockSyntax.create1(), false); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(this.modifiers, getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.getKeyword, propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GetMemberAccessorDeclarationSyntax; + })(MemberAccessorDeclarationSyntax); + TypeScript.GetMemberAccessorDeclarationSyntax = GetMemberAccessorDeclarationSyntax; + + var SetMemberAccessorDeclarationSyntax = (function (_super) { + __extends(SetMemberAccessorDeclarationSyntax, _super); + function SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, modifiers, propertyName, parameterList, block, parsedInStrictMode); + this.setKeyword = setKeyword; + } + SetMemberAccessorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitSetMemberAccessorDeclaration(this); + }; + + SetMemberAccessorDeclarationSyntax.prototype.kind = function () { + return 139 /* SetMemberAccessorDeclaration */; + }; + + SetMemberAccessorDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + SetMemberAccessorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.setKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetMemberAccessorDeclarationSyntax.prototype.update = function (modifiers, setKeyword, propertyName, parameterList, block) { + if (this.modifiers === modifiers && this.setKeyword === setKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.block === block) { + return this; + } + + return new SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, this.parsedInStrictMode()); + }; + + SetMemberAccessorDeclarationSyntax.create = function (setKeyword, propertyName, parameterList, block) { + return new SetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, setKeyword, propertyName, parameterList, block, false); + }; + + SetMemberAccessorDeclarationSyntax.create1 = function (propertyName) { + return new SetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(69 /* SetKeyword */), propertyName, ParameterListSyntax.create1(), BlockSyntax.create1(), false); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(this.modifiers, setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.setKeyword, propertyName, this.parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, this.parameterList, block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SetMemberAccessorDeclarationSyntax; + })(MemberAccessorDeclarationSyntax); + TypeScript.SetMemberAccessorDeclarationSyntax = SetMemberAccessorDeclarationSyntax; + + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + this.semicolonToken = semicolonToken; + } + MemberVariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberVariableDeclaration(this); + }; + + MemberVariableDeclarationSyntax.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + + MemberVariableDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + MemberVariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclarator; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberVariableDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.update = function (modifiers, variableDeclarator, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclarator === variableDeclarator && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, this.parsedInStrictMode()); + }; + + MemberVariableDeclarationSyntax.create = function (variableDeclarator, semicolonToken) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, semicolonToken, false); + }; + + MemberVariableDeclarationSyntax.create1 = function (variableDeclarator) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + MemberVariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberVariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.update(this.modifiers, variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclarator, semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(throwKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.throwKeyword = throwKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ThrowStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitThrowStatement(this); + }; + + ThrowStatementSyntax.prototype.kind = function () { + return 156 /* ThrowStatement */; + }; + + ThrowStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ThrowStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.throwKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ThrowStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.update = function (throwKeyword, expression, semicolonToken) { + if (this.throwKeyword === throwKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ThrowStatementSyntax(throwKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ThrowStatementSyntax.create1 = function (expression) { + return new ThrowStatementSyntax(TypeScript.Syntax.token(36 /* ThrowKeyword */), expression, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ThrowStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withThrowKeyword = function (throwKeyword) { + return this.update(throwKeyword, this.expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.throwKeyword, expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.throwKeyword, this.expression, semicolonToken); + }; + + ThrowStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ThrowStatementSyntax = ThrowStatementSyntax; + + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(returnKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.returnKeyword = returnKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ReturnStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitReturnStatement(this); + }; + + ReturnStatementSyntax.prototype.kind = function () { + return 149 /* ReturnStatement */; + }; + + ReturnStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ReturnStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.returnKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ReturnStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.update = function (returnKeyword, expression, semicolonToken) { + if (this.returnKeyword === returnKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ReturnStatementSyntax(returnKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ReturnStatementSyntax.create = function (returnKeyword, semicolonToken) { + return new ReturnStatementSyntax(returnKeyword, null, semicolonToken, false); + }; + + ReturnStatementSyntax.create1 = function () { + return new ReturnStatementSyntax(TypeScript.Syntax.token(33 /* ReturnKeyword */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ReturnStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withReturnKeyword = function (returnKeyword) { + return this.update(returnKeyword, this.expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.returnKeyword, expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.returnKeyword, this.expression, semicolonToken); + }; + + ReturnStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression !== null && this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ReturnStatementSyntax = ReturnStatementSyntax; + + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.expression = expression; + this.argumentList = argumentList; + } + ObjectCreationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectCreationExpression(this); + }; + + ObjectCreationExpressionSyntax.prototype.kind = function () { + return 215 /* ObjectCreationExpression */; + }; + + ObjectCreationExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectCreationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.expression; + case 2: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectCreationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.update = function (newKeyword, expression, argumentList) { + if (this.newKeyword === newKeyword && this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, this.parsedInStrictMode()); + }; + + ObjectCreationExpressionSyntax.create = function (newKeyword, expression) { + return new ObjectCreationExpressionSyntax(newKeyword, expression, null, false); + }; + + ObjectCreationExpressionSyntax.create1 = function (expression) { + return new ObjectCreationExpressionSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), expression, null, false); + }; + + ObjectCreationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.newKeyword, expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.newKeyword, this.expression, argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList !== null && this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.switchKeyword = switchKeyword; + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.openBraceToken = openBraceToken; + this.switchClauses = switchClauses; + this.closeBraceToken = closeBraceToken; + } + SwitchStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitSwitchStatement(this); + }; + + SwitchStatementSyntax.prototype.kind = function () { + return 150 /* SwitchStatement */; + }; + + SwitchStatementSyntax.prototype.childCount = function () { + return 7; + }; + + SwitchStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.switchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.expression; + case 3: + return this.closeParenToken; + case 4: + return this.openBraceToken; + case 5: + return this.switchClauses; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SwitchStatementSyntax.prototype.isStatement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.update = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + if (this.switchKeyword === switchKeyword && this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken && this.openBraceToken === openBraceToken && this.switchClauses === switchClauses && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, this.parsedInStrictMode()); + }; + + SwitchStatementSyntax.create = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, closeBraceToken) { + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + SwitchStatementSyntax.create1 = function (expression) { + return new SwitchStatementSyntax(TypeScript.Syntax.token(34 /* SwitchKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), expression, TypeScript.Syntax.token(74 /* CloseParenToken */), TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + SwitchStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withSwitchKeyword = function (switchKeyword) { + return this.update(switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.switchKeyword, openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.switchKeyword, this.openParenToken, expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClauses = function (switchClauses) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClause = function (switchClause) { + return this.withSwitchClauses(TypeScript.Syntax.list([switchClause])); + }; + + SwitchStatementSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, closeBraceToken); + }; + + SwitchStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.switchClauses.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchStatementSyntax = SwitchStatementSyntax; + + var SwitchClauseSyntax = (function (_super) { + __extends(SwitchClauseSyntax, _super); + function SwitchClauseSyntax(colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.statements = statements; + } + SwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + SwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return SwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchClauseSyntax = SwitchClauseSyntax; + + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, parsedInStrictMode) { + _super.call(this, colonToken, statements, parsedInStrictMode); + this.caseKeyword = caseKeyword; + this.expression = expression; + } + CaseSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCaseSwitchClause(this); + }; + + CaseSwitchClauseSyntax.prototype.kind = function () { + return 231 /* CaseSwitchClause */; + }; + + CaseSwitchClauseSyntax.prototype.childCount = function () { + return 4; + }; + + CaseSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.caseKeyword; + case 1: + return this.expression; + case 2: + return this.colonToken; + case 3: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CaseSwitchClauseSyntax.prototype.update = function (caseKeyword, expression, colonToken, statements) { + if (this.caseKeyword === caseKeyword && this.expression === expression && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, this.parsedInStrictMode()); + }; + + CaseSwitchClauseSyntax.create = function (caseKeyword, expression, colonToken) { + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.create1 = function (expression) { + return new CaseSwitchClauseSyntax(TypeScript.Syntax.token(16 /* CaseKeyword */), expression, TypeScript.Syntax.token(107 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withCaseKeyword = function (caseKeyword) { + return this.update(caseKeyword, this.expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withExpression = function (expression) { + return this.update(this.caseKeyword, expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.caseKeyword, this.expression, colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.caseKeyword, this.expression, this.colonToken, statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + CaseSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CaseSwitchClauseSyntax; + })(SwitchClauseSyntax); + TypeScript.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, parsedInStrictMode) { + _super.call(this, colonToken, statements, parsedInStrictMode); + this.defaultKeyword = defaultKeyword; + } + DefaultSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitDefaultSwitchClause(this); + }; + + DefaultSwitchClauseSyntax.prototype.kind = function () { + return 232 /* DefaultSwitchClause */; + }; + + DefaultSwitchClauseSyntax.prototype.childCount = function () { + return 3; + }; + + DefaultSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.defaultKeyword; + case 1: + return this.colonToken; + case 2: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DefaultSwitchClauseSyntax.prototype.update = function (defaultKeyword, colonToken, statements) { + if (this.defaultKeyword === defaultKeyword && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, this.parsedInStrictMode()); + }; + + DefaultSwitchClauseSyntax.create = function (defaultKeyword, colonToken) { + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.create1 = function () { + return new DefaultSwitchClauseSyntax(TypeScript.Syntax.token(20 /* DefaultKeyword */), TypeScript.Syntax.token(107 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withDefaultKeyword = function (defaultKeyword) { + return this.update(defaultKeyword, this.colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.defaultKeyword, colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.defaultKeyword, this.colonToken, statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + DefaultSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DefaultSwitchClauseSyntax; + })(SwitchClauseSyntax); + TypeScript.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(breakKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.breakKeyword = breakKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + BreakStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitBreakStatement(this); + }; + + BreakStatementSyntax.prototype.kind = function () { + return 151 /* BreakStatement */; + }; + + BreakStatementSyntax.prototype.childCount = function () { + return 3; + }; + + BreakStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.breakKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BreakStatementSyntax.prototype.isStatement = function () { + return true; + }; + + BreakStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + BreakStatementSyntax.prototype.update = function (breakKeyword, identifier, semicolonToken) { + if (this.breakKeyword === breakKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new BreakStatementSyntax(breakKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + BreakStatementSyntax.create = function (breakKeyword, semicolonToken) { + return new BreakStatementSyntax(breakKeyword, null, semicolonToken, false); + }; + + BreakStatementSyntax.create1 = function () { + return new BreakStatementSyntax(TypeScript.Syntax.token(15 /* BreakKeyword */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + BreakStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withBreakKeyword = function (breakKeyword) { + return this.update(breakKeyword, this.identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.breakKeyword, identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.breakKeyword, this.identifier, semicolonToken); + }; + + BreakStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BreakStatementSyntax = BreakStatementSyntax; + + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.continueKeyword = continueKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ContinueStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitContinueStatement(this); + }; + + ContinueStatementSyntax.prototype.kind = function () { + return 152 /* ContinueStatement */; + }; + + ContinueStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ContinueStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.continueKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ContinueStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.update = function (continueKeyword, identifier, semicolonToken) { + if (this.continueKeyword === continueKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ContinueStatementSyntax.create = function (continueKeyword, semicolonToken) { + return new ContinueStatementSyntax(continueKeyword, null, semicolonToken, false); + }; + + ContinueStatementSyntax.create1 = function () { + return new ContinueStatementSyntax(TypeScript.Syntax.token(18 /* ContinueKeyword */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ContinueStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withContinueKeyword = function (continueKeyword) { + return this.update(continueKeyword, this.identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.continueKeyword, identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.continueKeyword, this.identifier, semicolonToken); + }; + + ContinueStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ContinueStatementSyntax = ContinueStatementSyntax; + + var IterationStatementSyntax = (function (_super) { + __extends(IterationStatementSyntax, _super); + function IterationStatementSyntax(openParenToken, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + IterationStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IterationStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IterationStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IterationStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IterationStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return IterationStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IterationStatementSyntax = IterationStatementSyntax; + + var BaseForStatementSyntax = (function (_super) { + __extends(BaseForStatementSyntax, _super); + function BaseForStatementSyntax(forKeyword, openParenToken, variableDeclaration, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, openParenToken, closeParenToken, statement, parsedInStrictMode); + this.forKeyword = forKeyword; + this.variableDeclaration = variableDeclaration; + } + BaseForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BaseForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BaseForStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BaseForStatementSyntax; + })(IterationStatementSyntax); + TypeScript.BaseForStatementSyntax = BaseForStatementSyntax; + + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, forKeyword, openParenToken, variableDeclaration, closeParenToken, statement, parsedInStrictMode); + this.initializer = initializer; + this.firstSemicolonToken = firstSemicolonToken; + this.condition = condition; + this.secondSemicolonToken = secondSemicolonToken; + this.incrementor = incrementor; + } + ForStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForStatement(this); + }; + + ForStatementSyntax.prototype.kind = function () { + return 153 /* ForStatement */; + }; + + ForStatementSyntax.prototype.childCount = function () { + return 10; + }; + + ForStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.initializer; + case 4: + return this.firstSemicolonToken; + case 5: + return this.condition; + case 6: + return this.secondSemicolonToken; + case 7: + return this.incrementor; + case 8: + return this.closeParenToken; + case 9: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.initializer === initializer && this.firstSemicolonToken === firstSemicolonToken && this.condition === condition && this.secondSemicolonToken === secondSemicolonToken && this.incrementor === incrementor && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForStatementSyntax.create = function (forKeyword, openParenToken, firstSemicolonToken, secondSemicolonToken, closeParenToken, statement) { + return new ForStatementSyntax(forKeyword, openParenToken, null, null, firstSemicolonToken, null, secondSemicolonToken, null, closeParenToken, statement, false); + }; + + ForStatementSyntax.create1 = function (statement) { + return new ForStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), null, null, TypeScript.Syntax.token(79 /* SemicolonToken */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), null, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + ForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withInitializer = function (initializer) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withFirstSemicolonToken = function (firstSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withSecondSemicolonToken = function (secondSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withIncrementor = function (incrementor) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, statement); + }; + + ForStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.initializer !== null && this.initializer.isTypeScriptSpecific()) { + return true; + } + if (this.condition !== null && this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.incrementor !== null && this.incrementor.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForStatementSyntax; + })(BaseForStatementSyntax); + TypeScript.ForStatementSyntax = ForStatementSyntax; + + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, forKeyword, openParenToken, variableDeclaration, closeParenToken, statement, parsedInStrictMode); + this.left = left; + this.inKeyword = inKeyword; + this.expression = expression; + } + ForInStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForInStatement(this); + }; + + ForInStatementSyntax.prototype.kind = function () { + return 154 /* ForInStatement */; + }; + + ForInStatementSyntax.prototype.childCount = function () { + return 8; + }; + + ForInStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.left; + case 4: + return this.inKeyword; + case 5: + return this.expression; + case 6: + return this.closeParenToken; + case 7: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForInStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.left === left && this.inKeyword === inKeyword && this.expression === expression && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForInStatementSyntax.create = function (forKeyword, openParenToken, inKeyword, expression, closeParenToken, statement) { + return new ForInStatementSyntax(forKeyword, openParenToken, null, null, inKeyword, expression, closeParenToken, statement, false); + }; + + ForInStatementSyntax.create1 = function (expression, statement) { + return new ForInStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), null, null, TypeScript.Syntax.token(29 /* InKeyword */), expression, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + ForInStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withLeft = function (left) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withInKeyword = function (inKeyword) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, statement); + }; + + ForInStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.left !== null && this.left.isTypeScriptSpecific()) { + return true; + } + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForInStatementSyntax; + })(BaseForStatementSyntax); + TypeScript.ForInStatementSyntax = ForInStatementSyntax; + + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, openParenToken, closeParenToken, statement, parsedInStrictMode); + this.whileKeyword = whileKeyword; + this.condition = condition; + } + WhileStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWhileStatement(this); + }; + + WhileStatementSyntax.prototype.kind = function () { + return 157 /* WhileStatement */; + }; + + WhileStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WhileStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.whileKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WhileStatementSyntax.prototype.update = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WhileStatementSyntax.create1 = function (condition, statement) { + return new WhileStatementSyntax(TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + WhileStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WhileStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WhileStatementSyntax; + })(IterationStatementSyntax); + TypeScript.WhileStatementSyntax = WhileStatementSyntax; + + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.withKeyword = withKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WithStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWithStatement(this); + }; + + WithStatementSyntax.prototype.kind = function () { + return 162 /* WithStatement */; + }; + + WithStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WithStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.withKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WithStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WithStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WithStatementSyntax.prototype.update = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.withKeyword === withKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WithStatementSyntax.create1 = function (condition, statement) { + return new WithStatementSyntax(TypeScript.Syntax.token(43 /* WithKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + WithStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withWithKeyword = function (withKeyword) { + return this.update(withKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.withKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.withKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.withKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.withKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WithStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WithStatementSyntax = WithStatementSyntax; + + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.enumKeyword = enumKeyword; + this.identifier = identifier; + this.openBraceToken = openBraceToken; + this.enumElements = enumElements; + this.closeBraceToken = closeBraceToken; + } + EnumDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumDeclaration(this); + }; + + EnumDeclarationSyntax.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + + EnumDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + EnumDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.enumKeyword; + case 2: + return this.identifier; + case 3: + return this.openBraceToken; + case 4: + return this.enumElements; + case 5: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + EnumDeclarationSyntax.prototype.update = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + if (this.modifiers === modifiers && this.enumKeyword === enumKeyword && this.identifier === identifier && this.openBraceToken === openBraceToken && this.enumElements === enumElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, this.parsedInStrictMode()); + }; + + EnumDeclarationSyntax.create = function (enumKeyword, identifier, openBraceToken, closeBraceToken) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, enumKeyword, identifier, openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + EnumDeclarationSyntax.create1 = function (identifier) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(46 /* EnumKeyword */), identifier, TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + EnumDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + EnumDeclarationSyntax.prototype.withEnumKeyword = function (enumKeyword) { + return this.update(this.modifiers, enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.enumKeyword, identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElements = function (enumElements) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElement = function (enumElement) { + return this.withEnumElements(TypeScript.Syntax.separatedList([enumElement])); + }; + + EnumDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumDeclarationSyntax = EnumDeclarationSyntax; + + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(propertyName, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + } + EnumElementSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumElement(this); + }; + + EnumElementSyntax.prototype.kind = function () { + return 243 /* EnumElement */; + }; + + EnumElementSyntax.prototype.childCount = function () { + return 2; + }; + + EnumElementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumElementSyntax.prototype.update = function (propertyName, equalsValueClause) { + if (this.propertyName === propertyName && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new EnumElementSyntax(propertyName, equalsValueClause, this.parsedInStrictMode()); + }; + + EnumElementSyntax.create = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.create1 = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.equalsValueClause); + }; + + EnumElementSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, equalsValueClause); + }; + + EnumElementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumElementSyntax = EnumElementSyntax; + + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.type = type; + this.greaterThanToken = greaterThanToken; + this.expression = expression; + } + CastExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitCastExpression(this); + }; + + CastExpressionSyntax.prototype.kind = function () { + return 219 /* CastExpression */; + }; + + CastExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + CastExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.type; + case 2: + return this.greaterThanToken; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CastExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.update = function (lessThanToken, type, greaterThanToken, expression) { + if (this.lessThanToken === lessThanToken && this.type === type && this.greaterThanToken === greaterThanToken && this.expression === expression) { + return this; + } + + return new CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, this.parsedInStrictMode()); + }; + + CastExpressionSyntax.create1 = function (type, expression) { + return new CastExpressionSyntax(TypeScript.Syntax.token(81 /* LessThanToken */), type, TypeScript.Syntax.token(82 /* GreaterThanToken */), expression, false); + }; + + CastExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withType = function (type) { + return this.update(this.lessThanToken, type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.type, greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.lessThanToken, this.type, this.greaterThanToken, expression); + }; + + CastExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CastExpressionSyntax = CastExpressionSyntax; + + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.propertyAssignments = propertyAssignments; + this.closeBraceToken = closeBraceToken; + } + ObjectLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectLiteralExpression(this); + }; + + ObjectLiteralExpressionSyntax.prototype.kind = function () { + return 214 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.propertyAssignments; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.update = function (openBraceToken, propertyAssignments, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.propertyAssignments === propertyAssignments && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectLiteralExpressionSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectLiteralExpressionSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectLiteralExpressionSyntax.create1 = function () { + return new ObjectLiteralExpressionSyntax(TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ObjectLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignments = function (propertyAssignments) { + return this.update(this.openBraceToken, propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignment = function (propertyAssignment) { + return this.withPropertyAssignments(TypeScript.Syntax.separatedList([propertyAssignment])); + }; + + ObjectLiteralExpressionSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.propertyAssignments, closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.propertyAssignments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + + var PropertyAssignmentSyntax = (function (_super) { + __extends(PropertyAssignmentSyntax, _super); + function PropertyAssignmentSyntax(propertyName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + } + PropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return PropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertyAssignmentSyntax = PropertyAssignmentSyntax; + + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, parsedInStrictMode) { + _super.call(this, propertyName, parsedInStrictMode); + this.colonToken = colonToken; + this.expression = expression; + } + SimplePropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSimplePropertyAssignment(this); + }; + + SimplePropertyAssignmentSyntax.prototype.kind = function () { + return 238 /* SimplePropertyAssignment */; + }; + + SimplePropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + SimplePropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.colonToken; + case 2: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimplePropertyAssignmentSyntax.prototype.update = function (propertyName, colonToken, expression) { + if (this.propertyName === propertyName && this.colonToken === colonToken && this.expression === expression) { + return this; + } + + return new SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, this.parsedInStrictMode()); + }; + + SimplePropertyAssignmentSyntax.create1 = function (propertyName, expression) { + return new SimplePropertyAssignmentSyntax(propertyName, TypeScript.Syntax.token(107 /* ColonToken */), expression, false); + }; + + SimplePropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.propertyName, colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withExpression = function (expression) { + return this.update(this.propertyName, this.colonToken, expression); + }; + + SimplePropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SimplePropertyAssignmentSyntax; + })(PropertyAssignmentSyntax); + TypeScript.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, parsedInStrictMode) { + _super.call(this, propertyName, parsedInStrictMode); + this.callSignature = callSignature; + this.block = block; + } + FunctionPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionPropertyAssignment(this); + }; + + FunctionPropertyAssignmentSyntax.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + + FunctionPropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + FunctionPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.callSignature; + case 2: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionPropertyAssignmentSyntax.prototype.update = function (propertyName, callSignature, block) { + if (this.propertyName === propertyName && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionPropertyAssignmentSyntax.create1 = function (propertyName) { + return new FunctionPropertyAssignmentSyntax(propertyName, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.propertyName, this.callSignature, block); + }; + + FunctionPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionPropertyAssignmentSyntax; + })(PropertyAssignmentSyntax); + TypeScript.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + + var AccessorPropertyAssignmentSyntax = (function (_super) { + __extends(AccessorPropertyAssignmentSyntax, _super); + function AccessorPropertyAssignmentSyntax(propertyName, openParenToken, closeParenToken, block, parsedInStrictMode) { + _super.call(this, propertyName, parsedInStrictMode); + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + this.block = block; + } + AccessorPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + AccessorPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + AccessorPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return AccessorPropertyAssignmentSyntax; + })(PropertyAssignmentSyntax); + TypeScript.AccessorPropertyAssignmentSyntax = AccessorPropertyAssignmentSyntax; + + var GetAccessorPropertyAssignmentSyntax = (function (_super) { + __extends(GetAccessorPropertyAssignmentSyntax, _super); + function GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, propertyName, openParenToken, closeParenToken, block, parsedInStrictMode); + this.getKeyword = getKeyword; + this.typeAnnotation = typeAnnotation; + } + GetAccessorPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitGetAccessorPropertyAssignment(this); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.kind = function () { + return 239 /* GetAccessorPropertyAssignment */; + }; + + GetAccessorPropertyAssignmentSyntax.prototype.childCount = function () { + return 6; + }; + + GetAccessorPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.getKeyword; + case 1: + return this.propertyName; + case 2: + return this.openParenToken; + case 3: + return this.closeParenToken; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetAccessorPropertyAssignmentSyntax.prototype.update = function (getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block) { + if (this.getKeyword === getKeyword && this.propertyName === propertyName && this.openParenToken === openParenToken && this.closeParenToken === closeParenToken && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetAccessorPropertyAssignmentSyntax.create = function (getKeyword, propertyName, openParenToken, closeParenToken, block) { + return new GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, null, block, false); + }; + + GetAccessorPropertyAssignmentSyntax.create1 = function (propertyName) { + return new GetAccessorPropertyAssignmentSyntax(TypeScript.Syntax.token(65 /* GetKeyword */), propertyName, TypeScript.Syntax.token(73 /* OpenParenToken */), TypeScript.Syntax.token(74 /* CloseParenToken */), null, BlockSyntax.create1(), false); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(getKeyword, this.propertyName, this.openParenToken, this.closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.getKeyword, propertyName, this.openParenToken, this.closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.getKeyword, this.propertyName, openParenToken, this.closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.getKeyword, this.propertyName, this.openParenToken, closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.getKeyword, this.propertyName, this.openParenToken, this.closeParenToken, typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.getKeyword, this.propertyName, this.openParenToken, this.closeParenToken, this.typeAnnotation, block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return GetAccessorPropertyAssignmentSyntax; + })(AccessorPropertyAssignmentSyntax); + TypeScript.GetAccessorPropertyAssignmentSyntax = GetAccessorPropertyAssignmentSyntax; + + var SetAccessorPropertyAssignmentSyntax = (function (_super) { + __extends(SetAccessorPropertyAssignmentSyntax, _super); + function SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, parsedInStrictMode) { + _super.call(this, propertyName, openParenToken, closeParenToken, block, parsedInStrictMode); + this.setKeyword = setKeyword; + this.parameter = parameter; + } + SetAccessorPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSetAccessorPropertyAssignment(this); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.kind = function () { + return 240 /* SetAccessorPropertyAssignment */; + }; + + SetAccessorPropertyAssignmentSyntax.prototype.childCount = function () { + return 6; + }; + + SetAccessorPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.setKeyword; + case 1: + return this.propertyName; + case 2: + return this.openParenToken; + case 3: + return this.parameter; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetAccessorPropertyAssignmentSyntax.prototype.update = function (setKeyword, propertyName, openParenToken, parameter, closeParenToken, block) { + if (this.setKeyword === setKeyword && this.propertyName === propertyName && this.openParenToken === openParenToken && this.parameter === parameter && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, this.parsedInStrictMode()); + }; + + SetAccessorPropertyAssignmentSyntax.create1 = function (propertyName, parameter) { + return new SetAccessorPropertyAssignmentSyntax(TypeScript.Syntax.token(69 /* SetKeyword */), propertyName, TypeScript.Syntax.token(73 /* OpenParenToken */), parameter, TypeScript.Syntax.token(74 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(setKeyword, this.propertyName, this.openParenToken, this.parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.setKeyword, propertyName, this.openParenToken, this.parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.setKeyword, this.propertyName, openParenToken, this.parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withParameter = function (parameter) { + return this.update(this.setKeyword, this.propertyName, this.openParenToken, parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.setKeyword, this.propertyName, this.openParenToken, this.parameter, closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.setKeyword, this.propertyName, this.openParenToken, this.parameter, this.closeParenToken, block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameter.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SetAccessorPropertyAssignmentSyntax; + })(AccessorPropertyAssignmentSyntax); + TypeScript.SetAccessorPropertyAssignmentSyntax = SetAccessorPropertyAssignmentSyntax; + + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + } + FunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionExpression(this); + }; + + FunctionExpressionSyntax.prototype.kind = function () { + return 221 /* FunctionExpression */; + }; + + FunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.functionKeyword; + case 1: + return this.identifier; + case 2: + return this.callSignature; + case 3: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.update = function (functionKeyword, identifier, callSignature, block) { + if (this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionExpressionSyntax.create = function (functionKeyword, callSignature, block) { + return new FunctionExpressionSyntax(functionKeyword, null, callSignature, block, false); + }; + + FunctionExpressionSyntax.create1 = function () { + return new FunctionExpressionSyntax(TypeScript.Syntax.token(27 /* FunctionKeyword */), null, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(functionKeyword, this.identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.functionKeyword, identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.functionKeyword, this.identifier, callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.functionKeyword, this.identifier, this.callSignature, block); + }; + + FunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionExpressionSyntax = FunctionExpressionSyntax; + + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.semicolonToken = semicolonToken; + } + EmptyStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitEmptyStatement(this); + }; + + EmptyStatementSyntax.prototype.kind = function () { + return 155 /* EmptyStatement */; + }; + + EmptyStatementSyntax.prototype.childCount = function () { + return 1; + }; + + EmptyStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EmptyStatementSyntax.prototype.isStatement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.update = function (semicolonToken) { + if (this.semicolonToken === semicolonToken) { + return this; + } + + return new EmptyStatementSyntax(semicolonToken, this.parsedInStrictMode()); + }; + + EmptyStatementSyntax.create1 = function () { + return new EmptyStatementSyntax(TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + EmptyStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(semicolonToken); + }; + + EmptyStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EmptyStatementSyntax = EmptyStatementSyntax; + + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.tryKeyword = tryKeyword; + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + } + TryStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitTryStatement(this); + }; + + TryStatementSyntax.prototype.kind = function () { + return 158 /* TryStatement */; + }; + + TryStatementSyntax.prototype.childCount = function () { + return 4; + }; + + TryStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.tryKeyword; + case 1: + return this.block; + case 2: + return this.catchClause; + case 3: + return this.finallyClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TryStatementSyntax.prototype.isStatement = function () { + return true; + }; + + TryStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + TryStatementSyntax.prototype.update = function (tryKeyword, block, catchClause, finallyClause) { + if (this.tryKeyword === tryKeyword && this.block === block && this.catchClause === catchClause && this.finallyClause === finallyClause) { + return this; + } + + return new TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, this.parsedInStrictMode()); + }; + + TryStatementSyntax.create = function (tryKeyword, block) { + return new TryStatementSyntax(tryKeyword, block, null, null, false); + }; + + TryStatementSyntax.create1 = function () { + return new TryStatementSyntax(TypeScript.Syntax.token(38 /* TryKeyword */), BlockSyntax.create1(), null, null, false); + }; + + TryStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTryKeyword = function (tryKeyword) { + return this.update(tryKeyword, this.block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withBlock = function (block) { + return this.update(this.tryKeyword, block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withCatchClause = function (catchClause) { + return this.update(this.tryKeyword, this.block, catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withFinallyClause = function (finallyClause) { + return this.update(this.tryKeyword, this.block, this.catchClause, finallyClause); + }; + + TryStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + if (this.catchClause !== null && this.catchClause.isTypeScriptSpecific()) { + return true; + } + if (this.finallyClause !== null && this.finallyClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TryStatementSyntax = TryStatementSyntax; + + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.catchKeyword = catchKeyword; + this.openParenToken = openParenToken; + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.closeParenToken = closeParenToken; + this.block = block; + } + CatchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCatchClause(this); + }; + + CatchClauseSyntax.prototype.kind = function () { + return 234 /* CatchClause */; + }; + + CatchClauseSyntax.prototype.childCount = function () { + return 6; + }; + + CatchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.catchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.identifier; + case 3: + return this.typeAnnotation; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CatchClauseSyntax.prototype.update = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + if (this.catchKeyword === catchKeyword && this.openParenToken === openParenToken && this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, this.parsedInStrictMode()); + }; + + CatchClauseSyntax.create = function (catchKeyword, openParenToken, identifier, closeParenToken, block) { + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, null, closeParenToken, block, false); + }; + + CatchClauseSyntax.create1 = function (identifier) { + return new CatchClauseSyntax(TypeScript.Syntax.token(17 /* CatchKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), identifier, null, TypeScript.Syntax.token(74 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + CatchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withCatchKeyword = function (catchKeyword) { + return this.update(catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.catchKeyword, openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.catchKeyword, this.openParenToken, identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, block); + }; + + CatchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CatchClauseSyntax = CatchClauseSyntax; + + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(finallyKeyword, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.finallyKeyword = finallyKeyword; + this.block = block; + } + FinallyClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitFinallyClause(this); + }; + + FinallyClauseSyntax.prototype.kind = function () { + return 235 /* FinallyClause */; + }; + + FinallyClauseSyntax.prototype.childCount = function () { + return 2; + }; + + FinallyClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.finallyKeyword; + case 1: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FinallyClauseSyntax.prototype.update = function (finallyKeyword, block) { + if (this.finallyKeyword === finallyKeyword && this.block === block) { + return this; + } + + return new FinallyClauseSyntax(finallyKeyword, block, this.parsedInStrictMode()); + }; + + FinallyClauseSyntax.create1 = function () { + return new FinallyClauseSyntax(TypeScript.Syntax.token(25 /* FinallyKeyword */), BlockSyntax.create1(), false); + }; + + FinallyClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withFinallyKeyword = function (finallyKeyword) { + return this.update(finallyKeyword, this.block); + }; + + FinallyClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.finallyKeyword, block); + }; + + FinallyClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FinallyClauseSyntax = FinallyClauseSyntax; + + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(identifier, colonToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.colonToken = colonToken; + this.statement = statement; + } + LabeledStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitLabeledStatement(this); + }; + + LabeledStatementSyntax.prototype.kind = function () { + return 159 /* LabeledStatement */; + }; + + LabeledStatementSyntax.prototype.childCount = function () { + return 3; + }; + + LabeledStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.colonToken; + case 2: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + LabeledStatementSyntax.prototype.isStatement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.update = function (identifier, colonToken, statement) { + if (this.identifier === identifier && this.colonToken === colonToken && this.statement === statement) { + return this; + } + + return new LabeledStatementSyntax(identifier, colonToken, statement, this.parsedInStrictMode()); + }; + + LabeledStatementSyntax.create1 = function (identifier, statement) { + return new LabeledStatementSyntax(identifier, TypeScript.Syntax.token(107 /* ColonToken */), statement, false); + }; + + LabeledStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.identifier, colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.identifier, this.colonToken, statement); + }; + + LabeledStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.LabeledStatementSyntax = LabeledStatementSyntax; + + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, parsedInStrictMode) { + _super.call(this, openParenToken, closeParenToken, statement, parsedInStrictMode); + this.doKeyword = doKeyword; + this.whileKeyword = whileKeyword; + this.condition = condition; + this.semicolonToken = semicolonToken; + } + DoStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDoStatement(this); + }; + + DoStatementSyntax.prototype.kind = function () { + return 160 /* DoStatement */; + }; + + DoStatementSyntax.prototype.childCount = function () { + return 7; + }; + + DoStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.doKeyword; + case 1: + return this.statement; + case 2: + return this.whileKeyword; + case 3: + return this.openParenToken; + case 4: + return this.condition; + case 5: + return this.closeParenToken; + case 6: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DoStatementSyntax.prototype.update = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + if (this.doKeyword === doKeyword && this.statement === statement && this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.semicolonToken === semicolonToken) { + return this; + } + + return new DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, this.parsedInStrictMode()); + }; + + DoStatementSyntax.create1 = function (statement, condition) { + return new DoStatementSyntax(TypeScript.Syntax.token(22 /* DoKeyword */), statement, TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + DoStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withDoKeyword = function (doKeyword) { + return this.update(doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.doKeyword, statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(this.doKeyword, this.statement, whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, semicolonToken); + }; + + DoStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.condition.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DoStatementSyntax; + })(IterationStatementSyntax); + TypeScript.DoStatementSyntax = DoStatementSyntax; + + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(typeOfKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.expression = expression; + } + TypeOfExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeOfExpression(this); + }; + + TypeOfExpressionSyntax.prototype.kind = function () { + return 170 /* TypeOfExpression */; + }; + + TypeOfExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + TypeOfExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeOfExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.update = function (typeOfKeyword, expression) { + if (this.typeOfKeyword === typeOfKeyword && this.expression === expression) { + return this; + } + + return new TypeOfExpressionSyntax(typeOfKeyword, expression, this.parsedInStrictMode()); + }; + + TypeOfExpressionSyntax.create1 = function (expression) { + return new TypeOfExpressionSyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), expression, false); + }; + + TypeOfExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.expression); + }; + + TypeOfExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.typeOfKeyword, expression); + }; + + TypeOfExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(deleteKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.deleteKeyword = deleteKeyword; + this.expression = expression; + } + DeleteExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitDeleteExpression(this); + }; + + DeleteExpressionSyntax.prototype.kind = function () { + return 169 /* DeleteExpression */; + }; + + DeleteExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + DeleteExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.deleteKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DeleteExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.update = function (deleteKeyword, expression) { + if (this.deleteKeyword === deleteKeyword && this.expression === expression) { + return this; + } + + return new DeleteExpressionSyntax(deleteKeyword, expression, this.parsedInStrictMode()); + }; + + DeleteExpressionSyntax.create1 = function (expression) { + return new DeleteExpressionSyntax(TypeScript.Syntax.token(21 /* DeleteKeyword */), expression, false); + }; + + DeleteExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withDeleteKeyword = function (deleteKeyword) { + return this.update(deleteKeyword, this.expression); + }; + + DeleteExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.deleteKeyword, expression); + }; + + DeleteExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DeleteExpressionSyntax = DeleteExpressionSyntax; + + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(voidKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.voidKeyword = voidKeyword; + this.expression = expression; + } + VoidExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitVoidExpression(this); + }; + + VoidExpressionSyntax.prototype.kind = function () { + return 171 /* VoidExpression */; + }; + + VoidExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + VoidExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.voidKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VoidExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.update = function (voidKeyword, expression) { + if (this.voidKeyword === voidKeyword && this.expression === expression) { + return this; + } + + return new VoidExpressionSyntax(voidKeyword, expression, this.parsedInStrictMode()); + }; + + VoidExpressionSyntax.create1 = function (expression) { + return new VoidExpressionSyntax(TypeScript.Syntax.token(41 /* VoidKeyword */), expression, false); + }; + + VoidExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withVoidKeyword = function (voidKeyword) { + return this.update(voidKeyword, this.expression); + }; + + VoidExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.voidKeyword, expression); + }; + + VoidExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VoidExpressionSyntax = VoidExpressionSyntax; + + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(debuggerKeyword, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.debuggerKeyword = debuggerKeyword; + this.semicolonToken = semicolonToken; + } + DebuggerStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDebuggerStatement(this); + }; + + DebuggerStatementSyntax.prototype.kind = function () { + return 161 /* DebuggerStatement */; + }; + + DebuggerStatementSyntax.prototype.childCount = function () { + return 2; + }; + + DebuggerStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.debuggerKeyword; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DebuggerStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.update = function (debuggerKeyword, semicolonToken) { + if (this.debuggerKeyword === debuggerKeyword && this.semicolonToken === semicolonToken) { + return this; + } + + return new DebuggerStatementSyntax(debuggerKeyword, semicolonToken, this.parsedInStrictMode()); + }; + + DebuggerStatementSyntax.create1 = function () { + return new DebuggerStatementSyntax(TypeScript.Syntax.token(19 /* DebuggerKeyword */), TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + DebuggerStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withDebuggerKeyword = function (debuggerKeyword) { + return this.update(debuggerKeyword, this.semicolonToken); + }; + + DebuggerStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.debuggerKeyword, semicolonToken); + }; + + DebuggerStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DebuggerStatementSyntax = DebuggerStatementSyntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxRewriter = (function () { + function SyntaxRewriter() { + } + SyntaxRewriter.prototype.visitToken = function (token) { + return token; + }; + + SyntaxRewriter.prototype.visitNode = function (node) { + return node.accept(this); + }; + + SyntaxRewriter.prototype.visitNodeOrToken = function (node) { + return node.isToken() ? this.visitToken(node) : this.visitNode(node); + }; + + SyntaxRewriter.prototype.visitList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = this.visitNodeOrToken(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.list(newItems); + }; + + SyntaxRewriter.prototype.visitSeparatedList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = item.isToken() ? this.visitToken(item) : this.visitNode(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.separatedList(newItems); + }; + + SyntaxRewriter.prototype.visitSourceUnit = function (node) { + return node.update(this.visitList(node.moduleElements), this.visitToken(node.endOfFileToken)); + }; + + SyntaxRewriter.prototype.visitExternalModuleReference = function (node) { + return node.update(this.visitToken(node.moduleOrRequireKeyword), this.visitToken(node.openParenToken), this.visitToken(node.stringLiteral), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitModuleNameModuleReference = function (node) { + return node.update(this.visitNodeOrToken(node.moduleName)); + }; + + SyntaxRewriter.prototype.visitImportDeclaration = function (node) { + return node.update(this.visitToken(node.importKeyword), this.visitToken(node.identifier), this.visitToken(node.equalsToken), this.visitNode(node.moduleReference), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitExportAssignment = function (node) { + return node.update(this.visitToken(node.exportKeyword), this.visitToken(node.equalsToken), this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitClassDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.classKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitToken(node.openBraceToken), this.visitList(node.classElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitInterfaceDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.interfaceKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitNode(node.body)); + }; + + SyntaxRewriter.prototype.visitHeritageClause = function (node) { + return node.update(this.visitToken(node.extendsOrImplementsKeyword), this.visitSeparatedList(node.typeNames)); + }; + + SyntaxRewriter.prototype.visitModuleDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.moduleKeyword), node.moduleName === null ? null : this.visitNodeOrToken(node.moduleName), node.stringLiteral === null ? null : this.visitToken(node.stringLiteral), this.visitToken(node.openBraceToken), this.visitList(node.moduleElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.functionKeyword), this.visitToken(node.identifier), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableStatement = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclaration), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableDeclaration = function (node) { + return node.update(this.visitToken(node.varKeyword), this.visitSeparatedList(node.variableDeclarators)); + }; + + SyntaxRewriter.prototype.visitVariableDeclarator = function (node) { + return node.update(this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitEqualsValueClause = function (node) { + return node.update(this.visitToken(node.equalsToken), this.visitNodeOrToken(node.value)); + }; + + SyntaxRewriter.prototype.visitPrefixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.operand)); + }; + + SyntaxRewriter.prototype.visitArrayLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitSeparatedList(node.expressions), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitOmittedExpression = function (node) { + return node; + }; + + SyntaxRewriter.prototype.visitParenthesizedExpression = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitSimpleArrowFunctionExpression = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.body)); + }; + + SyntaxRewriter.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return node.update(this.visitNode(node.callSignature), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.body)); + }; + + SyntaxRewriter.prototype.visitQualifiedName = function (node) { + return node.update(this.visitNodeOrToken(node.left), this.visitToken(node.dotToken), this.visitToken(node.right)); + }; + + SyntaxRewriter.prototype.visitTypeArgumentList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeArguments), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitConstructorType = function (node) { + return node.update(this.visitToken(node.newKeyword), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitFunctionType = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitObjectType = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.typeMembers), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitArrayType = function (node) { + return node.update(this.visitNodeOrToken(node.type), this.visitToken(node.openBracketToken), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitGenericType = function (node) { + return node.update(this.visitNodeOrToken(node.name), this.visitNode(node.typeArgumentList)); + }; + + SyntaxRewriter.prototype.visitTypeAnnotation = function (node) { + return node.update(this.visitToken(node.colonToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitBlock = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitList(node.statements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitParameter = function (node) { + return node.update(node.dotDotDotToken === null ? null : this.visitToken(node.dotDotDotToken), node.publicOrPrivateKeyword === null ? null : this.visitToken(node.publicOrPrivateKeyword), this.visitToken(node.identifier), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitMemberAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.dotToken), this.visitToken(node.name)); + }; + + SyntaxRewriter.prototype.visitPostfixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.operand), this.visitToken(node.operatorToken)); + }; + + SyntaxRewriter.prototype.visitElementAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.openBracketToken), this.visitNodeOrToken(node.argumentExpression), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitInvocationExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitArgumentList = function (node) { + return node.update(node.typeArgumentList === null ? null : this.visitNode(node.typeArgumentList), this.visitToken(node.openParenToken), this.visitSeparatedList(node.arguments), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitBinaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.left), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.right)); + }; + + SyntaxRewriter.prototype.visitConditionalExpression = function (node) { + return node.update(this.visitNodeOrToken(node.condition), this.visitToken(node.questionToken), this.visitNodeOrToken(node.whenTrue), this.visitToken(node.colonToken), this.visitNodeOrToken(node.whenFalse)); + }; + + SyntaxRewriter.prototype.visitConstructSignature = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitMethodSignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitIndexSignature = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitNode(node.parameter), this.visitToken(node.closeBracketToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitPropertySignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitCallSignature = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitParameterList = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitSeparatedList(node.parameters), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameterList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeParameters), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameter = function (node) { + return node.update(this.visitToken(node.identifier), node.constraint === null ? null : this.visitNode(node.constraint)); + }; + + SyntaxRewriter.prototype.visitConstraint = function (node) { + return node.update(this.visitToken(node.extendsKeyword), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitElseClause = function (node) { + return node.update(this.visitToken(node.elseKeyword), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitIfStatement = function (node) { + return node.update(this.visitToken(node.ifKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement), node.elseClause === null ? null : this.visitNode(node.elseClause)); + }; + + SyntaxRewriter.prototype.visitExpressionStatement = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { + return node.update(this.visitToken(node.constructorKeyword), this.visitNode(node.parameterList), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.propertyName), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitGetMemberAccessorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetMemberAccessorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitMemberVariableDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclarator), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitThrowStatement = function (node) { + return node.update(this.visitToken(node.throwKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitReturnStatement = function (node) { + return node.update(this.visitToken(node.returnKeyword), node.expression === null ? null : this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitObjectCreationExpression = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNodeOrToken(node.expression), node.argumentList === null ? null : this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitSwitchStatement = function (node) { + return node.update(this.visitToken(node.switchKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitToken(node.openBraceToken), this.visitList(node.switchClauses), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitCaseSwitchClause = function (node) { + return node.update(this.visitToken(node.caseKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitDefaultSwitchClause = function (node) { + return node.update(this.visitToken(node.defaultKeyword), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitBreakStatement = function (node) { + return node.update(this.visitToken(node.breakKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitContinueStatement = function (node) { + return node.update(this.visitToken(node.continueKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitForStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.initializer === null ? null : this.visitNodeOrToken(node.initializer), this.visitToken(node.firstSemicolonToken), node.condition === null ? null : this.visitNodeOrToken(node.condition), this.visitToken(node.secondSemicolonToken), node.incrementor === null ? null : this.visitNodeOrToken(node.incrementor), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitForInStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.left === null ? null : this.visitNodeOrToken(node.left), this.visitToken(node.inKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWhileStatement = function (node) { + return node.update(this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWithStatement = function (node) { + return node.update(this.visitToken(node.withKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitEnumDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.enumKeyword), this.visitToken(node.identifier), this.visitToken(node.openBraceToken), this.visitSeparatedList(node.enumElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitEnumElement = function (node) { + return node.update(this.visitToken(node.propertyName), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitCastExpression = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitNodeOrToken(node.type), this.visitToken(node.greaterThanToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitObjectLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.propertyAssignments), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitSimplePropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitToken(node.colonToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitFunctionPropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitGetAccessorPropertyAssignment = function (node) { + return node.update(this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitToken(node.openParenToken), this.visitToken(node.closeParenToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetAccessorPropertyAssignment = function (node) { + return node.update(this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitToken(node.openParenToken), this.visitNode(node.parameter), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFunctionExpression = function (node) { + return node.update(this.visitToken(node.functionKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitEmptyStatement = function (node) { + return node.update(this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTryStatement = function (node) { + return node.update(this.visitToken(node.tryKeyword), this.visitNode(node.block), node.catchClause === null ? null : this.visitNode(node.catchClause), node.finallyClause === null ? null : this.visitNode(node.finallyClause)); + }; + + SyntaxRewriter.prototype.visitCatchClause = function (node) { + return node.update(this.visitToken(node.catchKeyword), this.visitToken(node.openParenToken), this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFinallyClause = function (node) { + return node.update(this.visitToken(node.finallyKeyword), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitLabeledStatement = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.colonToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitDoStatement = function (node) { + return node.update(this.visitToken(node.doKeyword), this.visitNodeOrToken(node.statement), this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTypeOfExpression = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDeleteExpression = function (node) { + return node.update(this.visitToken(node.deleteKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitVoidExpression = function (node) { + return node.update(this.visitToken(node.voidKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDebuggerStatement = function (node) { + return node.update(this.visitToken(node.debuggerKeyword), this.visitToken(node.semicolonToken)); + }; + return SyntaxRewriter; + })(); + TypeScript.SyntaxRewriter = SyntaxRewriter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDedenter = (function (_super) { + __extends(SyntaxDedenter, _super); + function SyntaxDedenter(dedentFirstToken, dedentationAmount, minimumIndent, options) { + _super.call(this); + this.dedentationAmount = dedentationAmount; + this.minimumIndent = minimumIndent; + this.options = options; + this.lastTriviaWasNewLine = dedentFirstToken; + } + SyntaxDedenter.prototype.abort = function () { + this.lastTriviaWasNewLine = false; + this.dedentationAmount = 0; + }; + + SyntaxDedenter.prototype.isAborted = function () { + return this.dedentationAmount === 0; + }; + + SyntaxDedenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.dedentTriviaList(token.leadingTrivia())); + } + + if (this.isAborted()) { + return token; + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxDedenter.prototype.dedentTriviaList = function (triviaList) { + var result = []; + var dedentNextWhitespace = true; + + for (var i = 0, n = triviaList.count(); i < n && !this.isAborted(); i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var dedentThisTrivia = dedentNextWhitespace; + dedentNextWhitespace = false; + + if (dedentThisTrivia) { + if (trivia.kind() === 4 /* WhitespaceTrivia */) { + var hasFollowingNewLine = (i < triviaList.count() - 1) && triviaList.syntaxTriviaAt(i + 1).kind() === 5 /* NewLineTrivia */; + result.push(this.dedentWhitespace(trivia, hasFollowingNewLine)); + continue; + } else if (trivia.kind() !== 5 /* NewLineTrivia */) { + this.abort(); + break; + } + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + result.push(this.dedentMultiLineComment(trivia)); + continue; + } + + result.push(trivia); + if (trivia.kind() === 5 /* NewLineTrivia */) { + dedentNextWhitespace = true; + } + } + + if (dedentNextWhitespace) { + this.abort(); + } + + if (this.isAborted()) { + return triviaList; + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxDedenter.prototype.dedentSegment = function (segment, hasFollowingNewLineTrivia) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition === segment.length) { + if (hasFollowingNewLineTrivia) { + return ""; + } + } else if (TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment.substring(firstNonWhitespacePosition); + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = TypeScript.MathPrototype.min(firstNonWhitespaceColumn, TypeScript.MathPrototype.max(firstNonWhitespaceColumn - this.dedentationAmount, this.minimumIndent)); + + if (newFirstNonWhitespaceColumn === firstNonWhitespaceColumn) { + this.abort(); + return segment; + } + + this.dedentationAmount = firstNonWhitespaceColumn - newFirstNonWhitespaceColumn; + TypeScript.Debug.assert(this.dedentationAmount >= 0); + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxDedenter.prototype.dedentWhitespace = function (trivia, hasFollowingNewLineTrivia) { + var newIndentation = this.dedentSegment(trivia.fullText(), hasFollowingNewLineTrivia); + return TypeScript.Syntax.whitespace(newIndentation); + }; + + SyntaxDedenter.prototype.dedentMultiLineComment = function (trivia) { + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length === 1) { + return trivia; + } + + for (var i = 1; i < segments.length; i++) { + var segment = segments[i]; + segments[i] = this.dedentSegment(segment, false); + } + + var result = segments.join(""); + + return TypeScript.Syntax.multiLineComment(result); + }; + + SyntaxDedenter.dedentNode = function (node, dedentFirstToken, dedentAmount, minimumIndent, options) { + var dedenter = new SyntaxDedenter(dedentFirstToken, dedentAmount, minimumIndent, options); + var result = node.accept(dedenter); + + if (dedenter.isAborted()) { + return node; + } + + return result; + }; + return SyntaxDedenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxDedenter = SyntaxDedenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxIndenter = (function (_super) { + __extends(SyntaxIndenter, _super); + function SyntaxIndenter(indentFirstToken, indentationAmount, options) { + _super.call(this); + this.indentationAmount = indentationAmount; + this.options = options; + this.lastTriviaWasNewLine = indentFirstToken; + this.indentationTrivia = TypeScript.Indentation.indentationTrivia(this.indentationAmount, this.options); + } + SyntaxIndenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.indentTriviaList(token.leadingTrivia())); + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxIndenter.prototype.indentTriviaList = function (triviaList) { + var result = []; + + var indentNextTrivia = true; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var indentThisTrivia = indentNextTrivia; + indentNextTrivia = false; + + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.indentMultiLineComment(trivia, indentThisTrivia, result); + continue; + + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + this.indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + continue; + + case 4 /* WhitespaceTrivia */: + this.indentWhitespace(trivia, indentThisTrivia, result); + continue; + + case 5 /* NewLineTrivia */: + result.push(trivia); + indentNextTrivia = true; + continue; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + if (indentNextTrivia) { + result.push(this.indentationTrivia); + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxIndenter.prototype.indentSegment = function (segment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment; + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = firstNonWhitespaceColumn + this.indentationAmount; + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxIndenter.prototype.indentWhitespace = function (trivia, indentThisTrivia, result) { + if (!indentThisTrivia) { + result.push(trivia); + return; + } + + var newIndentation = this.indentSegment(trivia.fullText()); + result.push(TypeScript.Syntax.whitespace(newIndentation)); + }; + + SyntaxIndenter.prototype.indentSingleLineOrSkippedText = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + result.push(trivia); + }; + + SyntaxIndenter.prototype.indentMultiLineComment = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + + for (var i = 1; i < segments.length; i++) { + segments[i] = this.indentSegment(segments[i]); + } + + var newText = segments.join(""); + result.push(TypeScript.Syntax.multiLineComment(newText)); + }; + + SyntaxIndenter.indentNode = function (node, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + return node.accept(indenter); + }; + + SyntaxIndenter.indentNodes = function (nodes, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + var result = TypeScript.ArrayUtilities.select(nodes, function (n) { + return n.accept(indenter); + }); + + return result; + }; + return SyntaxIndenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxIndenter = SyntaxIndenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var VariableWidthTokenWithNoTrivia = (function () { + function VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, textOrWidth) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._textOrWidth = textOrWidth; + } + VariableWidthTokenWithNoTrivia.prototype.clone = function () { + return new VariableWidthTokenWithNoTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth); + }; + + VariableWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.width(); + }; + VariableWidthTokenWithNoTrivia.prototype.start = function () { + return this._fullStart; + }; + VariableWidthTokenWithNoTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithNoTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithNoTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithNoTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithNoTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithNoTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithNoTrivia; + })(); + Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; + + var VariableWidthTokenWithLeadingTrivia = (function () { + function VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._textOrWidth = textOrWidth; + } + VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + }; + VariableWidthTokenWithLeadingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithLeadingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; + + var VariableWidthTokenWithTrailingTrivia = (function () { + function VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, textOrWidth, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._textOrWidth = textOrWidth; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.start = function () { + return this._fullStart; + }; + VariableWidthTokenWithTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; + + var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { + function VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._textOrWidth = textOrWidth; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia = VariableWidthTokenWithLeadingAndTrailingTrivia; + + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(kind) { + this.tokenKind = kind; + } + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this.tokenKind); + }; + + FixedWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.width(); + }; + FixedWidthTokenWithNoTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return this.text(); + }; + + FixedWidthTokenWithNoTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithNoTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithNoTrivia; + })(); + Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; + + var FixedWidthTokenWithLeadingTrivia = (function () { + function FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + }; + FixedWidthTokenWithLeadingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithLeadingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; + + var FixedWidthTokenWithTrailingTrivia = (function () { + function FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.start = function () { + return this._fullStart; + }; + FixedWidthTokenWithTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; + + var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { + function FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia = FixedWidthTokenWithLeadingAndTrailingTrivia; + + function collectTokenTextElements(token, elements) { + token.leadingTrivia().collectTextElements(elements); + elements.push(token.text()); + token.trailingTrivia().collectTextElements(elements); + } + + function fixedWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new FixedWidthTokenWithNoTrivia(kind); + } else { + return new FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo); + } else { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } + Syntax.fixedWidthToken = fixedWidthToken; + + function variableWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, width); + } else { + return new VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, width, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width); + } else { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); + } + } + Syntax.variableWidthToken = variableWidthToken; + + function getTriviaWidth(value) { + return value >>> 2 /* TriviaFullWidthShift */; + } + + function hasTriviaComment(value) { + return (value & 2 /* TriviaCommentMask */) !== 0; + } + + function hasTriviaNewLine(value) { + return (value & 1 /* TriviaNewLineMask */) !== 0; + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function realizeToken(token) { + return new RealizedToken(token.tokenKind, token.leadingTrivia(), token.text(), token.value(), token.valueText(), token.trailingTrivia()); + } + Syntax.realizeToken = realizeToken; + + function convertToIdentifierName(token) { + TypeScript.Debug.assert(TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)); + return new RealizedToken(11 /* IdentifierName */, token.leadingTrivia(), token.text(), token.text(), token.text(), token.trailingTrivia()); + } + Syntax.convertToIdentifierName = convertToIdentifierName; + + function tokenToJSON(token) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === token.kind()) { + result.kind = name; + break; + } + } + + result.width = token.width(); + if (token.fullWidth() !== token.width()) { + result.fullWidth = token.fullWidth(); + } + + result.text = token.text(); + + var value = token.value(); + if (value !== null) { + result.value = value; + result.valueText = token.valueText(); + } + + if (token.hasLeadingTrivia()) { + result.hasLeadingTrivia = true; + } + + if (token.hasLeadingComment()) { + result.hasLeadingComment = true; + } + + if (token.hasLeadingNewLine()) { + result.hasLeadingNewLine = true; + } + + if (token.hasLeadingSkippedText()) { + result.hasLeadingSkippedText = true; + } + + if (token.hasTrailingTrivia()) { + result.hasTrailingTrivia = true; + } + + if (token.hasTrailingComment()) { + result.hasTrailingComment = true; + } + + if (token.hasTrailingNewLine()) { + result.hasTrailingNewLine = true; + } + + if (token.hasTrailingSkippedText()) { + result.hasTrailingSkippedText = true; + } + + var trivia = token.leadingTrivia(); + if (trivia.count() > 0) { + result.leadingTrivia = trivia; + } + + trivia = token.trailingTrivia(); + if (trivia.count() > 0) { + result.trailingTrivia = trivia; + } + + return result; + } + Syntax.tokenToJSON = tokenToJSON; + + function value(token) { + return value1(token.tokenKind, token.text()); + } + Syntax.value = value; + + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + + return intChar; + } + + var characterArray = []; + + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + + default: + } + } + } + + characterArray.push(ch); + + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + + return result; + } + + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + + function value1(kind, text) { + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + + if (kind === 13 /* NumericLiteral */) { + return parseFloat(text); + } else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } else { + return massageEscapes(text.substr(1)); + } + } else if (kind === 12 /* RegularExpressionLiteral */) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } catch (e) { + return null; + } + } else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + + function valueText1(kind, text) { + var value = value1(kind, text); + return value === null ? "" : value.toString(); + } + + function valueText(token) { + var value = token.value(); + return value === null ? "" : value.toString(); + } + Syntax.valueText = valueText; + + var EmptyToken = (function () { + function EmptyToken(kind) { + this.tokenKind = kind; + } + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.tokenKind); + }; + + EmptyToken.prototype.kind = function () { + return this.tokenKind; + }; + + EmptyToken.prototype.isToken = function () { + return true; + }; + EmptyToken.prototype.isNode = function () { + return false; + }; + EmptyToken.prototype.isList = function () { + return false; + }; + EmptyToken.prototype.isSeparatedList = function () { + return false; + }; + + EmptyToken.prototype.childCount = function () { + return 0; + }; + + EmptyToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptyToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + EmptyToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + EmptyToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + EmptyToken.prototype.firstToken = function () { + return this; + }; + EmptyToken.prototype.lastToken = function () { + return this; + }; + EmptyToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.width = function () { + return 0; + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.value = function () { + return null; + }; + EmptyToken.prototype.valueText = function () { + return ""; + }; + + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasLeadingComment = function () { + return false; + }; + EmptyToken.prototype.hasLeadingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasLeadingSkippedText = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasTrailingComment = function () { + return false; + }; + EmptyToken.prototype.hasTrailingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasTrailingSkippedText = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + EmptyToken.prototype.realize = function () { + return realizeToken(this); + }; + EmptyToken.prototype.collectTextElements = function (elements) { + }; + + EmptyToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + EmptyToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return EmptyToken; + })(); + + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + + var RealizedToken = (function () { + function RealizedToken(tokenKind, leadingTrivia, text, value, valueText, trailingTrivia) { + this.tokenKind = tokenKind; + this._leadingTrivia = leadingTrivia; + this._text = text; + this._value = value; + this._valueText = valueText; + this._trailingTrivia = trailingTrivia; + } + RealizedToken.prototype.clone = function () { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.kind = function () { + return this.tokenKind; + }; + RealizedToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + RealizedToken.prototype.firstToken = function () { + return this; + }; + RealizedToken.prototype.lastToken = function () { + return this; + }; + RealizedToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + RealizedToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + RealizedToken.prototype.childCount = function () { + return 0; + }; + + RealizedToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + RealizedToken.prototype.isToken = function () { + return true; + }; + RealizedToken.prototype.isNode = function () { + return false; + }; + RealizedToken.prototype.isList = function () { + return false; + }; + RealizedToken.prototype.isSeparatedList = function () { + return false; + }; + RealizedToken.prototype.isTrivia = function () { + return false; + }; + RealizedToken.prototype.isTriviaList = function () { + return false; + }; + + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this.width() + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.width = function () { + return this.text().length; + }; + + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + + RealizedToken.prototype.value = function () { + return this._value; + }; + RealizedToken.prototype.valueText = function () { + return this._valueText; + }; + + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasLeadingComment = function () { + return this._leadingTrivia.hasComment(); + }; + RealizedToken.prototype.hasLeadingNewLine = function () { + return this._leadingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasLeadingSkippedText = function () { + return this._leadingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingComment = function () { + return this._trailingTrivia.hasComment(); + }; + RealizedToken.prototype.hasTrailingNewLine = function () { + return this._trailingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasTrailingSkippedText = function () { + return this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasSkippedToken = function () { + return this.hasLeadingSkippedText() || this.hasTrailingSkippedText(); + }; + + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + + RealizedToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + RealizedToken.prototype.collectTextElements = function (elements) { + this.leadingTrivia().collectTextElements(elements); + elements.push(this.text()); + this.trailingTrivia().collectTextElements(elements); + }; + + RealizedToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return new RealizedToken(this.tokenKind, leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, trailingTrivia); + }; + return RealizedToken; + })(); + + function token(kind, info) { + if (typeof info === "undefined") { info = null; } + var text = (info !== null && info.text !== undefined) ? info.text : TypeScript.SyntaxFacts.getText(kind); + + return new RealizedToken(kind, TypeScript.Syntax.triviaList(info === null ? null : info.leadingTrivia), text, value1(kind, text), valueText1(kind, text), TypeScript.Syntax.triviaList(info === null ? null : info.trailingTrivia)); + } + Syntax.token = token; + + function identifier(text, info) { + if (typeof info === "undefined") { info = null; } + info = info || {}; + info.text = text; + return token(11 /* IdentifierName */, info); + } + Syntax.identifier = identifier; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTokenReplacer = (function (_super) { + __extends(SyntaxTokenReplacer, _super); + function SyntaxTokenReplacer(token1, token2) { + _super.call(this); + this.token1 = token1; + this.token2 = token2; + } + SyntaxTokenReplacer.prototype.visitToken = function (token) { + if (token === this.token1) { + var result = this.token2; + this.token1 = null; + this.token2 = null; + + return result; + } + + return token; + }; + + SyntaxTokenReplacer.prototype.visitNode = function (node) { + if (this.token1 === null) { + return node; + } + + return _super.prototype.visitNode.call(this, node); + }; + + SyntaxTokenReplacer.prototype.visitList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitList.call(this, list); + }; + + SyntaxTokenReplacer.prototype.visitSeparatedList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitSeparatedList.call(this, list); + }; + return SyntaxTokenReplacer; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxTokenReplacer = SyntaxTokenReplacer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var SyntaxTrivia = (function () { + function SyntaxTrivia(kind, textOrToken) { + this._kind = kind; + this._textOrToken = textOrToken; + } + SyntaxTrivia.prototype.toJSON = function (key) { + var result = {}; + result.kind = TypeScript.SyntaxKind[this._kind]; + + if (this.isSkippedToken()) { + result.skippedToken = this._textOrToken; + } else { + result.text = this._textOrToken; + } + return result; + }; + + SyntaxTrivia.prototype.kind = function () { + return this._kind; + }; + + SyntaxTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + SyntaxTrivia.prototype.fullText = function () { + return this.isSkippedToken() ? this.skippedToken().fullText() : this._textOrToken; + }; + + SyntaxTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + + SyntaxTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + + SyntaxTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + + SyntaxTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + + SyntaxTrivia.prototype.skippedToken = function () { + TypeScript.Debug.assert(this.isSkippedToken()); + return this._textOrToken; + }; + + SyntaxTrivia.prototype.collectTextElements = function (elements) { + elements.push(this.fullText()); + }; + return SyntaxTrivia; + })(); + + function trivia(kind, text) { + return new SyntaxTrivia(kind, text); + } + Syntax.trivia = trivia; + + function skippedTokenTrivia(token) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SyntaxTrivia(8 /* SkippedTokenTrivia */, token); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + + function spaces(count) { + return trivia(4 /* WhitespaceTrivia */, TypeScript.StringUtilities.repeat(" ", count)); + } + Syntax.spaces = spaces; + + function whitespace(text) { + return trivia(4 /* WhitespaceTrivia */, text); + } + Syntax.whitespace = whitespace; + + function multiLineComment(text) { + return trivia(6 /* MultiLineCommentTrivia */, text); + } + Syntax.multiLineComment = multiLineComment; + + function singleLineComment(text) { + return trivia(7 /* SingleLineCommentTrivia */, text); + } + Syntax.singleLineComment = singleLineComment; + + Syntax.spaceTrivia = spaces(1); + Syntax.lineFeedTrivia = trivia(5 /* NewLineTrivia */, "\n"); + Syntax.carriageReturnTrivia = trivia(5 /* NewLineTrivia */, "\r"); + Syntax.carriageReturnLineFeedTrivia = trivia(5 /* NewLineTrivia */, "\r\n"); + + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + + var triviaText = trivia.fullText(); + var currentIndex = 0; + + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + + currentIndex = i + 1; + continue; + } + } + + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax.emptyTriviaList = { + kind: function () { + return 3 /* TriviaList */; + }, + count: function () { + return 0; + }, + syntaxTriviaAt: function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + last: function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + fullWidth: function () { + return 0; + }, + fullText: function () { + return ""; + }, + hasComment: function () { + return false; + }, + hasNewLine: function () { + return false; + }, + hasSkippedToken: function () { + return false; + }, + toJSON: function (key) { + return []; + }, + collectTextElements: function (elements) { + }, + toArray: function () { + return []; + }, + concat: function (trivia) { + return trivia; + } + }; + + function concatTrivia(list1, list2) { + if (list1.count() === 0) { + return list2; + } + + if (list2.count() === 0) { + return list1; + } + + var trivia = list1.toArray(); + trivia.push.apply(trivia, list2.toArray()); + + return triviaList(trivia); + } + + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.collectTextElements = function (elements) { + (this.item).collectTextElements(elements); + }; + + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return SingletonSyntaxTriviaList; + })(); + + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + this.trivia = trivia; + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.trivia[index]; + }; + + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { + return t.fullWidth(); + }); + }; + + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = ""; + + for (var i = 0, n = this.trivia.length; i < n; i++) { + result += this.trivia[i].fullText(); + } + + return result; + }; + + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.toJSON = function (key) { + return this.trivia; + }; + + NormalSyntaxTriviaList.prototype.collectTextElements = function (elements) { + for (var i = 0; i < this.trivia.length; i++) { + (this.trivia[i]).collectTextElements(elements); + } + }; + + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + + NormalSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return NormalSyntaxTriviaList; + })(); + + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return TypeScript.Syntax.emptyTriviaList; + } + + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + + Syntax.spaceTriviaList = triviaList([TypeScript.Syntax.spaceTrivia]); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement.element(); + var parent = positionedElement.parentElement(); + if (parent !== null && (element.kind() === 81 /* LessThanToken */ || element.kind() === 82 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 227 /* TypeArgumentList */: + case 228 /* TypeParameterList */: + case 219 /* CastExpression */: + return true; + } + } + + return false; + }; + + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var token = list.childAt(i); + if (token.tokenKind === kind) { + return token; + } + } + + return null; + }; + + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 147 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + return SyntaxUtilities.containsToken((moduleElement).modifiers, 47 /* ExportKeyword */); + } + + return false; + }; + + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + + var node = positionNode.node(); + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 147 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken((node).modifiers, 64 /* DeclareKeyword */)) { + return true; + } + + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 138 /* GetMemberAccessorDeclaration */: + case 139 /* SetMemberAccessorDeclaration */: + case 136 /* MemberVariableDeclaration */: + if (node.isClassElement() || node.isModuleElement()) { + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode().containingNode()); + + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxVisitor = (function () { + function SyntaxVisitor() { + } + SyntaxVisitor.prototype.defaultVisit = function (node) { + return null; + }; + + SyntaxVisitor.prototype.visitToken = function (token) { + return this.defaultVisit(token); + }; + + SyntaxVisitor.prototype.visitSourceUnit = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExternalModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleNameModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitImportDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExportAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitClassDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInterfaceDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitHeritageClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclarator = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEqualsValueClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPrefixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitOmittedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitQualifiedName = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGenericType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeAnnotation = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBlock = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPostfixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElementAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInvocationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBinaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConditionalExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMethodSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPropertySignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCallSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstraint = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElseClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIfStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExpressionStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetMemberAccessorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetMemberAccessorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitThrowStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitReturnStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectCreationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSwitchStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCaseSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDefaultSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBreakStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitContinueStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForInStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWhileStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWithStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumElement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCastExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimplePropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetAccessorPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetAccessorPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEmptyStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTryStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCatchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFinallyClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitLabeledStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDoStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeOfExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDeleteExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVoidExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDebuggerStatement = function (node) { + return this.defaultVisit(node); + }; + return SyntaxVisitor; + })(); + TypeScript.SyntaxVisitor = SyntaxVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + + SyntaxWalker.prototype.visitNode = function (node) { + node.accept(this); + }; + + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (nodeOrToken.isToken()) { + this.visitToken(nodeOrToken); + } else { + this.visitNode(nodeOrToken); + } + }; + + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + + this.visitToken(token); + }; + + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + + this.visitNode(node); + }; + + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + + this.visitNodeOrToken(nodeOrToken); + }; + + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.visitNodeOrToken(list.childAt(i)); + } + }; + + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + this.visitNodeOrToken(item); + } + }; + + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.moduleOrRequireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNode(node.moduleReference); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.moduleName); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.body); + }; + + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.body); + }; + + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitOptionalToken(node.publicOrPrivateKeyword); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitNode(node.parameter); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitToken(node.constructorKeyword); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitGetMemberAccessorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetMemberAccessorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitGetAccessorPropertyAssignment = function (node) { + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitToken(node.openParenToken); + this.visitToken(node.closeParenToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetAccessorPropertyAssignment = function (node) { + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitToken(node.openParenToken); + this.visitNode(node.parameter); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitToken(node.semicolonToken); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionTrackingWalker = (function (_super) { + __extends(PositionTrackingWalker, _super); + function PositionTrackingWalker() { + _super.apply(this, arguments); + this._position = 0; + } + PositionTrackingWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + PositionTrackingWalker.prototype.position = function () { + return this._position; + }; + + PositionTrackingWalker.prototype.skip = function (element) { + this._position += element.fullWidth(); + }; + return PositionTrackingWalker; + })(TypeScript.SyntaxWalker); + TypeScript.PositionTrackingWalker = PositionTrackingWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxInformationMap = (function (_super) { + __extends(SyntaxInformationMap, _super); + function SyntaxInformationMap(trackParents, trackPreviousToken) { + _super.call(this); + this.trackParents = trackParents; + this.trackPreviousToken = trackPreviousToken; + this.tokenToInformation = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this.elementToPosition = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._previousToken = null; + this._previousTokenInformation = null; + this._currentPosition = 0; + this._elementToParent = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._parentStack = []; + this._parentStack.push(null); + } + SyntaxInformationMap.create = function (node, trackParents, trackPreviousToken) { + var map = new SyntaxInformationMap(trackParents, trackPreviousToken); + map.visitNode(node); + return map; + }; + + SyntaxInformationMap.prototype.visitNode = function (node) { + this.trackParents && this._elementToParent.add(node, TypeScript.ArrayUtilities.last(this._parentStack)); + this.elementToPosition.add(node, this._currentPosition); + + this.trackParents && this._parentStack.push(node); + _super.prototype.visitNode.call(this, node); + this.trackParents && this._parentStack.pop(); + }; + + SyntaxInformationMap.prototype.visitToken = function (token) { + this.trackParents && this._elementToParent.add(token, TypeScript.ArrayUtilities.last(this._parentStack)); + + if (this.trackPreviousToken) { + var tokenInformation = { + previousToken: this._previousToken, + nextToken: null + }; + + if (this._previousTokenInformation !== null) { + this._previousTokenInformation.nextToken = token; + } + + this._previousToken = token; + this._previousTokenInformation = tokenInformation; + + this.tokenToInformation.add(token, tokenInformation); + } + + this.elementToPosition.add(token, this._currentPosition); + this._currentPosition += token.fullWidth(); + }; + + SyntaxInformationMap.prototype.parent = function (element) { + return this._elementToParent.get(element); + }; + + SyntaxInformationMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxInformationMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxInformationMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxInformationMap.prototype.previousToken = function (token) { + return this.tokenInformation(token).previousToken; + }; + + SyntaxInformationMap.prototype.tokenInformation = function (token) { + return this.tokenToInformation.get(token); + }; + + SyntaxInformationMap.prototype.firstTokenInLineContainingToken = function (token) { + var current = token; + while (true) { + var information = this.tokenInformation(current); + if (this.isFirstTokenInLineWorker(information)) { + break; + } + + current = information.previousToken; + } + + return current; + }; + + SyntaxInformationMap.prototype.isFirstTokenInLine = function (token) { + var information = this.tokenInformation(token); + return this.isFirstTokenInLineWorker(information); + }; + + SyntaxInformationMap.prototype.isFirstTokenInLineWorker = function (information) { + return information.previousToken === null || information.previousToken.hasTrailingNewLine(); + }; + return SyntaxInformationMap; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxInformationMap = SyntaxInformationMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNodeInvariantsChecker = (function (_super) { + __extends(SyntaxNodeInvariantsChecker, _super); + function SyntaxNodeInvariantsChecker() { + _super.apply(this, arguments); + this.tokenTable = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + } + SyntaxNodeInvariantsChecker.checkInvariants = function (node) { + node.accept(new SyntaxNodeInvariantsChecker()); + }; + + SyntaxNodeInvariantsChecker.prototype.visitToken = function (token) { + this.tokenTable.add(token, token); + }; + return SyntaxNodeInvariantsChecker; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxNodeInvariantsChecker = SyntaxNodeInvariantsChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } else { + this.skip(node); + } + }; + return DepthLimitedWalker; + })(TypeScript.PositionTrackingWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + var ExpressionPrecedence; + (function (ExpressionPrecedence) { + ExpressionPrecedence[ExpressionPrecedence["CommaExpressionPrecedence"] = 1] = "CommaExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["AssignmentExpressionPrecedence"] = 2] = "AssignmentExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ConditionalExpressionPrecedence"] = 3] = "ConditionalExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ArrowFunctionPrecedence"] = 4] = "ArrowFunctionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["LogicalOrExpressionPrecedence"] = 5] = "LogicalOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["LogicalAndExpressionPrecedence"] = 6] = "LogicalAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 7] = "BitwiseOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 8] = "BitwiseExclusiveOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 9] = "BitwiseAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["EqualityExpressionPrecedence"] = 10] = "EqualityExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["RelationalExpressionPrecedence"] = 11] = "RelationalExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["ShiftExpressionPrecdence"] = 12] = "ShiftExpressionPrecdence"; + ExpressionPrecedence[ExpressionPrecedence["AdditiveExpressionPrecedence"] = 13] = "AdditiveExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 14] = "MultiplicativeExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["UnaryExpressionPrecedence"] = 15] = "UnaryExpressionPrecedence"; + })(ExpressionPrecedence || (ExpressionPrecedence = {})); + + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 1 << 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1 << 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 1 << 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 1 << 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 1 << 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 1 << 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 1 << 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 1 << 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 1 << 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 1 << 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 1 << 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 1 << 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 1 << 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 1 << 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 1 << 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 1 << 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 1 << 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 1 << 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 1 << 18] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; + + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeArgumentList_Types] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + + var SyntaxCursor = (function () { + function SyntaxCursor(sourceUnit) { + this._elements = []; + this._index = 0; + this._pinCount = 0; + sourceUnit.insertChildrenInto(this._elements, 0); + } + SyntaxCursor.prototype.isFinished = function () { + return this._index === this._elements.length; + }; + + SyntaxCursor.prototype.currentElement = function () { + if (this.isFinished()) { + return null; + } + + return this._elements[this._index]; + }; + + SyntaxCursor.prototype.currentNode = function () { + var element = this.currentElement(); + return element !== null && element.isNode() ? element : null; + }; + + SyntaxCursor.prototype.moveToFirstChild = function () { + if (this.isFinished()) { + return; + } + + var element = this._elements[this._index]; + if (element.isToken()) { + return; + } + + var node = element; + + this._elements.splice(this._index, 1); + + node.insertChildrenInto(this._elements, this._index); + }; + + SyntaxCursor.prototype.moveToNextSibling = function () { + if (this.isFinished()) { + return; + } + + if (this._pinCount > 0) { + this._index++; + return; + } + + this._elements.shift(); + }; + + SyntaxCursor.prototype.getAndPinCursorIndex = function () { + this._pinCount++; + return this._index; + }; + + SyntaxCursor.prototype.releaseAndUnpinCursorIndex = function (index) { + this._pinCount--; + if (this._pinCount === 0) { + } + }; + + SyntaxCursor.prototype.rewindToPinnedCursorIndex = function (index) { + this._index = index; + }; + + SyntaxCursor.prototype.pinCount = function () { + return this._pinCount; + }; + + SyntaxCursor.prototype.moveToFirstToken = function () { + var element; + + while (!this.isFinished()) { + element = this.currentElement(); + if (element.isNode()) { + this.moveToFirstChild(); + continue; + } + + return; + } + }; + + SyntaxCursor.prototype.currentToken = function () { + this.moveToFirstToken(); + if (this.isFinished()) { + return null; + } + + var element = this.currentElement(); + + return element; + }; + + SyntaxCursor.prototype.peekToken = function (n) { + this.moveToFirstToken(); + var pin = this.getAndPinCursorIndex(); + try { + for (var i = 0; i < n; i++) { + this.moveToNextSibling(); + this.moveToFirstToken(); + } + + return this.currentToken(); + } finally { + this.rewindToPinnedCursorIndex(pin); + this.releaseAndUnpinCursorIndex(pin); + } + }; + return SyntaxCursor; + })(); + + var NormalParserSource = (function () { + function NormalParserSource(fileName, text, languageVersion) { + this._previousToken = null; + this._absolutePosition = 0; + this._tokenDiagnostics = []; + this.rewindPointPool = []; + this.rewindPointPoolCount = 0; + this.slidingWindow = new TypeScript.SlidingWindow(this, TypeScript.ArrayUtilities.createArray(32, null), null); + this.scanner = new TypeScript.Scanner(fileName, text, languageVersion); + } + NormalParserSource.prototype.languageVersion = function () { + return this.scanner.languageVersion(); + }; + + NormalParserSource.prototype.currentNode = function () { + return null; + }; + + NormalParserSource.prototype.moveToNextNode = function () { + throw TypeScript.Errors.invalidOperation(); + }; + + NormalParserSource.prototype.absolutePosition = function () { + return this._absolutePosition; + }; + + NormalParserSource.prototype.previousToken = function () { + return this._previousToken; + }; + + NormalParserSource.prototype.tokenDiagnostics = function () { + return this._tokenDiagnostics; + }; + + NormalParserSource.prototype.getOrCreateRewindPoint = function () { + if (this.rewindPointPoolCount === 0) { + return {}; + } + + this.rewindPointPoolCount--; + var result = this.rewindPointPool[this.rewindPointPoolCount]; + this.rewindPointPool[this.rewindPointPoolCount] = null; + return result; + }; + + NormalParserSource.prototype.getRewindPoint = function () { + var slidingWindowIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var rewindPoint = this.getOrCreateRewindPoint(); + + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.previousToken = this._previousToken; + rewindPoint.absolutePosition = this._absolutePosition; + + rewindPoint.pinCount = this.slidingWindow.pinCount(); + + return rewindPoint; + }; + + NormalParserSource.prototype.isPinned = function () { + return this.slidingWindow.pinCount() > 0; + }; + + NormalParserSource.prototype.rewind = function (rewindPoint) { + this.slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + + this._previousToken = rewindPoint.previousToken; + this._absolutePosition = rewindPoint.absolutePosition; + }; + + NormalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this.slidingWindow.releaseAndUnpinAbsoluteIndex((rewindPoint).absoluteIndex); + + this.rewindPointPool[this.rewindPointPoolCount] = rewindPoint; + this.rewindPointPoolCount++; + }; + + NormalParserSource.prototype.fetchMoreItems = function (allowRegularExpression, sourceIndex, window, destinationIndex, spaceAvailable) { + window[destinationIndex] = this.scanner.scan(this._tokenDiagnostics, allowRegularExpression); + return 1; + }; + + NormalParserSource.prototype.peekToken = function (n) { + return this.slidingWindow.peekItemN(n); + }; + + NormalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + this._absolutePosition += currentToken.fullWidth(); + this._previousToken = currentToken; + + this.slidingWindow.moveToNextItem(); + }; + + NormalParserSource.prototype.currentToken = function () { + return this.slidingWindow.currentItem(false); + }; + + NormalParserSource.prototype.removeDiagnosticsOnOrAfterPosition = function (position) { + var tokenDiagnosticsLength = this._tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = this._tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } else { + break; + } + } + + this._tokenDiagnostics.length = tokenDiagnosticsLength; + }; + + NormalParserSource.prototype.resetToPosition = function (absolutePosition, previousToken) { + this._absolutePosition = absolutePosition; + this._previousToken = previousToken; + + this.removeDiagnosticsOnOrAfterPosition(absolutePosition); + + this.slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + + this.scanner.setAbsoluteIndex(absolutePosition); + }; + + NormalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + this.resetToPosition(this._absolutePosition, this._previousToken); + + var token = this.slidingWindow.currentItem(true); + + return token; + }; + return NormalParserSource; + })(); + + var IncrementalParserSource = (function () { + function IncrementalParserSource(oldSyntaxTree, textChangeRange, newText) { + this._changeDelta = 0; + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + this._oldSourceUnitCursor = new SyntaxCursor(oldSourceUnit); + + this._changeRange = IncrementalParserSource.extendToAffectedRange(textChangeRange, oldSourceUnit); + + this._normalParserSource = new NormalParserSource(oldSyntaxTree.fileName(), newText, oldSyntaxTree.languageVersion()); + } + IncrementalParserSource.extendToAffectedRange = function (changeRange, sourceUnit) { + var maxLookahead = 1; + + var start = changeRange.span().start(); + + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = sourceUnit.findToken(start); + + var position = token.fullStart(); + + start = TypeScript.MathPrototype.max(0, position - 1); + } + + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + + return new TypeScript.TextChangeRange(finalSpan, finalLength); + }; + + IncrementalParserSource.prototype.languageVersion = function () { + return this._normalParserSource.languageVersion(); + }; + + IncrementalParserSource.prototype.absolutePosition = function () { + return this._normalParserSource.absolutePosition(); + }; + + IncrementalParserSource.prototype.previousToken = function () { + return this._normalParserSource.previousToken(); + }; + + IncrementalParserSource.prototype.tokenDiagnostics = function () { + return this._normalParserSource.tokenDiagnostics(); + }; + + IncrementalParserSource.prototype.getRewindPoint = function () { + var rewindPoint = this._normalParserSource.getRewindPoint(); + var oldSourceUnitCursorIndex = this._oldSourceUnitCursor.getAndPinCursorIndex(); + + rewindPoint.changeDelta = this._changeDelta; + rewindPoint.changeRange = this._changeRange; + rewindPoint.oldSourceUnitCursorIndex = oldSourceUnitCursorIndex; + + return rewindPoint; + }; + + IncrementalParserSource.prototype.rewind = function (rewindPoint) { + this._changeRange = rewindPoint.changeRange; + this._changeDelta = rewindPoint.changeDelta; + this._oldSourceUnitCursor.rewindToPinnedCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + + this._normalParserSource.rewind(rewindPoint); + }; + + IncrementalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this._oldSourceUnitCursor.releaseAndUnpinCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + this._normalParserSource.releaseRewindPoint(rewindPoint); + }; + + IncrementalParserSource.prototype.canReadFromOldSourceUnit = function () { + if (this._normalParserSource.isPinned()) { + return false; + } + + if (this._changeRange !== null && this._changeRange.newSpan().intersectsWithPosition(this.absolutePosition())) { + return false; + } + + this.syncCursorToNewTextIfBehind(); + + return this._changeDelta === 0 && !this._oldSourceUnitCursor.isFinished(); + }; + + IncrementalParserSource.prototype.currentNode = function () { + if (this.canReadFromOldSourceUnit()) { + return this.tryGetNodeFromOldSourceUnit(); + } + + return null; + }; + + IncrementalParserSource.prototype.currentToken = function () { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryGetTokenFromOldSourceUnit(); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.currentToken(); + }; + + IncrementalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + return this._normalParserSource.currentTokenAllowingRegularExpression(); + }; + + IncrementalParserSource.prototype.syncCursorToNewTextIfBehind = function () { + while (true) { + if (this._oldSourceUnitCursor.isFinished()) { + break; + } + + if (this._changeDelta >= 0) { + break; + } + + var currentElement = this._oldSourceUnitCursor.currentElement(); + + if (currentElement.isNode() && (currentElement.fullWidth() > Math.abs(this._changeDelta))) { + this._oldSourceUnitCursor.moveToFirstChild(); + } else { + this._oldSourceUnitCursor.moveToNextSibling(); + + this._changeDelta += currentElement.fullWidth(); + } + } + }; + + IncrementalParserSource.prototype.intersectsWithChangeRangeSpanInOriginalText = function (start, length) { + return this._changeRange !== null && this._changeRange.span().intersectsWith(start, length); + }; + + IncrementalParserSource.prototype.tryGetNodeFromOldSourceUnit = function () { + while (true) { + var node = this._oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + + if (!this.intersectsWithChangeRangeSpanInOriginalText(this.absolutePosition(), node.fullWidth())) { + if (!node.isIncrementallyUnusable()) { + return node; + } + } + + this._oldSourceUnitCursor.moveToFirstChild(); + } + }; + + IncrementalParserSource.prototype.canReuseTokenFromOldSourceUnit = function (position, token) { + if (token !== null) { + if (!this.intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable()) { + return true; + } + } + } + + return false; + }; + + IncrementalParserSource.prototype.tryGetTokenFromOldSourceUnit = function () { + var token = this._oldSourceUnitCursor.currentToken(); + + return this.canReuseTokenFromOldSourceUnit(this.absolutePosition(), token) ? token : null; + }; + + IncrementalParserSource.prototype.peekToken = function (n) { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.peekToken(n); + }; + + IncrementalParserSource.prototype.tryPeekTokenFromOldSourceUnit = function (n) { + var currentPosition = this.absolutePosition(); + for (var i = 0; i < n; i++) { + var interimToken = this._oldSourceUnitCursor.peekToken(i); + if (!this.canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + + currentPosition += interimToken.fullWidth(); + } + + var token = this._oldSourceUnitCursor.peekToken(n); + return this.canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + }; + + IncrementalParserSource.prototype.moveToNextNode = function () { + var currentElement = this._oldSourceUnitCursor.currentElement(); + var currentNode = this._oldSourceUnitCursor.currentNode(); + + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentNode.fullWidth(); + var previousToken = currentNode.lastToken(); + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + }; + + IncrementalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + + if (this._oldSourceUnitCursor.currentToken() === currentToken) { + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentToken.fullWidth(); + var previousToken = currentToken; + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + } else { + this._changeDelta -= currentToken.fullWidth(); + + this._normalParserSource.moveToNextToken(); + + if (this._changeRange !== null) { + var changeRangeSpanInNewText = this._changeRange.newSpan(); + if (this.absolutePosition() >= changeRangeSpanInNewText.end()) { + this._changeDelta += this._changeRange.newLength() - this._changeRange.span().length(); + this._changeRange = null; + } + } + } + }; + return IncrementalParserSource; + })(); + + var ParserImpl = (function () { + function ParserImpl(fileName, lineMap, source, parseOptions) { + this.listParsingState = 0; + this.isInStrictMode = false; + this.diagnostics = []; + this.factory = TypeScript.Syntax.normalModeFactory; + this.mergeTokensStorage = []; + this.arrayPool = []; + this.fileName = fileName; + this.lineMap = lineMap; + this.source = source; + this.parseOptions = parseOptions; + } + ParserImpl.prototype.getRewindPoint = function () { + var rewindPoint = this.source.getRewindPoint(); + + rewindPoint.diagnosticsCount = this.diagnostics.length; + + rewindPoint.isInStrictMode = this.isInStrictMode; + rewindPoint.listParsingState = this.listParsingState; + + return rewindPoint; + }; + + ParserImpl.prototype.rewind = function (rewindPoint) { + this.source.rewind(rewindPoint); + + this.diagnostics.length = rewindPoint.diagnosticsCount; + }; + + ParserImpl.prototype.releaseRewindPoint = function (rewindPoint) { + this.source.releaseRewindPoint(rewindPoint); + }; + + ParserImpl.prototype.currentTokenStart = function () { + return this.source.absolutePosition() + this.currentToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenStart = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.source.absolutePosition() - this.previousToken().fullWidth() + this.previousToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenEnd = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.previousTokenStart() + this.previousToken().width(); + }; + + ParserImpl.prototype.currentNode = function () { + var node = this.source.currentNode(); + + if (node === null || node.parsedInStrictMode() !== this.isInStrictMode) { + return null; + } + + return node; + }; + + ParserImpl.prototype.currentToken = function () { + return this.source.currentToken(); + }; + + ParserImpl.prototype.currentTokenAllowingRegularExpression = function () { + return this.source.currentTokenAllowingRegularExpression(); + }; + + ParserImpl.prototype.peekToken = function (n) { + return this.source.peekToken(n); + }; + + ParserImpl.prototype.eatAnyToken = function () { + var token = this.currentToken(); + this.moveToNextToken(); + return token; + }; + + ParserImpl.prototype.moveToNextToken = function () { + this.source.moveToNextToken(); + }; + + ParserImpl.prototype.previousToken = function () { + return this.source.previousToken(); + }; + + ParserImpl.prototype.eatNode = function () { + var node = this.source.currentNode(); + this.source.moveToNextNode(); + return node; + }; + + ParserImpl.prototype.eatToken = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.tryEatToken = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatToken(kind); + } + + return null; + }; + + ParserImpl.prototype.tryEatKeyword = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatKeyword(kind); + } + + return null; + }; + + ParserImpl.prototype.eatKeyword = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.isIdentifier = function (token) { + var tokenKind = token.tokenKind; + + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + + if (tokenKind >= 51 /* FirstFutureReservedStrictKeyword */) { + if (tokenKind <= 59 /* LastFutureReservedStrictKeyword */) { + return !this.isInStrictMode; + } + + return tokenKind <= 70 /* LastTypeScriptKeyword */; + } + + return false; + }; + + ParserImpl.prototype.eatIdentifierNameToken = function () { + var token = this.currentToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + this.moveToNextToken(); + return token; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)) { + this.moveToNextToken(); + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.eatIdentifierToken = function () { + var token = this.currentToken(); + if (this.isIdentifier(token)) { + this.moveToNextToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + return token; + } + + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.canEatAutomaticSemicolon = function (allowWithoutNewLine) { + var token = this.currentToken(); + + if (token.tokenKind === 10 /* EndOfFileToken */) { + return true; + } + + if (token.tokenKind === 72 /* CloseBraceToken */) { + return true; + } + + if (allowWithoutNewLine) { + return true; + } + + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.canEatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 79 /* SemicolonToken */) { + return true; + } + + return this.canEatAutomaticSemicolon(allowWithoutNewline); + }; + + ParserImpl.prototype.eatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 79 /* SemicolonToken */) { + return this.eatToken(79 /* SemicolonToken */); + } + + if (this.canEatAutomaticSemicolon(allowWithoutNewline)) { + var semicolonToken = TypeScript.Syntax.emptyToken(79 /* SemicolonToken */); + + if (!this.parseOptions.allowAutomaticSemicolonInsertion()) { + this.addDiagnostic(new TypeScript.SyntaxDiagnostic(this.fileName, this.previousTokenEnd(), 0, 11 /* Automatic_semicolon_insertion_not_allowed */, null)); + } + + return semicolonToken; + } + + return this.eatToken(79 /* SemicolonToken */); + }; + + ParserImpl.prototype.isKeyword = function (kind) { + if (kind >= TypeScript.SyntaxKind.FirstKeyword) { + if (kind <= 50 /* LastFutureReservedKeyword */) { + return true; + } + + if (this.isInStrictMode) { + return kind <= 59 /* LastFutureReservedStrictKeyword */; + } + } + + return false; + }; + + ParserImpl.prototype.createMissingToken = function (expectedKind, actual) { + var diagnostic = this.getExpectedTokenDiagnostic(expectedKind, actual); + this.addDiagnostic(diagnostic); + + return TypeScript.Syntax.emptyToken(expectedKind); + }; + + ParserImpl.prototype.getExpectedTokenDiagnostic = function (expectedKind, actual) { + var token = this.currentToken(); + + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + return new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 9 /* _0_expected */, [TypeScript.SyntaxFacts.getText(expectedKind)]); + } else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.tokenKind)) { + return new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 10 /* Identifier_expected__0__is_a_keyword */, [TypeScript.SyntaxFacts.getText(actual.tokenKind)]); + } else { + return new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 7 /* Identifier_expected */, null); + } + } + }; + + ParserImpl.getPrecedence = function (expressionKind) { + switch (expressionKind) { + case 172 /* CommaExpression */: + return 1 /* CommaExpressionPrecedence */; + + case 173 /* AssignmentExpression */: + case 174 /* AddAssignmentExpression */: + case 175 /* SubtractAssignmentExpression */: + case 176 /* MultiplyAssignmentExpression */: + case 177 /* DivideAssignmentExpression */: + case 178 /* ModuloAssignmentExpression */: + case 179 /* AndAssignmentExpression */: + case 180 /* ExclusiveOrAssignmentExpression */: + case 181 /* OrAssignmentExpression */: + case 182 /* LeftShiftAssignmentExpression */: + case 183 /* SignedRightShiftAssignmentExpression */: + case 184 /* UnsignedRightShiftAssignmentExpression */: + return 2 /* AssignmentExpressionPrecedence */; + + case 185 /* ConditionalExpression */: + return 3 /* ConditionalExpressionPrecedence */; + + case 186 /* LogicalOrExpression */: + return 5 /* LogicalOrExpressionPrecedence */; + + case 187 /* LogicalAndExpression */: + return 6 /* LogicalAndExpressionPrecedence */; + + case 188 /* BitwiseOrExpression */: + return 7 /* BitwiseOrExpressionPrecedence */; + + case 189 /* BitwiseExclusiveOrExpression */: + return 8 /* BitwiseExclusiveOrExpressionPrecedence */; + + case 190 /* BitwiseAndExpression */: + return 9 /* BitwiseAndExpressionPrecedence */; + + case 191 /* EqualsWithTypeConversionExpression */: + case 192 /* NotEqualsWithTypeConversionExpression */: + case 193 /* EqualsExpression */: + case 194 /* NotEqualsExpression */: + return 10 /* EqualityExpressionPrecedence */; + + case 195 /* LessThanExpression */: + case 196 /* GreaterThanExpression */: + case 197 /* LessThanOrEqualExpression */: + case 198 /* GreaterThanOrEqualExpression */: + case 199 /* InstanceOfExpression */: + case 200 /* InExpression */: + return 11 /* RelationalExpressionPrecedence */; + + case 201 /* LeftShiftExpression */: + case 202 /* SignedRightShiftExpression */: + case 203 /* UnsignedRightShiftExpression */: + return 12 /* ShiftExpressionPrecdence */; + + case 207 /* AddExpression */: + case 208 /* SubtractExpression */: + return 13 /* AdditiveExpressionPrecedence */; + + case 204 /* MultiplyExpression */: + case 205 /* DivideExpression */: + case 206 /* ModuloExpression */: + return 14 /* MultiplicativeExpressionPrecedence */; + + case 163 /* PlusExpression */: + case 164 /* NegateExpression */: + case 165 /* BitwiseNotExpression */: + case 166 /* LogicalNotExpression */: + case 169 /* DeleteExpression */: + case 170 /* TypeOfExpression */: + case 171 /* VoidExpression */: + case 167 /* PreIncrementExpression */: + case 168 /* PreDecrementExpression */: + return 15 /* UnaryExpressionPrecedence */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ParserImpl.prototype.addSkippedTokenAfterNodeOrToken = function (nodeOrToken, skippedToken) { + if (nodeOrToken.isToken()) { + return this.addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } else if (nodeOrToken.isNode()) { + return this.addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.addSkippedTokenAfterNode = function (node, skippedToken) { + var oldToken = node.lastToken(); + var newToken = this.addSkippedTokenAfterToken(oldToken, skippedToken); + + return node.replaceToken(oldToken, newToken); + }; + + ParserImpl.prototype.addSkippedTokensBeforeNode = function (node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = node.firstToken(); + var newToken = this.addSkippedTokensBeforeToken(oldToken, skippedTokens); + + return node.replaceToken(oldToken, newToken); + } + + return node; + }; + + ParserImpl.prototype.addSkippedTokensBeforeToken = function (token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(leadingTrivia, skippedTokens[i]); + } + + this.addTriviaTo(token.leadingTrivia(), leadingTrivia); + + this.returnArray(skippedTokens); + return token.withLeadingTrivia(TypeScript.Syntax.triviaList(leadingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokensAfterToken = function (token, skippedTokens) { + if (skippedTokens.length === 0) { + this.returnArray(skippedTokens); + return token; + } + + var trailingTrivia = token.trailingTrivia().toArray(); + + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + + this.returnArray(skippedTokens); + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenAfterToken = function (token, skippedToken) { + var trailingTrivia = token.trailingTrivia().toArray(); + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenToTriviaArray = function (array, skippedToken) { + this.addTriviaTo(skippedToken.leadingTrivia(), array); + + var trimmedToken = skippedToken.withLeadingTrivia(TypeScript.Syntax.emptyTriviaList).withTrailingTrivia(TypeScript.Syntax.emptyTriviaList); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken)); + + this.addTriviaTo(skippedToken.trailingTrivia(), array); + }; + + ParserImpl.prototype.addTriviaTo = function (list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + }; + + ParserImpl.prototype.parseSyntaxTree = function (isDeclaration) { + var sourceUnit = this.parseSourceUnit(); + + var allDiagnostics = this.source.tokenDiagnostics().concat(this.diagnostics); + allDiagnostics.sort(function (a, b) { + return a.start() - b.start(); + }); + + return new TypeScript.SyntaxTree(sourceUnit, isDeclaration, allDiagnostics, this.fileName, this.lineMap, this.source.languageVersion(), this.parseOptions); + }; + + ParserImpl.prototype.setStrictMode = function (isInStrictMode) { + this.isInStrictMode = isInStrictMode; + this.factory = isInStrictMode ? TypeScript.Syntax.strictModeFactory : TypeScript.Syntax.normalModeFactory; + }; + + ParserImpl.prototype.parseSourceUnit = function () { + var savedIsInStrictMode = this.isInStrictMode; + + var result = this.parseSyntaxList(1 /* SourceUnit_ModuleElements */, ParserImpl.updateStrictModeState); + var moduleElements = result.list; + + this.setStrictMode(savedIsInStrictMode); + + var sourceUnit = this.factory.sourceUnit(moduleElements, this.currentToken()); + sourceUnit = this.addSkippedTokensBeforeNode(sourceUnit, result.skippedTokens); + + return sourceUnit; + }; + + ParserImpl.updateStrictModeState = function (parser, items) { + if (!parser.isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + + parser.setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + }; + + ParserImpl.prototype.isModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return true; + } + + return this.isImportDeclaration() || this.isExportAssignment() || this.isModuleDeclaration() || this.isInterfaceDeclaration() || this.isClassDeclaration() || this.isEnumDeclaration() || this.isStatement(inErrorRecovery); + }; + + ParserImpl.prototype.parseModuleElement = function () { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return this.eatNode(); + } + + if (this.isImportDeclaration()) { + return this.parseImportDeclaration(); + } else if (this.isExportAssignment()) { + return this.parseExportAssignment(); + } else if (this.isModuleDeclaration()) { + return this.parseModuleDeclaration(); + } else if (this.isInterfaceDeclaration()) { + return this.parseInterfaceDeclaration(); + } else if (this.isClassDeclaration()) { + return this.parseClassDeclaration(); + } else if (this.isEnumDeclaration()) { + return this.parseEnumDeclaration(); + } else if (this.isStatement(false)) { + return this.parseStatement(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isImportDeclaration = function () { + return this.currentToken().tokenKind === 49 /* ImportKeyword */; + }; + + ParserImpl.prototype.parseImportDeclaration = function () { + var importKeyword = this.eatKeyword(49 /* ImportKeyword */); + var identifier = this.eatIdentifierToken(); + var equalsToken = this.eatToken(108 /* EqualsToken */); + var moduleReference = this.parseModuleReference(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.importDeclaration(importKeyword, identifier, equalsToken, moduleReference, semicolonToken); + }; + + ParserImpl.prototype.isExportAssignment = function () { + return this.currentToken().tokenKind === 47 /* ExportKeyword */ && this.peekToken(1).tokenKind === 108 /* EqualsToken */; + }; + + ParserImpl.prototype.parseExportAssignment = function () { + var exportKeyword = this.eatKeyword(47 /* ExportKeyword */); + var equalsToken = this.eatToken(108 /* EqualsToken */); + var identifier = this.eatIdentifierToken(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.exportAssignment(exportKeyword, equalsToken, identifier, semicolonToken); + }; + + ParserImpl.prototype.parseModuleReference = function () { + if (this.isExternalModuleReference()) { + return this.parseExternalModuleReference(); + } else { + return this.parseModuleNameModuleReference(); + } + }; + + ParserImpl.prototype.isExternalModuleReference = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 66 /* ModuleKeyword */ || token0.tokenKind === 67 /* RequireKeyword */) { + return this.peekToken(1).tokenKind === 73 /* OpenParenToken */; + } + + return false; + }; + + ParserImpl.prototype.parseExternalModuleReference = function () { + var moduleOrRequireKeyword = this.eatAnyToken(); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var stringLiteral = this.eatToken(14 /* StringLiteral */); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + return this.factory.externalModuleReference(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken); + }; + + ParserImpl.prototype.parseModuleNameModuleReference = function () { + var name = this.parseName(); + return this.factory.moduleNameModuleReference(name); + }; + + ParserImpl.prototype.parseIdentifierName = function () { + var identifierName = this.eatIdentifierNameToken(); + return identifierName; + }; + + ParserImpl.prototype.isName = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.tryParseTypeArgumentList = function (inExpression) { + if (this.currentToken().kind() !== 81 /* LessThanToken */) { + return null; + } + + var lessThanToken; + var greaterThanToken; + var result; + var typeArguments; + + if (!inExpression) { + lessThanToken = this.eatToken(81 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } + + var rewindPoint = this.getRewindPoint(); + try { + lessThanToken = this.eatToken(81 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + + if (greaterThanToken.fullWidth() === 0 || !this.canFollowTypeArgumentListInExpression(this.currentToken().kind())) { + this.rewind(rewindPoint); + return null; + } + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.canFollowTypeArgumentListInExpression = function (kind) { + switch (kind) { + case 73 /* OpenParenToken */: + case 77 /* DotToken */: + + case 74 /* CloseParenToken */: + case 76 /* CloseBracketToken */: + case 107 /* ColonToken */: + case 79 /* SemicolonToken */: + case 80 /* CommaToken */: + case 106 /* QuestionToken */: + case 85 /* EqualsEqualsToken */: + case 88 /* EqualsEqualsEqualsToken */: + case 87 /* ExclamationEqualsToken */: + case 89 /* ExclamationEqualsEqualsToken */: + case 104 /* AmpersandAmpersandToken */: + case 105 /* BarBarToken */: + case 101 /* CaretToken */: + case 99 /* AmpersandToken */: + case 100 /* BarToken */: + case 72 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseName = function () { + var shouldContinue = this.isIdentifier(this.currentToken()); + var current = this.eatIdentifierToken(); + + while (shouldContinue && this.currentToken().tokenKind === 77 /* DotToken */) { + var dotToken = this.eatToken(77 /* DotToken */); + + var currentToken = this.currentToken(); + var identifierName; + + if (TypeScript.SyntaxFacts.isAnyKeyword(currentToken.tokenKind) && this.previousToken().hasTrailingNewLine() && !currentToken.hasTrailingNewLine() && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.peekToken(1))) { + identifierName = this.createMissingToken(11 /* IdentifierName */, currentToken); + } else { + identifierName = this.eatIdentifierNameToken(); + } + + current = this.factory.qualifiedName(current, dotToken, identifierName); + + shouldContinue = identifierName.fullWidth() > 0; + } + + return current; + }; + + ParserImpl.prototype.isEnumDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 46 /* EnumKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 46 /* EnumKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseEnumDeclaration = function () { + var modifiers = this.parseModifiers(); + var enumKeyword = this.eatKeyword(46 /* EnumKeyword */); + var identifier = this.eatIdentifierToken(); + + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList; + + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(256 /* EnumDeclaration_EnumElements */); + enumElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.enumDeclaration(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken); + }; + + ParserImpl.prototype.isEnumElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return true; + } + + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseEnumElement = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return this.eatNode(); + } + + var propertyName = this.eatPropertyName(); + var equalsValueClause = null; + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.enumElement(propertyName, equalsValueClause); + }; + + ParserImpl.isModifier = function (token) { + switch (token.tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 47 /* ExportKeyword */: + case 64 /* DeclareKeyword */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.modifierCount = function () { + var modifierCount = 0; + while (true) { + if (ParserImpl.isModifier(this.peekToken(modifierCount))) { + modifierCount++; + continue; + } + + break; + } + + return modifierCount; + }; + + ParserImpl.prototype.parseModifiers = function () { + var tokens = this.getArray(); + + while (true) { + if (ParserImpl.isModifier(this.currentToken())) { + tokens.push(this.eatAnyToken()); + continue; + } + + break; + } + + var result = TypeScript.Syntax.list(tokens); + + this.returnZeroOrOneLengthArray(tokens); + + return result; + }; + + ParserImpl.prototype.isClassDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 44 /* ClassKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 44 /* ClassKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseHeritageClauses = function () { + var heritageClauses = TypeScript.Syntax.emptyList; + + if (this.isHeritageClause()) { + var result = this.parseSyntaxList(1024 /* ClassOrInterfaceDeclaration_HeritageClauses */); + heritageClauses = result.list; + TypeScript.Debug.assert(result.skippedTokens.length === 0); + } + + return heritageClauses; + }; + + ParserImpl.prototype.parseClassDeclaration = function () { + var modifiers = this.parseModifiers(); + + var classKeyword = this.eatKeyword(44 /* ClassKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList; + + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(2 /* ClassDeclaration_ClassElements */); + + classElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + return this.factory.classDeclaration(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken); + }; + + ParserImpl.prototype.isConstructorDeclaration = function () { + return this.currentToken().tokenKind === 63 /* ConstructorKeyword */; + }; + + ParserImpl.isPublicOrPrivateKeyword = function (token) { + return token.tokenKind === 57 /* PublicKeyword */ || token.tokenKind === 55 /* PrivateKeyword */; + }; + + ParserImpl.prototype.isMemberAccessorDeclaration = function (inErrorRecovery) { + var index = this.modifierCount(); + + if (this.peekToken(index).tokenKind !== 65 /* GetKeyword */ && this.peekToken(index).tokenKind !== 69 /* SetKeyword */) { + return false; + } + + index++; + return this.isPropertyName(this.peekToken(index), inErrorRecovery); + }; + + ParserImpl.prototype.parseMemberAccessorDeclaration = function () { + var modifiers = this.parseModifiers(); + + if (this.currentToken().tokenKind === 65 /* GetKeyword */) { + return this.parseGetMemberAccessorDeclaration(modifiers); + } else if (this.currentToken().tokenKind === 69 /* SetKeyword */) { + return this.parseSetMemberAccessorDeclaration(modifiers); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseGetMemberAccessorDeclaration = function (modifiers) { + var getKeyword = this.eatKeyword(65 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, false); + + return this.factory.getMemberAccessorDeclaration(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block); + }; + + ParserImpl.prototype.parseSetMemberAccessorDeclaration = function (modifiers) { + var setKeyword = this.eatKeyword(69 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var block = this.parseBlock(false, false); + + return this.factory.setMemberAccessorDeclaration(modifiers, setKeyword, propertyName, parameterList, block); + }; + + ParserImpl.prototype.isClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return true; + } + + return this.isConstructorDeclaration() || this.isMemberFunctionDeclaration(inErrorRecovery) || this.isMemberAccessorDeclaration(inErrorRecovery) || this.isMemberVariableDeclaration(inErrorRecovery) || this.isIndexSignature(); + }; + + ParserImpl.prototype.parseConstructorDeclaration = function () { + var constructorKeyword = this.eatKeyword(63 /* ConstructorKeyword */); + var parameterList = this.parseParameterList(); + + var semicolonToken = null; + var block = null; + + if (this.isBlock()) { + block = this.parseBlock(false, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.constructorDeclaration(constructorKeyword, parameterList, block, semicolonToken); + }; + + ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isCallSignature(index + 1)) { + return true; + } + + if (ParserImpl.isModifier(token)) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberFunctionDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isCallSignature(1)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + var parseBlockEvenWithNoOpenBrace = callSignature !== newCallSignature; + callSignature = newCallSignature; + + var block = null; + var semicolon = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolon = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.memberFunctionDeclaration(modifiers, propertyName, callSignature, block, semicolon); + }; + + ParserImpl.prototype.isDefinitelyMemberVariablePropertyName = function (index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(this.peekToken(index).tokenKind)) { + switch (this.peekToken(index + 1).tokenKind) { + case 79 /* SemicolonToken */: + case 108 /* EqualsToken */: + case 107 /* ColonToken */: + case 72 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } else { + return true; + } + }; + + ParserImpl.prototype.isMemberVariableDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isDefinitelyMemberVariablePropertyName(index)) { + return true; + } + + if (ParserImpl.isModifier(this.peekToken(index))) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberVariableDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isDefinitelyMemberVariablePropertyName(0)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var variableDeclarator = this.parseVariableDeclarator(true, true); + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.memberVariableDeclaration(modifiers, variableDeclarator, semicolon); + }; + + ParserImpl.prototype.parseClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return this.eatNode(); + } + + if (this.isConstructorDeclaration()) { + return this.parseConstructorDeclaration(); + } else if (this.isMemberFunctionDeclaration(inErrorRecovery)) { + return this.parseMemberFunctionDeclaration(); + } else if (this.isMemberAccessorDeclaration(inErrorRecovery)) { + return this.parseMemberAccessorDeclaration(); + } else if (this.isMemberVariableDeclaration(inErrorRecovery)) { + return this.parseMemberVariableDeclaration(); + } else if (this.isIndexSignature()) { + return this.parseIndexSignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.tryAddUnexpectedEqualsGreaterThanToken = function (callSignature) { + var token0 = this.currentToken(); + + var hasEqualsGreaterThanToken = token0.tokenKind === 86 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token0.width(), 16 /* Unexpected_token_ */, []); + this.addDiagnostic(diagnostic); + + var token = this.eatAnyToken(); + return this.addSkippedTokenAfterNode(callSignature, token0); + } + + return callSignature; + }; + + ParserImpl.prototype.isFunctionDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 27 /* FunctionKeyword */; + }; + + ParserImpl.prototype.parseFunctionDeclaration = function () { + var modifiers = this.parseModifiers(); + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = this.eatIdentifierToken(); + var callSignature = this.parseCallSignature(false); + + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + var parseBlockEvenWithNoOpenBrace = callSignature !== newCallSignature; + callSignature = newCallSignature; + + var semicolonToken = null; + var block = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.functionDeclaration(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isModuleDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 66 /* ModuleKeyword */) { + return true; + } + + if (this.currentToken().tokenKind === 66 /* ModuleKeyword */) { + var token1 = this.peekToken(1); + return this.isIdentifier(token1) || token1.tokenKind === 14 /* StringLiteral */; + } + + return false; + }; + + ParserImpl.prototype.parseModuleDeclaration = function () { + var modifiers = this.parseModifiers(); + var moduleKeyword = this.eatKeyword(66 /* ModuleKeyword */); + + var moduleName = null; + var stringLiteral = null; + + if (this.currentToken().tokenKind === 14 /* StringLiteral */) { + stringLiteral = this.eatToken(14 /* StringLiteral */); + } else { + moduleName = this.parseName(); + } + + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var moduleElements = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(4 /* ModuleDeclaration_ModuleElements */); + moduleElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.moduleDeclaration(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken); + }; + + ParserImpl.prototype.isInterfaceDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 52 /* InterfaceKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 52 /* InterfaceKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseInterfaceDeclaration = function () { + var modifiers = this.parseModifiers(); + var interfaceKeyword = this.eatKeyword(52 /* InterfaceKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + + var objectType = this.parseObjectType(); + return this.factory.interfaceDeclaration(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, objectType); + }; + + ParserImpl.prototype.parseObjectType = function () { + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var typeMembers = TypeScript.Syntax.emptySeparatedList; + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(512 /* ObjectType_TypeMembers */); + typeMembers = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + return this.factory.objectType(openBraceToken, typeMembers, closeBraceToken); + }; + + ParserImpl.prototype.isTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return true; + } + + return this.isCallSignature(0) || this.isConstructSignature() || this.isIndexSignature() || this.isMethodSignature(inErrorRecovery) || this.isPropertySignature(inErrorRecovery); + }; + + ParserImpl.prototype.parseTypeMember = function () { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return this.eatNode(); + } + + if (this.isCallSignature(0)) { + return this.parseCallSignature(false); + } else if (this.isConstructSignature()) { + return this.parseConstructSignature(); + } else if (this.isIndexSignature()) { + return this.parseIndexSignature(); + } else if (this.isMethodSignature(false)) { + return this.parseMethodSignature(); + } else if (this.isPropertySignature(false)) { + return this.parsePropertySignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseConstructSignature = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var callSignature = this.parseCallSignature(false); + + return this.factory.constructSignature(newKeyword, callSignature); + }; + + ParserImpl.prototype.parseIndexSignature = function () { + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + var parameter = this.parseParameter(); + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.indexSignature(openBracketToken, parameter, closeBracketToken, typeAnnotation); + }; + + ParserImpl.prototype.parseMethodSignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(106 /* QuestionToken */); + var callSignature = this.parseCallSignature(false); + + return this.factory.methodSignature(propertyName, questionToken, callSignature); + }; + + ParserImpl.prototype.parsePropertySignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(106 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.propertySignature(propertyName, questionToken, typeAnnotation); + }; + + ParserImpl.prototype.isCallSignature = function (tokenIndex) { + var tokenKind = this.peekToken(tokenIndex).tokenKind; + return tokenKind === 73 /* OpenParenToken */ || tokenKind === 81 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructSignature = function () { + if (this.currentToken().tokenKind !== 31 /* NewKeyword */) { + return false; + } + + var token1 = this.peekToken(1); + return token1.tokenKind === 81 /* LessThanToken */ || token1.tokenKind === 73 /* OpenParenToken */; + }; + + ParserImpl.prototype.isIndexSignature = function () { + return this.currentToken().tokenKind === 75 /* OpenBracketToken */; + }; + + ParserImpl.prototype.isMethodSignature = function (inErrorRecovery) { + if (this.isPropertyName(this.currentToken(), inErrorRecovery)) { + if (this.isCallSignature(1)) { + return true; + } + + if (this.peekToken(1).tokenKind === 106 /* QuestionToken */ && this.isCallSignature(2)) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPropertySignature = function (inErrorRecovery) { + var currentToken = this.currentToken(); + + if (ParserImpl.isModifier(currentToken) && !currentToken.hasTrailingNewLine() && this.isPropertyName(this.peekToken(1), inErrorRecovery)) { + return false; + } + + return this.isPropertyName(currentToken, inErrorRecovery); + }; + + ParserImpl.prototype.isHeritageClause = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */; + }; + + ParserImpl.prototype.isNotHeritageClauseTypeName = function () { + if (this.currentToken().tokenKind === 51 /* ImplementsKeyword */ || this.currentToken().tokenKind === 48 /* ExtendsKeyword */) { + return this.isIdentifier(this.peekToken(1)); + } + + return false; + }; + + ParserImpl.prototype.isHeritageClauseTypeName = function () { + if (this.isName()) { + return !this.isNotHeritageClauseTypeName(); + } + + return false; + }; + + ParserImpl.prototype.parseHeritageClause = function () { + var extendsOrImplementsKeyword = this.eatAnyToken(); + TypeScript.Debug.assert(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ || extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + + var result = this.parseSeparatedSyntaxList(2048 /* HeritageClause_TypeNameList */); + var typeNames = result.list; + extendsOrImplementsKeyword = this.addSkippedTokensAfterToken(extendsOrImplementsKeyword, result.skippedTokens); + + return this.factory.heritageClause(extendsOrImplementsKeyword, typeNames); + }; + + ParserImpl.prototype.isStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return true; + } + + switch (this.currentToken().tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = this.peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + } + + return this.isVariableStatement() || this.isLabeledStatement() || this.isFunctionDeclaration() || this.isIfStatement() || this.isBlock() || this.isExpressionStatement() || this.isReturnStatement() || this.isSwitchStatement() || this.isThrowStatement() || this.isBreakStatement() || this.isContinueStatement() || this.isForOrForInStatement() || this.isEmptyStatement(inErrorRecovery) || this.isWhileStatement() || this.isWithStatement() || this.isDoStatement() || this.isTryStatement() || this.isDebuggerStatement(); + }; + + ParserImpl.prototype.parseStatement = function () { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return this.eatNode(); + } + + if (this.isVariableStatement()) { + return this.parseVariableStatement(); + } else if (this.isLabeledStatement()) { + return this.parseLabeledStatement(); + } else if (this.isFunctionDeclaration()) { + return this.parseFunctionDeclaration(); + } else if (this.isIfStatement()) { + return this.parseIfStatement(); + } else if (this.isBlock()) { + return this.parseBlock(false, false); + } else if (this.isReturnStatement()) { + return this.parseReturnStatement(); + } else if (this.isSwitchStatement()) { + return this.parseSwitchStatement(); + } else if (this.isThrowStatement()) { + return this.parseThrowStatement(); + } else if (this.isBreakStatement()) { + return this.parseBreakStatement(); + } else if (this.isContinueStatement()) { + return this.parseContinueStatement(); + } else if (this.isForOrForInStatement()) { + return this.parseForOrForInStatement(); + } else if (this.isEmptyStatement(false)) { + return this.parseEmptyStatement(); + } else if (this.isWhileStatement()) { + return this.parseWhileStatement(); + } else if (this.isWithStatement()) { + return this.parseWithStatement(); + } else if (this.isDoStatement()) { + return this.parseDoStatement(); + } else if (this.isTryStatement()) { + return this.parseTryStatement(); + } else if (this.isDebuggerStatement()) { + return this.parseDebuggerStatement(); + } else { + return this.parseExpressionStatement(); + } + }; + + ParserImpl.prototype.isDebuggerStatement = function () { + return this.currentToken().tokenKind === 19 /* DebuggerKeyword */; + }; + + ParserImpl.prototype.parseDebuggerStatement = function () { + var debuggerKeyword = this.eatKeyword(19 /* DebuggerKeyword */); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.debuggerStatement(debuggerKeyword, semicolonToken); + }; + + ParserImpl.prototype.isDoStatement = function () { + return this.currentToken().tokenKind === 22 /* DoKeyword */; + }; + + ParserImpl.prototype.parseDoStatement = function () { + var doKeyword = this.eatKeyword(22 /* DoKeyword */); + var statement = this.parseStatement(); + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(true); + + return this.factory.doStatement(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + }; + + ParserImpl.prototype.isLabeledStatement = function () { + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 107 /* ColonToken */; + }; + + ParserImpl.prototype.parseLabeledStatement = function () { + var identifier = this.eatIdentifierToken(); + var colonToken = this.eatToken(107 /* ColonToken */); + var statement = this.parseStatement(); + + return this.factory.labeledStatement(identifier, colonToken, statement); + }; + + ParserImpl.prototype.isTryStatement = function () { + return this.currentToken().tokenKind === 38 /* TryKeyword */; + }; + + ParserImpl.prototype.parseTryStatement = function () { + var tryKeyword = this.eatKeyword(38 /* TryKeyword */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 64 /* TryBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + var catchClause = null; + if (this.isCatchClause()) { + catchClause = this.parseCatchClause(); + } + + var finallyClause = null; + if (catchClause === null || this.isFinallyClause()) { + finallyClause = this.parseFinallyClause(); + } + + return this.factory.tryStatement(tryKeyword, block, catchClause, finallyClause); + }; + + ParserImpl.prototype.isCatchClause = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */; + }; + + ParserImpl.prototype.parseCatchClause = function () { + var catchKeyword = this.eatKeyword(17 /* CatchKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var identifier = this.eatIdentifierToken(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 128 /* CatchBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + return this.factory.catchClause(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block); + }; + + ParserImpl.prototype.isFinallyClause = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.parseFinallyClause = function () { + var finallyKeyword = this.eatKeyword(25 /* FinallyKeyword */); + var block = this.parseBlock(false, false); + + return this.factory.finallyClause(finallyKeyword, block); + }; + + ParserImpl.prototype.isWithStatement = function () { + return this.currentToken().tokenKind === 43 /* WithKeyword */; + }; + + ParserImpl.prototype.parseWithStatement = function () { + var withKeyword = this.eatKeyword(43 /* WithKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.withStatement(withKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isWhileStatement = function () { + return this.currentToken().tokenKind === 42 /* WhileKeyword */; + }; + + ParserImpl.prototype.parseWhileStatement = function () { + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.whileStatement(whileKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isEmptyStatement = function (inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + + return this.currentToken().tokenKind === 79 /* SemicolonToken */; + }; + + ParserImpl.prototype.parseEmptyStatement = function () { + var semicolonToken = this.eatToken(79 /* SemicolonToken */); + return this.factory.emptyStatement(semicolonToken); + }; + + ParserImpl.prototype.isForOrForInStatement = function () { + return this.currentToken().tokenKind === 26 /* ForKeyword */; + }; + + ParserImpl.prototype.parseForOrForInStatement = function () { + var forKeyword = this.eatKeyword(26 /* ForKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 40 /* VarKeyword */) { + return this.parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } else if (currentToken.tokenKind === 79 /* SemicolonToken */) { + return this.parseForStatement(forKeyword, openParenToken); + } else { + return this.parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + }; + + ParserImpl.prototype.parseForOrForInStatementWithVariableDeclaration = function (forKeyword, openParenToken) { + var variableDeclaration = this.parseVariableDeclaration(false); + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + }; + + ParserImpl.prototype.parseForInStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var inKeyword = this.eatKeyword(29 /* InKeyword */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.forInStatement(forKeyword, openParenToken, variableDeclaration, initializer, inKeyword, expression, closeParenToken, statement); + }; + + ParserImpl.prototype.parseForOrForInStatementWithInitializer = function (forKeyword, openParenToken) { + var initializer = this.parseExpression(false); + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } else { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + }; + + ParserImpl.prototype.parseForStatement = function (forKeyword, openParenToken) { + var initializer = null; + + if (this.currentToken().tokenKind !== 79 /* SemicolonToken */ && this.currentToken().tokenKind !== 74 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + initializer = this.parseExpression(false); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + }; + + ParserImpl.prototype.parseForStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var firstSemicolonToken = this.eatToken(79 /* SemicolonToken */); + + var condition = null; + if (this.currentToken().tokenKind !== 79 /* SemicolonToken */ && this.currentToken().tokenKind !== 74 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + condition = this.parseExpression(true); + } + + var secondSemicolonToken = this.eatToken(79 /* SemicolonToken */); + + var incrementor = null; + if (this.currentToken().tokenKind !== 74 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + incrementor = this.parseExpression(true); + } + + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.forStatement(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement); + }; + + ParserImpl.prototype.isBreakStatement = function () { + return this.currentToken().tokenKind === 15 /* BreakKeyword */; + }; + + ParserImpl.prototype.parseBreakStatement = function () { + var breakKeyword = this.eatKeyword(15 /* BreakKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.breakStatement(breakKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.isContinueStatement = function () { + return this.currentToken().tokenKind === 18 /* ContinueKeyword */; + }; + + ParserImpl.prototype.parseContinueStatement = function () { + var continueKeyword = this.eatKeyword(18 /* ContinueKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.continueStatement(continueKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.isSwitchStatement = function () { + return this.currentToken().tokenKind === 34 /* SwitchKeyword */; + }; + + ParserImpl.prototype.parseSwitchStatement = function () { + var switchKeyword = this.eatKeyword(34 /* SwitchKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var switchClauses = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(8 /* SwitchStatement_SwitchClauses */); + switchClauses = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + return this.factory.switchStatement(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken); + }; + + ParserImpl.prototype.isCaseSwitchClause = function () { + return this.currentToken().tokenKind === 16 /* CaseKeyword */; + }; + + ParserImpl.prototype.isDefaultSwitchClause = function () { + return this.currentToken().tokenKind === 20 /* DefaultKeyword */; + }; + + ParserImpl.prototype.isSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return true; + } + + return this.isCaseSwitchClause() || this.isDefaultSwitchClause(); + }; + + ParserImpl.prototype.parseSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return this.eatNode(); + } + + if (this.isCaseSwitchClause()) { + return this.parseCaseSwitchClause(); + } else if (this.isDefaultSwitchClause()) { + return this.parseDefaultSwitchClause(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseCaseSwitchClause = function () { + var caseKeyword = this.eatKeyword(16 /* CaseKeyword */); + var expression = this.parseExpression(true); + var colonToken = this.eatToken(107 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.caseSwitchClause(caseKeyword, expression, colonToken, statements); + }; + + ParserImpl.prototype.parseDefaultSwitchClause = function () { + var defaultKeyword = this.eatKeyword(20 /* DefaultKeyword */); + var colonToken = this.eatToken(107 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.defaultSwitchClause(defaultKeyword, colonToken, statements); + }; + + ParserImpl.prototype.isThrowStatement = function () { + return this.currentToken().tokenKind === 36 /* ThrowKeyword */; + }; + + ParserImpl.prototype.parseThrowStatement = function () { + var throwKeyword = this.eatKeyword(36 /* ThrowKeyword */); + + var expression = null; + if (this.canEatExplicitOrAutomaticSemicolon(false)) { + var token = this.createMissingToken(11 /* IdentifierName */, null); + expression = token; + } else { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.throwStatement(throwKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isReturnStatement = function () { + return this.currentToken().tokenKind === 33 /* ReturnKeyword */; + }; + + ParserImpl.prototype.parseReturnStatement = function () { + var returnKeyword = this.eatKeyword(33 /* ReturnKeyword */); + + var expression = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.returnStatement(returnKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isExpressionStatement = function () { + var currentToken = this.currentToken(); + + var kind = currentToken.tokenKind; + if (kind === 71 /* OpenBraceToken */ || kind === 27 /* FunctionKeyword */) { + return false; + } + + return this.isExpression(); + }; + + ParserImpl.prototype.isAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 80 /* CommaToken */) { + return true; + } + + return this.isExpression(); + }; + + ParserImpl.prototype.parseAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 80 /* CommaToken */) { + return this.factory.omittedExpression(); + } + + return this.parseAssignmentExpression(true); + }; + + ParserImpl.prototype.isExpression = function () { + var currentToken = this.currentToken(); + var kind = currentToken.tokenKind; + + switch (kind) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + return true; + + case 75 /* OpenBracketToken */: + case 73 /* OpenParenToken */: + return true; + + case 81 /* LessThanToken */: + return true; + + case 94 /* PlusPlusToken */: + case 95 /* MinusMinusToken */: + case 90 /* PlusToken */: + case 91 /* MinusToken */: + case 103 /* TildeToken */: + case 102 /* ExclamationToken */: + return true; + + case 71 /* OpenBraceToken */: + return true; + + case 86 /* EqualsGreaterThanToken */: + return true; + + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + return true; + + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + return true; + + case 31 /* NewKeyword */: + return true; + + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + return true; + + case 27 /* FunctionKeyword */: + return true; + } + + if (this.isIdentifier(this.currentToken())) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpressionStatement = function () { + var expression = this.parseExpression(true); + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.expressionStatement(expression, semicolon); + }; + + ParserImpl.prototype.isIfStatement = function () { + return this.currentToken().tokenKind === 28 /* IfKeyword */; + }; + + ParserImpl.prototype.parseIfStatement = function () { + var ifKeyword = this.eatKeyword(28 /* IfKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + var elseClause = null; + if (this.isElseClause()) { + elseClause = this.parseElseClause(); + } + + return this.factory.ifStatement(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause); + }; + + ParserImpl.prototype.isElseClause = function () { + return this.currentToken().tokenKind === 23 /* ElseKeyword */; + }; + + ParserImpl.prototype.parseElseClause = function () { + var elseKeyword = this.eatKeyword(23 /* ElseKeyword */); + var statement = this.parseStatement(); + + return this.factory.elseClause(elseKeyword, statement); + }; + + ParserImpl.prototype.isVariableStatement = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 40 /* VarKeyword */; + }; + + ParserImpl.prototype.parseVariableStatement = function () { + var modifiers = this.parseModifiers(); + var variableDeclaration = this.parseVariableDeclaration(true); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.variableStatement(modifiers, variableDeclaration, semicolonToken); + }; + + ParserImpl.prototype.parseVariableDeclaration = function (allowIn) { + var varKeyword = this.eatKeyword(40 /* VarKeyword */); + + var listParsingState = allowIn ? 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + + var result = this.parseSeparatedSyntaxList(listParsingState); + var variableDeclarators = result.list; + varKeyword = this.addSkippedTokensAfterToken(varKeyword, result.skippedTokens); + + return this.factory.variableDeclaration(varKeyword, variableDeclarators); + }; + + ParserImpl.prototype.isVariableDeclarator = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 224 /* VariableDeclarator */) { + return true; + } + + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.canReuseVariableDeclaratorNode = function (node) { + if (node === null || node.kind() !== 224 /* VariableDeclarator */) { + return false; + } + + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + }; + + ParserImpl.prototype.parseVariableDeclarator = function (allowIn, allowPropertyName) { + if (this.canReuseVariableDeclaratorNode(this.currentNode())) { + return this.eatNode(); + } + + var propertyName = allowPropertyName ? this.eatPropertyName() : this.eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + + if (propertyName.width() > 0) { + typeAnnotation = this.parseOptionalTypeAnnotation(false); + + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(allowIn); + } + } + + return this.factory.variableDeclarator(propertyName, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.isColonValueClause = function () { + return this.currentToken().tokenKind === 107 /* ColonToken */; + }; + + ParserImpl.prototype.isEqualsValueClause = function (inParameter) { + var token0 = this.currentToken(); + if (token0.tokenKind === 108 /* EqualsToken */) { + return true; + } + + if (!this.previousToken().hasTrailingNewLine()) { + if (token0.tokenKind === 86 /* EqualsGreaterThanToken */) { + return false; + } + + if (token0.tokenKind === 71 /* OpenBraceToken */ && inParameter) { + return false; + } + + return this.isExpression(); + } + + return false; + }; + + ParserImpl.prototype.parseEqualsValueClause = function (allowIn) { + var equalsToken = this.eatToken(108 /* EqualsToken */); + var value = this.parseAssignmentExpression(allowIn); + + return this.factory.equalsValueClause(equalsToken, value); + }; + + ParserImpl.prototype.parseExpression = function (allowIn) { + return this.parseSubExpression(0, allowIn); + }; + + ParserImpl.prototype.parseAssignmentExpression = function (allowIn) { + return this.parseSubExpression(2 /* AssignmentExpressionPrecedence */, allowIn); + }; + + ParserImpl.prototype.parseUnaryExpression = function () { + var currentTokenKind = this.currentToken().tokenKind; + if (TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(currentTokenKind)) { + var operatorKind = TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(currentTokenKind); + + var operatorToken = this.eatAnyToken(); + + var operand = this.parseUnaryExpression(); + return this.factory.prefixUnaryExpression(operatorKind, operatorToken, operand); + } else { + return this.parseTerm(false); + } + }; + + ParserImpl.prototype.parseSubExpression = function (precedence, allowIn) { + var leftOperand = this.parseUnaryExpression(); + leftOperand = this.parseBinaryOrConditionalExpressions(precedence, allowIn, leftOperand); + + return leftOperand; + }; + + ParserImpl.prototype.parseBinaryOrConditionalExpressions = function (precedence, allowIn, leftOperand) { + while (true) { + var token0 = this.currentToken(); + var token0Kind = token0.tokenKind; + + if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(token0Kind)) { + if (token0Kind === 29 /* InKeyword */ && !allowIn) { + break; + } + + var mergedToken = this.tryMergeBinaryExpressionTokens(); + var tokenKind = mergedToken === null ? token0Kind : mergedToken.syntaxKind; + + var binaryExpressionKind = TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(tokenKind); + var newPrecedence = ParserImpl.getPrecedence(binaryExpressionKind); + + if (newPrecedence < precedence) { + break; + } + + if (newPrecedence === precedence && !this.isRightAssociative(binaryExpressionKind)) { + break; + } + + var operatorToken = mergedToken === null ? token0 : TypeScript.Syntax.token(mergedToken.syntaxKind).withLeadingTrivia(token0.leadingTrivia()).withTrailingTrivia(this.peekToken(mergedToken.tokenCount - 1).trailingTrivia()); + + var skipCount = mergedToken === null ? 1 : mergedToken.tokenCount; + for (var i = 0; i < skipCount; i++) { + this.eatAnyToken(); + } + + leftOperand = this.factory.binaryExpression(binaryExpressionKind, leftOperand, operatorToken, this.parseSubExpression(newPrecedence, allowIn)); + continue; + } + + if (token0Kind === 106 /* QuestionToken */ && precedence <= 3 /* ConditionalExpressionPrecedence */) { + var questionToken = this.eatToken(106 /* QuestionToken */); + + var whenTrueExpression = this.parseAssignmentExpression(allowIn); + var colon = this.eatToken(107 /* ColonToken */); + + var whenFalseExpression = this.parseAssignmentExpression(allowIn); + leftOperand = this.factory.conditionalExpression(leftOperand, questionToken, whenTrueExpression, colon, whenFalseExpression); + continue; + } + + break; + } + + return leftOperand; + }; + + ParserImpl.prototype.tryMergeBinaryExpressionTokens = function () { + var token0 = this.currentToken(); + + if (token0.tokenKind === 82 /* GreaterThanToken */ && !token0.hasTrailingTrivia()) { + var storage = this.mergeTokensStorage; + storage[0] = 0 /* None */; + storage[1] = 0 /* None */; + storage[2] = 0 /* None */; + + for (var i = 0; i < storage.length; i++) { + var nextToken = this.peekToken(i + 1); + + if (!nextToken.hasLeadingTrivia()) { + storage[i] = nextToken.tokenKind; + } + + if (nextToken.hasTrailingTrivia()) { + break; + } + } + + if (storage[0] === 82 /* GreaterThanToken */) { + if (storage[1] === 82 /* GreaterThanToken */) { + if (storage[2] === 108 /* EqualsToken */) { + return { tokenCount: 4, syntaxKind: 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 3, syntaxKind: 98 /* GreaterThanGreaterThanGreaterThanToken */ }; + } + } else if (storage[1] === 108 /* EqualsToken */) { + return { tokenCount: 3, syntaxKind: 114 /* GreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 2, syntaxKind: 97 /* GreaterThanGreaterThanToken */ }; + } + } else if (storage[0] === 108 /* EqualsToken */) { + return { tokenCount: 2, syntaxKind: 84 /* GreaterThanEqualsToken */ }; + } + } + + return null; + }; + + ParserImpl.prototype.isRightAssociative = function (expressionKind) { + switch (expressionKind) { + case 173 /* AssignmentExpression */: + case 174 /* AddAssignmentExpression */: + case 175 /* SubtractAssignmentExpression */: + case 176 /* MultiplyAssignmentExpression */: + case 177 /* DivideAssignmentExpression */: + case 178 /* ModuloAssignmentExpression */: + case 179 /* AndAssignmentExpression */: + case 180 /* ExclusiveOrAssignmentExpression */: + case 181 /* OrAssignmentExpression */: + case 182 /* LeftShiftAssignmentExpression */: + case 183 /* SignedRightShiftAssignmentExpression */: + case 184 /* UnsignedRightShiftAssignmentExpression */: + return true; + default: + return false; + } + }; + + ParserImpl.prototype.parseTerm = function (inObjectCreation) { + var term = this.parseTermWorker(); + if (term === null) { + return this.eatIdentifierToken(); + } + + return this.parsePostFixExpression(term, inObjectCreation); + }; + + ParserImpl.prototype.parsePostFixExpression = function (expression, inObjectCreation) { + while (true) { + var currentTokenKind = this.currentToken().tokenKind; + switch (currentTokenKind) { + case 73 /* OpenParenToken */: + if (inObjectCreation) { + return expression; + } + + expression = this.factory.invocationExpression(expression, this.parseArgumentList(null)); + continue; + + case 81 /* LessThanToken */: + if (inObjectCreation) { + return expression; + } + + var argumentList = this.tryParseArgumentList(); + if (argumentList !== null) { + expression = this.factory.invocationExpression(expression, argumentList); + continue; + } + + break; + + case 75 /* OpenBracketToken */: + expression = this.parseElementAccessExpression(expression, inObjectCreation); + continue; + + case 94 /* PlusPlusToken */: + case 95 /* MinusMinusToken */: + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + break; + } + + expression = this.factory.postfixUnaryExpression(TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(currentTokenKind), expression, this.eatAnyToken()); + continue; + + case 77 /* DotToken */: + expression = this.factory.memberAccessExpression(expression, this.eatToken(77 /* DotToken */), this.eatIdentifierNameToken()); + continue; + } + + return expression; + } + }; + + ParserImpl.prototype.tryParseArgumentList = function () { + var typeArgumentList = null; + + if (this.currentToken().tokenKind === 81 /* LessThanToken */) { + var rewindPoint = this.getRewindPoint(); + try { + typeArgumentList = this.tryParseTypeArgumentList(true); + var token0 = this.currentToken(); + + var isOpenParen = token0.tokenKind === 73 /* OpenParenToken */; + var isDot = token0.tokenKind === 77 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + if (typeArgumentList === null || !isOpenParenOrDot) { + this.rewind(rewindPoint); + return null; + } + + if (isDot) { + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token0.width(), 138 /* A_parameter_list_must_follow_a_generic_type_argument_list______expected */, null); + this.addDiagnostic(diagnostic); + + return this.factory.argumentList(typeArgumentList, TypeScript.Syntax.emptyToken(73 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.emptyToken(74 /* CloseParenToken */)); + } + } finally { + this.releaseRewindPoint(rewindPoint); + } + } + + if (this.currentToken().tokenKind === 73 /* OpenParenToken */) { + return this.parseArgumentList(typeArgumentList); + } + + return null; + }; + + ParserImpl.prototype.parseArgumentList = function (typeArgumentList) { + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var arguments = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.fullWidth() > 0) { + var result = this.parseSeparatedSyntaxList(16384 /* ArgumentList_AssignmentExpressions */); + arguments = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + return this.factory.argumentList(typeArgumentList, openParenToken, arguments, closeParenToken); + }; + + ParserImpl.prototype.parseElementAccessExpression = function (expression, inObjectCreation) { + var start = this.currentTokenStart(); + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + var argumentExpression; + + if (this.currentToken().tokenKind === 76 /* CloseBracketToken */ && inObjectCreation) { + var end = this.currentTokenStart() + this.currentToken().width(); + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, start, end - start, 137 /* _new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead */, null); + this.addDiagnostic(diagnostic); + + argumentExpression = TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } else { + argumentExpression = this.parseExpression(true); + } + + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + + return this.factory.elementAccessExpression(expression, openBracketToken, argumentExpression, closeBracketToken); + }; + + ParserImpl.prototype.parseTermWorker = function () { + var currentToken = this.currentToken(); + + if (currentToken.tokenKind === 86 /* EqualsGreaterThanToken */) { + return this.parseSimpleArrowFunctionExpression(); + } + + if (this.isIdentifier(currentToken)) { + if (this.isSimpleArrowFunctionExpression()) { + return this.parseSimpleArrowFunctionExpression(); + } else { + var identifier = this.eatIdentifierToken(); + return identifier; + } + } + + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + return this.parseThisExpression(); + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.parseLiteralExpression(); + + case 32 /* NullKeyword */: + return this.parseLiteralExpression(); + + case 31 /* NewKeyword */: + return this.parseObjectCreationExpression(); + + case 27 /* FunctionKeyword */: + return this.parseFunctionExpression(); + + case 50 /* SuperKeyword */: + return this.parseSuperExpression(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeOfExpression(); + + case 21 /* DeleteKeyword */: + return this.parseDeleteExpression(); + + case 41 /* VoidKeyword */: + return this.parseVoidExpression(); + + case 13 /* NumericLiteral */: + return this.parseLiteralExpression(); + + case 12 /* RegularExpressionLiteral */: + return this.parseLiteralExpression(); + + case 14 /* StringLiteral */: + return this.parseLiteralExpression(); + + case 75 /* OpenBracketToken */: + return this.parseArrayLiteralExpression(); + + case 71 /* OpenBraceToken */: + return this.parseObjectLiteralExpression(); + + case 73 /* OpenParenToken */: + return this.parseParenthesizedOrArrowFunctionExpression(); + + case 81 /* LessThanToken */: + return this.parseCastOrArrowFunctionExpression(); + + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + var result = this.tryReparseDivideAsRegularExpression(); + if (result !== null) { + return result; + } + break; + } + + return null; + }; + + ParserImpl.prototype.tryReparseDivideAsRegularExpression = function () { + var currentToken = this.currentToken(); + + if (this.previousToken() !== null) { + var previousTokenKind = this.previousToken().tokenKind; + switch (previousTokenKind) { + case 11 /* IdentifierName */: + return null; + + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return null; + + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 94 /* PlusPlusToken */: + case 95 /* MinusMinusToken */: + case 76 /* CloseBracketToken */: + case 72 /* CloseBraceToken */: + return null; + } + } + + currentToken = this.currentTokenAllowingRegularExpression(); + + if (currentToken.tokenKind === 119 /* SlashToken */ || currentToken.tokenKind === 120 /* SlashEqualsToken */) { + return null; + } else if (currentToken.tokenKind === 12 /* RegularExpressionLiteral */) { + return this.parseLiteralExpression(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseTypeOfExpression = function () { + var typeOfKeyword = this.eatKeyword(39 /* TypeOfKeyword */); + var expression = this.parseUnaryExpression(); + + return this.factory.typeOfExpression(typeOfKeyword, expression); + }; + + ParserImpl.prototype.parseDeleteExpression = function () { + var deleteKeyword = this.eatKeyword(21 /* DeleteKeyword */); + var expression = this.parseUnaryExpression(); + + return this.factory.deleteExpression(deleteKeyword, expression); + }; + + ParserImpl.prototype.parseVoidExpression = function () { + var voidKeyword = this.eatKeyword(41 /* VoidKeyword */); + var expression = this.parseUnaryExpression(); + + return this.factory.voidExpression(voidKeyword, expression); + }; + + ParserImpl.prototype.parseSuperExpression = function () { + var superKeyword = this.eatKeyword(50 /* SuperKeyword */); + return superKeyword; + }; + + ParserImpl.prototype.parseFunctionExpression = function () { + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = null; + + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionExpression(functionKeyword, identifier, callSignature, block); + }; + + ParserImpl.prototype.parseObjectCreationExpression = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + + var expression = this.parseTerm(true); + var argumentList = this.tryParseArgumentList(); + + return this.factory.objectCreationExpression(newKeyword, expression, argumentList); + }; + + ParserImpl.prototype.parseCastOrArrowFunctionExpression = function () { + var rewindPoint = this.getRewindPoint(); + try { + var arrowFunction = this.tryParseArrowFunctionExpression(); + if (arrowFunction !== null) { + return arrowFunction; + } + + this.rewind(rewindPoint); + return this.parseCastExpression(); + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.parseCastExpression = function () { + var lessThanToken = this.eatToken(81 /* LessThanToken */); + var type = this.parseType(); + var greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + var expression = this.parseUnaryExpression(); + + return this.factory.castExpression(lessThanToken, type, greaterThanToken, expression); + }; + + ParserImpl.prototype.parseParenthesizedOrArrowFunctionExpression = function () { + var result = this.tryParseArrowFunctionExpression(); + if (result !== null) { + return result; + } + + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + return this.factory.parenthesizedExpression(openParenToken, expression, closeParenToken); + }; + + ParserImpl.prototype.tryParseArrowFunctionExpression = function () { + var tokenKind = this.currentToken().tokenKind; + + if (this.isDefinitelyArrowFunctionExpression()) { + return this.parseParenthesizedArrowFunctionExpression(false); + } + + if (!this.isPossiblyArrowFunctionExpression()) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + try { + var arrowFunction = this.parseParenthesizedArrowFunctionExpression(true); + if (arrowFunction === null) { + this.rewind(rewindPoint); + } + return arrowFunction; + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.parseParenthesizedArrowFunctionExpression = function (requireArrow) { + var currentToken = this.currentToken(); + + var callSignature = this.parseCallSignature(true); + + if (requireArrow && this.currentToken().tokenKind !== 86 /* EqualsGreaterThanToken */) { + return null; + } + + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var body = this.parseArrowFunctionBody(); + + return this.factory.parenthesizedArrowFunctionExpression(callSignature, equalsGreaterThanToken, body); + }; + + ParserImpl.prototype.parseArrowFunctionBody = function () { + if (this.isBlock()) { + return this.parseBlock(false, false); + } else { + return this.parseAssignmentExpression(true); + } + }; + + ParserImpl.prototype.isSimpleArrowFunctionExpression = function () { + if (this.currentToken().tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 86 /* EqualsGreaterThanToken */; + }; + + ParserImpl.prototype.parseSimpleArrowFunctionExpression = function () { + var identifier = this.eatIdentifierToken(); + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var body = this.parseArrowFunctionBody(); + + return this.factory.simpleArrowFunctionExpression(identifier, equalsGreaterThanToken, body); + }; + + ParserImpl.prototype.isBlock = function () { + return this.currentToken().tokenKind === 71 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isDefinitelyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 73 /* OpenParenToken */) { + return false; + } + + var token1 = this.peekToken(1); + var token2; + + if (token1.tokenKind === 74 /* CloseParenToken */) { + token2 = this.peekToken(2); + return token2.tokenKind === 107 /* ColonToken */ || token2.tokenKind === 86 /* EqualsGreaterThanToken */ || token2.tokenKind === 71 /* OpenBraceToken */; + } + + if (token1.tokenKind === 78 /* DotDotDotToken */) { + return true; + } + + if (!this.isIdentifier(token1)) { + return false; + } + + token2 = this.peekToken(2); + if (token2.tokenKind === 107 /* ColonToken */) { + return true; + } + + var token3 = this.peekToken(3); + if (token2.tokenKind === 106 /* QuestionToken */) { + if (token3.tokenKind === 107 /* ColonToken */ || token3.tokenKind === 74 /* CloseParenToken */ || token3.tokenKind === 80 /* CommaToken */) { + return true; + } + } + + if (token2.tokenKind === 74 /* CloseParenToken */) { + if (token3.tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPossiblyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 73 /* OpenParenToken */) { + return true; + } + + var token1 = this.peekToken(1); + + if (!this.isIdentifier(token1)) { + return false; + } + + var token2 = this.peekToken(2); + if (token2.tokenKind === 108 /* EqualsToken */) { + return true; + } + + if (token2.tokenKind === 80 /* CommaToken */) { + return true; + } + + if (token2.tokenKind === 74 /* CloseParenToken */) { + var token3 = this.peekToken(3); + if (token3.tokenKind === 107 /* ColonToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseObjectLiteralExpression = function () { + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var result = this.parseSeparatedSyntaxList(32768 /* ObjectLiteralExpression_PropertyAssignments */); + var propertyAssignments = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.objectLiteralExpression(openBraceToken, propertyAssignments, closeBraceToken); + }; + + ParserImpl.prototype.parsePropertyAssignment = function () { + if (this.isGetAccessorPropertyAssignment(false)) { + return this.parseGetAccessorPropertyAssignment(); + } else if (this.isSetAccessorPropertyAssignment(false)) { + return this.parseSetAccessorPropertyAssignment(); + } else if (this.isFunctionPropertyAssignment(false)) { + return this.parseFunctionPropertyAssignment(); + } else if (this.isSimplePropertyAssignment(false)) { + return this.parseSimplePropertyAssignment(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isPropertyAssignment = function (inErrorRecovery) { + return this.isGetAccessorPropertyAssignment(inErrorRecovery) || this.isSetAccessorPropertyAssignment(inErrorRecovery) || this.isFunctionPropertyAssignment(inErrorRecovery) || this.isSimplePropertyAssignment(inErrorRecovery); + }; + + ParserImpl.prototype.isGetAccessorPropertyAssignment = function (inErrorRecovery) { + return this.currentToken().tokenKind === 65 /* GetKeyword */ && this.isPropertyName(this.peekToken(1), inErrorRecovery); + }; + + ParserImpl.prototype.parseGetAccessorPropertyAssignment = function () { + var getKeyword = this.eatKeyword(65 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, true); + + return this.factory.getAccessorPropertyAssignment(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block); + }; + + ParserImpl.prototype.isSetAccessorPropertyAssignment = function (inErrorRecovery) { + return this.currentToken().tokenKind === 69 /* SetKeyword */ && this.isPropertyName(this.peekToken(1), inErrorRecovery); + }; + + ParserImpl.prototype.parseSetAccessorPropertyAssignment = function () { + var setKeyword = this.eatKeyword(69 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var parameter = this.parseParameter(); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var block = this.parseBlock(false, true); + + return this.factory.setAccessorPropertyAssignment(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block); + }; + + ParserImpl.prototype.eatPropertyName = function () { + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.currentToken()) ? this.eatIdentifierNameToken() : this.eatAnyToken(); + }; + + ParserImpl.prototype.isFunctionPropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery) && this.isCallSignature(1); + }; + + ParserImpl.prototype.parseFunctionPropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionPropertyAssignment(propertyName, callSignature, block); + }; + + ParserImpl.prototype.isSimplePropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseSimplePropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var colonToken = this.eatToken(107 /* ColonToken */); + var expression = this.parseAssignmentExpression(true); + + return this.factory.simplePropertyAssignment(propertyName, colonToken, expression); + }; + + ParserImpl.prototype.isPropertyName = function (token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return this.isIdentifier(token); + } else { + return true; + } + } + + switch (token.tokenKind) { + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseArrayLiteralExpression = function () { + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + + var result = this.parseSeparatedSyntaxList(65536 /* ArrayLiteralExpression_AssignmentExpressions */); + var expressions = result.list; + openBracketToken = this.addSkippedTokensAfterToken(openBracketToken, result.skippedTokens); + + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + + return this.factory.arrayLiteralExpression(openBracketToken, expressions, closeBracketToken); + }; + + ParserImpl.prototype.parseLiteralExpression = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.parseThisExpression = function () { + var thisKeyword = this.eatKeyword(35 /* ThisKeyword */); + return thisKeyword; + }; + + ParserImpl.prototype.parseBlock = function (parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var statements = TypeScript.Syntax.emptyList; + + if (parseBlockEvenWithNoOpenBrace || openBraceToken.width() > 0) { + var savedIsInStrictMode = this.isInStrictMode; + + var processItems = checkForStrictMode ? ParserImpl.updateStrictModeState : null; + var result = this.parseSyntaxList(32 /* Block_Statements */, processItems); + statements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + this.setStrictMode(savedIsInStrictMode); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.block(openBraceToken, statements, closeBraceToken); + }; + + ParserImpl.prototype.parseCallSignature = function (requireCompleteTypeParameterList) { + var typeParameterList = this.parseOptionalTypeParameterList(requireCompleteTypeParameterList); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.callSignature(typeParameterList, parameterList, typeAnnotation); + }; + + ParserImpl.prototype.parseOptionalTypeParameterList = function (requireCompleteTypeParameterList) { + if (this.currentToken().tokenKind !== 81 /* LessThanToken */) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + try { + var lessThanToken = this.eatToken(81 /* LessThanToken */); + + var result = this.parseSeparatedSyntaxList(524288 /* TypeParameterList_TypeParameters */); + var typeParameterList = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + var greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + this.rewind(rewindPoint); + return null; + } + + return this.factory.typeParameterList(lessThanToken, typeParameterList, greaterThanToken); + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.isTypeParameter = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.parseTypeParameter = function () { + var identifier = this.eatIdentifierToken(); + var constraint = this.parseOptionalConstraint(); + + return this.factory.typeParameter(identifier, constraint); + }; + + ParserImpl.prototype.parseOptionalConstraint = function () { + if (this.currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + + var extendsKeyword = this.eatKeyword(48 /* ExtendsKeyword */); + var type = this.parseType(); + + return this.factory.constraint(extendsKeyword, type); + }; + + ParserImpl.prototype.parseParameterList = function () { + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(131072 /* ParameterList_Parameters */); + parameters = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + return this.factory.parameterList(openParenToken, parameters, closeParenToken); + }; + + ParserImpl.prototype.isTypeAnnotation = function () { + return this.currentToken().tokenKind === 107 /* ColonToken */; + }; + + ParserImpl.prototype.parseOptionalTypeAnnotation = function (allowStringLiteral) { + return this.isTypeAnnotation() ? this.parseTypeAnnotation(allowStringLiteral) : null; + }; + + ParserImpl.prototype.parseTypeAnnotation = function (allowStringLiteral) { + var colonToken = this.eatToken(107 /* ColonToken */); + var type = allowStringLiteral && this.currentToken().tokenKind === 14 /* StringLiteral */ ? this.eatToken(14 /* StringLiteral */) : this.parseType(); + + return this.factory.typeAnnotation(colonToken, type); + }; + + ParserImpl.prototype.isType = function () { + return this.isPredefinedType() || this.isTypeLiteral() || this.isName(); + }; + + ParserImpl.prototype.parseType = function () { + var type = this.parseNonArrayType(); + + while (this.currentToken().tokenKind === 75 /* OpenBracketToken */) { + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + + type = this.factory.arrayType(type, openBracketToken, closeBracketToken); + } + + return type; + }; + + ParserImpl.prototype.parseNonArrayType = function () { + if (this.isPredefinedType()) { + return this.parsePredefinedType(); + } else if (this.isTypeLiteral()) { + return this.parseTypeLiteral(); + } else { + return this.parseNameOrGenericType(); + } + }; + + ParserImpl.prototype.parseNameOrGenericType = function () { + var name = this.parseName(); + var typeArgumentList = this.tryParseTypeArgumentList(false); + + return typeArgumentList === null ? name : this.factory.genericType(name, typeArgumentList); + }; + + ParserImpl.prototype.parseTypeLiteral = function () { + if (this.isObjectType()) { + return this.parseObjectType(); + } else if (this.isFunctionType()) { + return this.parseFunctionType(); + } else if (this.isConstructorType()) { + return this.parseConstructorType(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseFunctionType = function () { + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var returnType = this.parseType(); + + return this.factory.functionType(typeParameterList, parameterList, equalsGreaterThanToken, returnType); + }; + + ParserImpl.prototype.parseConstructorType = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var type = this.parseType(); + + return this.factory.constructorType(newKeyword, null, parameterList, equalsGreaterThanToken, type); + }; + + ParserImpl.prototype.isTypeLiteral = function () { + return this.isObjectType() || this.isFunctionType() || this.isConstructorType(); + }; + + ParserImpl.prototype.isObjectType = function () { + return this.currentToken().tokenKind === 71 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isFunctionType = function () { + var tokenKind = this.currentToken().tokenKind; + return tokenKind === 73 /* OpenParenToken */ || tokenKind === 81 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructorType = function () { + return this.currentToken().tokenKind === 31 /* NewKeyword */; + }; + + ParserImpl.prototype.parsePredefinedType = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.isPredefinedType = function () { + switch (this.currentToken().tokenKind) { + case 60 /* AnyKeyword */: + case 68 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 62 /* BoolKeyword */: + case 70 /* StringKeyword */: + case 41 /* VoidKeyword */: + return true; + } + + return false; + }; + + ParserImpl.prototype.isParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return true; + } + + var token = this.currentToken(); + if (token.tokenKind === 78 /* DotDotDotToken */) { + return true; + } + + if (ParserImpl.isPublicOrPrivateKeyword(token)) { + return true; + } + + return this.isIdentifier(token); + }; + + ParserImpl.prototype.parseParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return this.eatNode(); + } + + var dotDotDotToken = this.tryEatToken(78 /* DotDotDotToken */); + + var publicOrPrivateToken = null; + if (ParserImpl.isPublicOrPrivateKeyword(this.currentToken())) { + publicOrPrivateToken = this.eatAnyToken(); + } + + var identifier = this.eatIdentifierToken(); + var questionToken = this.tryEatToken(106 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(true); + + var equalsValueClause = null; + if (this.isEqualsValueClause(true)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.parameter(dotDotDotToken, publicOrPrivateToken, identifier, questionToken, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.parseSyntaxList = function (currentListType, processItems) { + if (typeof processItems === "undefined") { processItems = null; } + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSyntaxListWorker(currentListType, processItems); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.parseSeparatedSyntaxList = function (currentListType) { + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSeparatedSyntaxListWorker(currentListType); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { + this.reportUnexpectedTokenDiagnostic(currentListType); + + for (var state = 262144 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + if ((this.listParsingState & state) !== 0) { + if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { + return true; + } + } + } + + var skippedToken = this.currentToken(); + + this.moveToNextToken(); + + this.addSkippedTokenToList(items, skippedTokens, skippedToken); + + return false; + }; + + ParserImpl.prototype.addSkippedTokenToList = function (items, skippedTokens, skippedToken) { + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + var lastToken = item.lastToken(); + if (lastToken.fullWidth() > 0) { + items[i] = this.addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + + skippedTokens.push(skippedToken); + }; + + ParserImpl.prototype.tryParseExpectedListItem = function (currentListType, inErrorRecovery, items, processItems) { + if (this.isExpectedListItem(currentListType, inErrorRecovery)) { + var item = this.parseExpectedListItem(currentListType); + + items.push(item); + + if (processItems !== null) { + processItems(this, items); + } + } + }; + + ParserImpl.prototype.listIsTerminated = function (currentListType) { + return this.isExpectedListTerminator(currentListType) || this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.getArray = function () { + if (this.arrayPool.length > 0) { + return this.arrayPool.pop(); + } + + return []; + }; + + ParserImpl.prototype.returnZeroOrOneLengthArray = function (array) { + if (array.length <= 1) { + this.returnArray(array); + } + }; + + ParserImpl.prototype.returnArray = function (array) { + array.length = 0; + this.arrayPool.push(array); + }; + + ParserImpl.prototype.parseSyntaxListWorker = function (currentListType, processItems) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + + while (true) { + var oldItemsCount = items.length; + this.tryParseExpectedListItem(currentListType, false, items, processItems); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } + } + } + + var result = TypeScript.Syntax.list(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.parseSeparatedSyntaxListWorker = function (currentListType) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + TypeScript.Debug.assert(items.length === 0); + TypeScript.Debug.assert(skippedTokens.length === 0); + TypeScript.Debug.assert(skippedTokens !== items); + + var separatorKind = this.separatorKind(currentListType); + var allowAutomaticSemicolonInsertion = separatorKind === 79 /* SemicolonToken */; + + var inErrorRecovery = false; + var listWasTerminated = false; + while (true) { + var oldItemsCount = items.length; + + this.tryParseExpectedListItem(currentListType, inErrorRecovery, items, null); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } else { + inErrorRecovery = true; + continue; + } + } + + inErrorRecovery = false; + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === separatorKind || currentToken.tokenKind === 80 /* CommaToken */) { + items.push(this.eatAnyToken()); + continue; + } + + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + if (allowAutomaticSemicolonInsertion && this.canEatAutomaticSemicolon(false)) { + items.push(this.eatExplicitOrAutomaticSemicolon(false)); + + continue; + } + + items.push(this.eatToken(separatorKind)); + + inErrorRecovery = true; + } + + var result = TypeScript.Syntax.separatedList(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.separatorKind = function (currentListType) { + switch (currentListType) { + case 2048 /* HeritageClause_TypeNameList */: + case 16384 /* ArgumentList_AssignmentExpressions */: + case 256 /* EnumDeclaration_EnumElements */: + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + case 131072 /* ParameterList_Parameters */: + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + case 262144 /* TypeArgumentList_Types */: + case 524288 /* TypeParameterList_TypeParameters */: + return 80 /* CommaToken */; + + case 512 /* ObjectType_TypeMembers */: + return 79 /* SemicolonToken */; + + case 1 /* SourceUnit_ModuleElements */: + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + case 2 /* ClassDeclaration_ClassElements */: + case 4 /* ModuleDeclaration_ModuleElements */: + case 8 /* SwitchStatement_SwitchClauses */: + case 16 /* SwitchClause_Statements */: + case 32 /* Block_Statements */: + default: + throw TypeScript.Errors.notYetImplemented(); + } + }; + + ParserImpl.prototype.reportUnexpectedTokenDiagnostic = function (listType) { + var token = this.currentToken(); + + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 12 /* Unexpected_token__0_expected */, [this.getExpectedListElementType(listType)]); + this.addDiagnostic(diagnostic); + }; + + ParserImpl.prototype.addDiagnostic = function (diagnostic) { + if (this.diagnostics.length > 0 && this.diagnostics[this.diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + + this.diagnostics.push(diagnostic); + }; + + ParserImpl.prototype.isExpectedListTerminator = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isExpectedSourceUnit_ModuleElementsTerminator(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isExpectedClassDeclaration_ClassElementsTerminator(); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isExpectedModuleDeclaration_ModuleElementsTerminator(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isExpectedSwitchStatement_SwitchClausesTerminator(); + + case 16 /* SwitchClause_Statements */: + return this.isExpectedSwitchClause_StatementsTerminator(); + + case 32 /* Block_Statements */: + return this.isExpectedBlock_StatementsTerminator(); + + case 64 /* TryBlock_Statements */: + return this.isExpectedTryBlock_StatementsTerminator(); + + case 128 /* CatchBlock_Statements */: + return this.isExpectedCatchBlock_StatementsTerminator(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.isExpectedEnumDeclaration_EnumElementsTerminator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isExpectedObjectType_TypeMembersTerminator(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpressionsTerminator(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isExpectedHeritageClause_TypeNameListTerminator(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + + case 131072 /* ParameterList_Parameters */: + return this.isExpectedParameterList_ParametersTerminator(); + + case 262144 /* TypeArgumentList_Types */: + return this.isExpectedTypeArgumentList_TypesTerminator(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isExpectedTypeParameterList_TypeParametersTerminator(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedSourceUnit_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.isExpectedEnumDeclaration_EnumElementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedModuleDeclaration_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectType_TypeMembersTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedLiteralExpression_AssignmentExpressionsTerminator = function () { + return this.currentToken().tokenKind === 76 /* CloseBracketToken */; + }; + + ParserImpl.prototype.isExpectedTypeArgumentList_TypesTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 82 /* GreaterThanToken */) { + return true; + } + + if (this.canFollowTypeArgumentListInExpression(token.tokenKind)) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedTypeParameterList_TypeParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 82 /* GreaterThanToken */) { + return true; + } + + if (token.tokenKind === 73 /* OpenParenToken */ || token.tokenKind === 71 /* OpenBraceToken */ || token.tokenKind === 48 /* ExtendsKeyword */ || token.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedParameterList_ParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 74 /* CloseParenToken */) { + return true; + } + + if (token.tokenKind === 71 /* OpenBraceToken */) { + return true; + } + + if (token.tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator = function () { + if (this.currentToken().tokenKind === 79 /* SemicolonToken */ || this.currentToken().tokenKind === 74 /* CloseParenToken */) { + return true; + } + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator = function () { + if (this.previousToken().tokenKind === 80 /* CommaToken */) { + return false; + } + + if (this.currentToken().tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + + return this.canEatExplicitOrAutomaticSemicolon(false); + }; + + ParserImpl.prototype.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 71 /* OpenBraceToken */ || token0.tokenKind === 72 /* CloseBraceToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedHeritageClause_TypeNameListTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + if (this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpressionsTerminator = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 74 /* CloseParenToken */ || token0.tokenKind === 79 /* SemicolonToken */; + }; + + ParserImpl.prototype.isExpectedClassDeclaration_ClassElementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchStatement_SwitchClausesTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchClause_StatementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */ || this.isSwitchClause(); + }; + + ParserImpl.prototype.isExpectedBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedTryBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */ || this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedCatchBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.isStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.isStatement(inErrorRecovery); + + case 64 /* TryBlock_Statements */: + case 128 /* CatchBlock_Statements */: + return false; + + case 256 /* EnumDeclaration_EnumElements */: + return this.isEnumElement(inErrorRecovery); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isVariableDeclarator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpression(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isHeritageClauseTypeName(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isPropertyAssignment(inErrorRecovery); + + case 131072 /* ParameterList_Parameters */: + return this.isParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.isType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isTypeParameter(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isAssignmentOrOmittedExpression(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpression = function () { + if (this.isExpression()) { + return true; + } + + if (this.currentToken().tokenKind === 80 /* CommaToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpectedListItem = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.parseModuleElement(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.parseHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.parseClassElement(false); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.parseModuleElement(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.parseSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.parseStatement(); + + case 32 /* Block_Statements */: + return this.parseStatement(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.parseEnumElement(); + + case 512 /* ObjectType_TypeMembers */: + return this.parseTypeMember(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.parseAssignmentExpression(true); + + case 2048 /* HeritageClause_TypeNameList */: + return this.parseNameOrGenericType(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.parseVariableDeclarator(true, false); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.parseVariableDeclarator(false, false); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.parsePropertyAssignment(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.parseAssignmentOrOmittedExpression(); + + case 131072 /* ParameterList_Parameters */: + return this.parseParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.parseType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.parseTypeParameter(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.getExpectedListElementType = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return TypeScript.Strings.module__class__interface__enum__import_or_statement; + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + + case 2 /* ClassDeclaration_ClassElements */: + return TypeScript.Strings.constructor__function__accessor_or_variable; + + case 4 /* ModuleDeclaration_ModuleElements */: + return TypeScript.Strings.module__class__interface__enum__import_or_statement; + + case 8 /* SwitchStatement_SwitchClauses */: + return TypeScript.Strings.case_or_default_clause; + + case 16 /* SwitchClause_Statements */: + return TypeScript.Strings.statement; + + case 32 /* Block_Statements */: + return TypeScript.Strings.statement; + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.Strings.identifier; + + case 256 /* EnumDeclaration_EnumElements */: + return TypeScript.Strings.identifier; + + case 512 /* ObjectType_TypeMembers */: + return TypeScript.Strings.call__construct__index__property_or_function_signature; + + case 16384 /* ArgumentList_AssignmentExpressions */: + return TypeScript.Strings.expression; + + case 2048 /* HeritageClause_TypeNameList */: + return TypeScript.Strings.type_name; + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.Strings.property_or_accessor; + + case 131072 /* ParameterList_Parameters */: + return TypeScript.Strings.parameter; + + case 262144 /* TypeArgumentList_Types */: + return TypeScript.Strings.type; + + case 524288 /* TypeParameterList_TypeParameters */: + return TypeScript.Strings.type_parameter; + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.Strings.expression; + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + return ParserImpl; + })(); + + function parse(fileName, text, isDeclaration, languageVersion, options) { + var source = new NormalParserSource(fileName, text, languageVersion); + + return new ParserImpl(fileName, text.lineMap(), source, options).parseSyntaxTree(isDeclaration); + } + Parser.parse = parse; + + function incrementalParse(oldSyntaxTree, textChangeRange, newText) { + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + + var source = new IncrementalParserSource(oldSyntaxTree, textChangeRange, newText); + + return new ParserImpl(oldSyntaxTree.fileName(), newText.lineMap(), source, oldSyntaxTree.parseOptions()).parseSyntaxTree(oldSyntaxTree.isDeclaration()); + } + Parser.incrementalParse = incrementalParse; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTree = (function () { + function SyntaxTree(sourceUnit, isDeclaration, diagnostics, fileName, lineMap, languageVersion, parseOtions) { + this._allDiagnostics = null; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = lineMap; + this._languageVersion = languageVersion; + this._parseOptions = parseOtions; + } + SyntaxTree.prototype.toJSON = function (key) { + var result = {}; + + result.isDeclaration = this._isDeclaration; + result.languageVersion = TypeScript.LanguageVersion[this._languageVersion]; + result.parseOptions = this._parseOptions; + + if (this.diagnostics().length > 0) { + result.diagnostics = this.diagnostics(); + } + + result.sourceUnit = this._sourceUnit; + result.lineMap = this._lineMap; + + return result; + }; + + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + + var diagnostics = []; + this.sourceUnit().accept(new GrammarCheckerWalker(this, diagnostics)); + + return diagnostics; + }; + + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + this._allDiagnostics = this.computeDiagnostics(); + } + + return this._allDiagnostics; + }; + + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + + SyntaxTree.prototype.languageVersion = function () { + return this._languageVersion; + }; + + SyntaxTree.prototype.parseOptions = function () { + return this._parseOptions; + }; + + SyntaxTree.prototype.structuralEquals = function (tree) { + return TypeScript.ArrayUtilities.sequenceEquals(this.diagnostics(), tree.diagnostics(), TypeScript.SyntaxDiagnostic.equals) && this.sourceUnit().structuralEquals(tree.sourceUnit()); + }; + return SyntaxTree; + })(); + TypeScript.SyntaxTree = SyntaxTree; + + var GrammarCheckerWalker = (function (_super) { + __extends(GrammarCheckerWalker, _super); + function GrammarCheckerWalker(syntaxTree, diagnostics) { + _super.call(this); + this.syntaxTree = syntaxTree; + this.diagnostics = diagnostics; + this.inAmbientDeclaration = false; + this.inBlock = false; + this.currentConstructor = null; + } + GrammarCheckerWalker.prototype.childFullStart = function (parent, child) { + return this.position() + TypeScript.Syntax.childOffset(parent, child); + }; + + GrammarCheckerWalker.prototype.childStart = function (parent, child) { + return this.childFullStart(parent, child) + child.leadingTriviaWidth(); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic = function (start, length, diagnosticCode, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.SyntaxDiagnostic(this.syntaxTree.fileName(), start, length, diagnosticCode, args)); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic1 = function (elementFullStart, element, diagnosticCode, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.SyntaxDiagnostic(this.syntaxTree.fileName(), elementFullStart + element.leadingTriviaWidth(), element.width(), diagnosticCode, args)); + }; + + GrammarCheckerWalker.prototype.visitCatchClause = function (node) { + if (node.typeAnnotation) { + this.pushDiagnostic(this.childStart(node, node.typeAnnotation), node.typeAnnotation.width(), 17 /* A_catch_clause_variable_cannot_have_a_type_annotation */); + } + + _super.prototype.visitCatchClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkParameterListOrder = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + var seenOptionalParameter = false; + var parameterCount = node.parameters.nonSeparatorCount(); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameterIndex = i / 2; + var parameter = node.parameters.childAt(i); + + if (parameter.dotDotDotToken) { + if (parameterIndex !== (parameterCount - 1)) { + this.pushDiagnostic1(parameterFullStart, parameter, 18 /* Rest_parameter_must_be_last_in_list */); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 56 /* Rest_parameter_cannot_be_optional */); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 57 /* Rest_parameter_cannot_have_initializer */); + return true; + } + } else if (parameter.questionToken || parameter.equalsValueClause) { + seenOptionalParameter = true; + + if (parameter.questionToken && parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 19 /* Parameter_cannot_have_question_mark_and_initializer */); + return true; + } + } else { + if (seenOptionalParameter) { + this.pushDiagnostic1(parameterFullStart, parameter, 20 /* Required_parameter_cannot_follow_optional_parameter */); + return true; + } + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterListAcessibilityModifiers = function (node) { + if (this.currentConstructor !== null && this.currentConstructor.parameterList === node && this.currentConstructor.block && !this.inAmbientDeclaration) { + return false; + } + + var parameterFullStart = this.childFullStart(node, node.parameters); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameter = node.parameters.childAt(i); + + if (parameter.publicOrPrivateKeyword) { + var keywordFullStart = parameterFullStart + TypeScript.Syntax.childOffset(parameter, parameter.publicOrPrivateKeyword); + this.pushDiagnostic1(keywordFullStart, parameter.publicOrPrivateKeyword, 43 /* Overload_and_ambient_signatures_cannot_specify_parameter_properties */); + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForTrailingSeparator = function (parent, list) { + if (list.childCount() === 0 || list.childCount() % 2 === 1) { + return false; + } + + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i === n - 1) { + this.pushDiagnostic1(currentElementFullStart, child, 13 /* Trailing_separator_not_allowed */); + } + + currentElementFullStart += child.fullWidth(); + } + + return true; + }; + + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, expected) { + if (list.childCount() > 0) { + return false; + } + + var listFullStart = this.childFullStart(parent, list); + var tokenAtStart = this.syntaxTree.sourceUnit().findToken(listFullStart); + + this.pushDiagnostic1(listFullStart, tokenAtStart.token(), 12 /* Unexpected_token__0_expected */, [expected]); + + return true; + }; + + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingSeparator(node, node.parameters)) { + this.skip(node); + return; + } + + _super.prototype.visitParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingSeparator(node, node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, TypeScript.Strings.type_name)) { + this.skip(node); + return; + } + + _super.prototype.visitHeritageClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.arguments)) { + this.skip(node); + return; + } + + _super.prototype.visitArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForTrailingSeparator(node, node.variableDeclarators) || this.checkForAtLeastOneElement(node, node.variableDeclarators, TypeScript.Strings.identifier)) { + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, TypeScript.Strings.identifier)) { + this.skip(node); + return; + } + + _super.prototype.visitTypeArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, TypeScript.Strings.identifier)) { + this.skip(node); + return; + } + + _super.prototype.visitTypeParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameter); + var parameter = node.parameter; + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 21 /* Index_signatures_cannot_have_rest_parameters */); + return true; + } else if (parameter.publicOrPrivateKeyword) { + this.pushDiagnostic1(parameterFullStart, parameter, 22 /* Index_signature_parameter_cannot_have_accessibility_modifiers */); + return true; + } else if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 23 /* Index_signature_parameter_cannot_have_a_question_mark */); + return true; + } else if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 24 /* Index_signature_parameter_cannot_have_an_initializer */); + return true; + } else if (!parameter.typeAnnotation) { + this.pushDiagnostic1(parameterFullStart, parameter, 26 /* Index_signature_parameter_must_have_a_type_annotation */); + return true; + } else if (parameter.typeAnnotation.type.kind() !== 70 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 68 /* NumberKeyword */) { + this.pushDiagnostic1(parameterFullStart, parameter, 27 /* Index_signature_parameter_type_must_be__string__or__number_ */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + this.skip(node); + return; + } + + if (!node.typeAnnotation) { + this.pushDiagnostic1(this.position(), node, 25 /* Index_signature_must_have_a_type_annotation */); + this.skip(node); + return; + } + + _super.prototype.visitIndexSignature.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + var seenImplementsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 28 /* _extends__clause_already_seen */); + return true; + } + + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 29 /* _extends__clause_must_precede__implements__clause */); + return true; + } + + if (heritageClause.typeNames.nonSeparatorCount() > 1) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 30 /* Class_can_only_extend_single_type */); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 31 /* _implements__clause_already_seen */); + return true; + } + + seenImplementsClause = true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 64 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, 41 /* _declare__modifier_not_allowed_for_code_already_in_an_ambient_context */); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, typeKeyword, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 64 /* DeclareKeyword */)) { + this.pushDiagnostic1(this.childFullStart(moduleElement, typeKeyword), typeKeyword.firstToken(), 49 /* _declare__modifier_required_for_top_level_element */); + return true; + } + } + }; + + GrammarCheckerWalker.prototype.checkFunctionOverloads = function (node, moduleElements) { + if (!this.inAmbientDeclaration && !this.syntaxTree.isDeclaration()) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + + var inFunctionOverloadChain = false; + var functionOverloadChainName = null; + + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (moduleElement.kind() !== 129 /* FunctionDeclaration */) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + + var functionDeclaration = moduleElement; + if (functionDeclaration.identifier.valueText() !== functionOverloadChainName) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, 46 /* Function_overload_name_must_be__0_ */, [functionOverloadChainName]); + return true; + } + } + + if (moduleElement.kind() === 129 /* FunctionDeclaration */) { + functionDeclaration = moduleElement; + if (!TypeScript.SyntaxUtilities.containsToken(functionDeclaration.modifiers, 64 /* DeclareKeyword */)) { + inFunctionOverloadChain = functionDeclaration.block === null; + functionOverloadChainName = functionDeclaration.identifier.valueText(); + + if (lastElement && inFunctionOverloadChain) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + } else { + inFunctionOverloadChain = false; + functionOverloadChainName = ""; + } + } + + moduleElementFullStart += moduleElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkClassOverloads = function (node) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */)) { + var classElementFullStart = this.childFullStart(node, node.classElements); + + var inFunctionOverloadChain = false; + var inConstructorOverloadChain = false; + + var functionOverloadChainName = null; + var memberFunctionDeclaration = null; + + for (var i = 0, n = node.classElements.childCount(); i < n; i++) { + var classElement = node.classElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (classElement.kind() !== 135 /* MemberFunctionDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + + memberFunctionDeclaration = classElement; + if (memberFunctionDeclaration.propertyName.valueText() !== functionOverloadChainName) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, 46 /* Function_overload_name_must_be__0_ */, [functionOverloadChainName]); + return true; + } + } else if (inConstructorOverloadChain) { + if (classElement.kind() !== 137 /* ConstructorDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 45 /* Constructor_implementation_expected */); + return true; + } + } + + if (classElement.kind() === 135 /* MemberFunctionDeclaration */) { + memberFunctionDeclaration = classElement; + + inFunctionOverloadChain = memberFunctionDeclaration.block === null; + functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); + + if (lastElement && inFunctionOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = classElement; + + inConstructorOverloadChain = constructorDeclaration.block === null; + if (lastElement && inConstructorOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 45 /* Constructor_implementation_expected */); + return true; + } + } + + classElementFullStart += classElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForReservedName = function (parent, name, code) { + var nameFullStart = this.childFullStart(parent, name); + var token; + var tokenFullStart; + + var current = name; + while (current !== null) { + if (current.kind() === 122 /* QualifiedName */) { + var qualifiedName = current; + token = qualifiedName.right; + tokenFullStart = nameFullStart + this.childFullStart(qualifiedName, token); + current = qualifiedName.left; + } else { + TypeScript.Debug.assert(current.kind() === 11 /* IdentifierName */); + token = current; + tokenFullStart = nameFullStart; + current = null; + } + + switch (token.valueText()) { + case "any": + case "number": + case "bool": + case "string": + case "void": + this.pushDiagnostic(tokenFullStart + token.leadingTriviaWidth(), token.width(), code, [token.valueText()]); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, 60 /* Class_name_cannot_be__0_ */) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.classKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node) || this.checkClassOverloads(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 28 /* _extends__clause_already_seen */); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 36 /* Interface_declaration_cannot_have__implements__clause */); + return true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + var modifierFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 64 /* DeclareKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, 48 /* _declare__modifier_cannot_appear_on_an_interface_declaration */); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, 61 /* Interface_name_cannot_be__0_ */) || this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + this.skip(node); + return; + } + + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var modifierFullStart = this.position(); + + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var modifier = list.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 32 /* Accessibility_modifier_already_seen */); + return true; + } + + if (seenStaticModifier) { + var previousToken = list.childAt(i - 1); + this.pushDiagnostic1(modifierFullStart, modifier, 33 /* _0__modifier_must_precede__1__modifier */, [modifier.text(), previousToken.text()]); + return true; + } + + seenAccessibilityModifier = true; + } else if (modifier.tokenKind === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 34 /* _0__modifier_already_seen */, [modifier.text()]); + return true; + } + + seenStaticModifier = true; + } else { + this.pushDiagnostic1(modifierFullStart, modifier, 35 /* _0__modifier_cannot_appear_on_a_class_element */, [modifier.text()]); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkGetMemberAccessorParameter = function (node) { + var getKeywordFullStart = this.childFullStart(node, node.getKeyword); + if (node.parameterList.parameters.childCount() !== 0) { + this.pushDiagnostic1(getKeywordFullStart, node.getKeyword, 55 /* _get__accessor_cannot_have_parameters */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, node, languageVersion, code) { + if (this.syntaxTree.languageVersion() < languageVersion) { + var nodeFullStart = this.childFullStart(parent, node); + this.pushDiagnostic1(nodeFullStart, node, code); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitGetMemberAccessorDeclaration = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */) || this.checkClassElementModifiers(node.modifiers) || this.checkGetMemberAccessorParameter(node)) { + this.skip(node); + return; + } + + _super.prototype.visitGetMemberAccessorDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkSetMemberAccessorParameter = function (node) { + var setKeywordFullStart = this.childFullStart(node, node.setKeyword); + if (node.parameterList.parameters.childCount() !== 1) { + this.pushDiagnostic1(setKeywordFullStart, node.setKeyword, 50 /* _set__accessor_must_have_only_one_parameter */); + return true; + } + + var parameterListFullStart = this.childFullStart(node, node.parameterList); + var parameterFullStart = parameterListFullStart + TypeScript.Syntax.childOffset(node.parameterList, node.parameterList.openParenToken); + var parameter = node.parameterList.parameters.childAt(0); + + if (parameter.publicOrPrivateKeyword) { + this.pushDiagnostic1(parameterFullStart, parameter, 51 /* _set__accessor_parameter_cannot_have_accessibility_modifier */); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 52 /* _set__accessor_parameter_cannot_be_optional */); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 53 /* _set__accessor_parameter_cannot_have_initializer */); + return true; + } + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 54 /* _set__accessor_cannot_have_rest_parameter */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSetMemberAccessorDeclaration = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */) || this.checkClassElementModifiers(node.modifiers) || this.checkSetMemberAccessorParameter(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSetMemberAccessorDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitGetAccessorPropertyAssignment = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */)) { + this.skip(node); + return; + } + + _super.prototype.visitGetAccessorPropertyAssignment.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSetAccessorPropertyAssignment = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */)) { + this.skip(node); + return; + } + + _super.prototype.visitSetAccessorPropertyAssignment.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, 62 /* Enum_name_cannot_be__0_ */) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.enumKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var enumElementFullStart = this.childFullStart(node, node.enumElements); + + var seenComputedValue = false; + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + var child = node.enumElements.childAt(i); + + if (i % 2 === 0) { + var enumElement = child; + + if (!enumElement.equalsValueClause && seenComputedValue) { + this.pushDiagnostic1(enumElementFullStart, enumElement, 64 /* Enum_member_must_have_initializer */, null); + return true; + } + + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + if (value.kind() !== 13 /* NumericLiteral */) { + seenComputedValue = true; + } + } + } + + enumElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic1(this.position(), node, 37 /* _super__invocation_cannot_have_type_arguments */); + } + + _super.prototype.visitInvocationExpression.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var modifierFullStart = this.position(); + var seenExportModifier = false; + var seenDeclareModifier = false; + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */ || modifier.tokenKind === 58 /* StaticKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, 47 /* _0__modifier_cannot_appear_on_a_module_element */, [modifier.text()]); + return true; + } + + if (modifier.tokenKind === 64 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 32 /* Accessibility_modifier_already_seen */); + return; + } + + seenDeclareModifier = true; + } else if (modifier.tokenKind === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 34 /* _0__modifier_already_seen */, [modifier.text()]); + return; + } + + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 33 /* _0__modifier_must_precede__1__modifier */, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(64 /* DeclareKeyword */)]); + return; + } + + seenExportModifier = true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + if (node.stringLiteral === null) { + var currentElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.pushDiagnostic1(currentElementFullStart, importDeclaration, 201 /* Import_declarations_in_an_internal_module_cannot_reference_an_external_module */, null); + } + } + + currentElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForReservedName(node, node.moduleName, 63 /* Module_name_cannot_be__0_ */) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.moduleKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (!TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) && this.checkFunctionOverloads(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (node.stringLiteral && !this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */)) { + var stringLiteralFullStart = this.childFullStart(node, node.stringLiteral); + this.pushDiagnostic1(stringLiteralFullStart, node.stringLiteral, 38 /* Non_ambient_modules_cannot_use_quoted_names */); + this.skip(node); + return; + } + + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExports = function (node, moduleElements) { + var seenExportedElement = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (TypeScript.SyntaxUtilities.hasExportKeyword(child)) { + seenExportedElement = true; + break; + } + } + + var moduleElementFullStart = this.childFullStart(node, moduleElements); + if (seenExportedElement) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, 67 /* Export_assignment_not_allowed_in_module_with_exported_element */); + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForMultipleExportAssignments = function (node, moduleElements) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + var seenExportAssignment = false; + var errorFound = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + if (child.kind() === 134 /* ExportAssignment */) { + if (seenExportAssignment) { + this.pushDiagnostic1(moduleElementFullStart, child, 68 /* Module_cannot_have_multiple_export_assignments */); + errorFound = true; + } + seenExportAssignment = true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return errorFound; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + var moduleElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, 66 /* Export_assignments_cannot_be_used_in_internal_modules */); + + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), 40 /* Implementations_are_not_allowed_in_ambient_contexts */); + this.skip(node); + return; + } + + if (this.checkFunctionOverloads(node, node.statements)) { + this.skip(node); + return; + } + + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), 39 /* Statements_are_not_allowed_in_ambient_contexts */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitBreakStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitContinueStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDebuggerStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDoStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitEmptyStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitExpressionStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForInStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIfStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitLabeledStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitReturnStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSwitchStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitThrowStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitTryStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWhileStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWithStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock && modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(parent, modifiers); + this.pushDiagnostic1(modifierFullStart, modifiers.childAt(0), 58 /* Modifiers_cannot_appear_here */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.functionKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic1(currentElementFullStart, child, 9 /* _0_expected */, [TypeScript.SyntaxFacts.getText(kind)]); + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 79 /* SemicolonToken */)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitEqualsValueClause = function (node) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic1(this.position(), node.firstToken(), 42 /* Initializers_are_not_allowed_in_ambient_contexts */); + this.skip(node); + return; + } + + _super.prototype.visitEqualsValueClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + var savedCurrentConstructor = this.currentConstructor; + this.currentConstructor = node; + _super.prototype.visitConstructorDeclaration.call(this, node); + this.currentConstructor = savedCurrentConstructor; + }; + + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { + if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + _super.prototype.visitSourceUnit.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExternalModuleReference = function (node) { + if (node.moduleOrRequireKeyword.tokenKind === 66 /* ModuleKeyword */ && !this.syntaxTree.parseOptions().allowModuleKeywordInExternalModuleReference()) { + this.pushDiagnostic1(this.position(), node.moduleOrRequireKeyword, 65 /* _module_______is_deprecated__Use__require_______instead */); + this.skip(node); + return; + } + + _super.prototype.visitExternalModuleReference.call(this, node); + }; + return GrammarCheckerWalker; + })(TypeScript.PositionTrackingWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpanWalker = (function (_super) { + __extends(TextSpanWalker, _super); + function TextSpanWalker(textSpan) { + _super.call(this); + this.textSpan = textSpan; + this._position = 0; + } + TextSpanWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + TextSpanWalker.prototype.visitNode = function (node) { + var nodeSpan = new TypeScript.TextSpan(this.position(), node.fullWidth()); + + if (nodeSpan.intersectsWithTextSpan(this.textSpan)) { + node.accept(this); + } else { + this._position += node.fullWidth(); + } + }; + + TextSpanWalker.prototype.position = function () { + return this._position; + }; + return TextSpanWalker; + })(TypeScript.SyntaxWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + + var lo = 0; + var hi = map.length; + var mid; + + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + + if (code < map[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + + return false; + }; + + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + Unicode.unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + + Unicode.unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) !== 0; + } + TypeScript.hasFlag = hasFlag; + + function withoutFlag(val, flag) { + return val & ~flag; + } + TypeScript.withoutFlag = withoutFlag; + + (function (ASTFlags) { + ASTFlags[ASTFlags["None"] = 0] = "None"; + ASTFlags[ASTFlags["SingleLine"] = 1 << 1] = "SingleLine"; + ASTFlags[ASTFlags["OptionalName"] = 1 << 2] = "OptionalName"; + ASTFlags[ASTFlags["TypeReference"] = 1 << 3] = "TypeReference"; + ASTFlags[ASTFlags["EnumElement"] = 1 << 4] = "EnumElement"; + ASTFlags[ASTFlags["EnumMapElement"] = 1 << 5] = "EnumMapElement"; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + + (function (DeclFlags) { + DeclFlags[DeclFlags["None"] = 0] = "None"; + DeclFlags[DeclFlags["Exported"] = 1] = "Exported"; + DeclFlags[DeclFlags["Private"] = 1 << 1] = "Private"; + DeclFlags[DeclFlags["Public"] = 1 << 2] = "Public"; + DeclFlags[DeclFlags["Ambient"] = 1 << 3] = "Ambient"; + DeclFlags[DeclFlags["Static"] = 1 << 4] = "Static"; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + + (function (ModuleFlags) { + ModuleFlags[ModuleFlags["None"] = 0] = "None"; + ModuleFlags[ModuleFlags["Exported"] = 1] = "Exported"; + ModuleFlags[ModuleFlags["Private"] = 1 << 1] = "Private"; + ModuleFlags[ModuleFlags["Public"] = 1 << 2] = "Public"; + ModuleFlags[ModuleFlags["Ambient"] = 1 << 3] = "Ambient"; + ModuleFlags[ModuleFlags["Static"] = 1 << 4] = "Static"; + ModuleFlags[ModuleFlags["IsEnum"] = 1 << 7] = "IsEnum"; + ModuleFlags[ModuleFlags["IsWholeFile"] = 1 << 8] = "IsWholeFile"; + ModuleFlags[ModuleFlags["IsDynamic"] = 1 << 9] = "IsDynamic"; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + + (function (VariableFlags) { + VariableFlags[VariableFlags["None"] = 0] = "None"; + VariableFlags[VariableFlags["Exported"] = 1] = "Exported"; + VariableFlags[VariableFlags["Private"] = 1 << 1] = "Private"; + VariableFlags[VariableFlags["Public"] = 1 << 2] = "Public"; + VariableFlags[VariableFlags["Ambient"] = 1 << 3] = "Ambient"; + VariableFlags[VariableFlags["Static"] = 1 << 4] = "Static"; + VariableFlags[VariableFlags["Property"] = 1 << 8] = "Property"; + VariableFlags[VariableFlags["ClassProperty"] = 1 << 11] = "ClassProperty"; + VariableFlags[VariableFlags["Constant"] = 1 << 12] = "Constant"; + + VariableFlags[VariableFlags["EnumElement"] = 1 << 13] = "EnumElement"; + })(TypeScript.VariableFlags || (TypeScript.VariableFlags = {})); + var VariableFlags = TypeScript.VariableFlags; + + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["None"] = 0] = "None"; + FunctionFlags[FunctionFlags["Exported"] = 1] = "Exported"; + FunctionFlags[FunctionFlags["Private"] = 1 << 1] = "Private"; + FunctionFlags[FunctionFlags["Public"] = 1 << 2] = "Public"; + FunctionFlags[FunctionFlags["Ambient"] = 1 << 3] = "Ambient"; + FunctionFlags[FunctionFlags["Static"] = 1 << 4] = "Static"; + FunctionFlags[FunctionFlags["GetAccessor"] = 1 << 5] = "GetAccessor"; + FunctionFlags[FunctionFlags["SetAccessor"] = 1 << 6] = "SetAccessor"; + FunctionFlags[FunctionFlags["Signature"] = 1 << 7] = "Signature"; + FunctionFlags[FunctionFlags["Method"] = 1 << 8] = "Method"; + FunctionFlags[FunctionFlags["CallMember"] = 1 << 9] = "CallMember"; + FunctionFlags[FunctionFlags["ConstructMember"] = 1 << 10] = "ConstructMember"; + FunctionFlags[FunctionFlags["IsFatArrowFunction"] = 1 << 11] = "IsFatArrowFunction"; + FunctionFlags[FunctionFlags["IndexerMember"] = 1 << 12] = "IndexerMember"; + FunctionFlags[FunctionFlags["IsFunctionExpression"] = 1 << 13] = "IsFunctionExpression"; + FunctionFlags[FunctionFlags["IsFunctionProperty"] = 1 << 14] = "IsFunctionProperty"; + })(TypeScript.FunctionFlags || (TypeScript.FunctionFlags = {})); + var FunctionFlags = TypeScript.FunctionFlags; + + function ToDeclFlags(fncOrVarOrModuleFlags) { + return fncOrVarOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["InconsistantPropertyAccesibility"] = 1 << 7] = "InconsistantPropertyAccesibility"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 0] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 1] = "Asynchronous"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (NodeType) { + NodeType[NodeType["None"] = 0] = "None"; + NodeType[NodeType["List"] = 1] = "List"; + NodeType[NodeType["Script"] = 2] = "Script"; + + NodeType[NodeType["TrueLiteral"] = 3] = "TrueLiteral"; + NodeType[NodeType["FalseLiteral"] = 4] = "FalseLiteral"; + NodeType[NodeType["StringLiteral"] = 5] = "StringLiteral"; + NodeType[NodeType["RegularExpressionLiteral"] = 6] = "RegularExpressionLiteral"; + NodeType[NodeType["NumericLiteral"] = 7] = "NumericLiteral"; + NodeType[NodeType["NullLiteral"] = 8] = "NullLiteral"; + + NodeType[NodeType["TypeParameter"] = 9] = "TypeParameter"; + NodeType[NodeType["GenericType"] = 10] = "GenericType"; + NodeType[NodeType["TypeRef"] = 11] = "TypeRef"; + + NodeType[NodeType["FunctionDeclaration"] = 12] = "FunctionDeclaration"; + NodeType[NodeType["ClassDeclaration"] = 13] = "ClassDeclaration"; + NodeType[NodeType["InterfaceDeclaration"] = 14] = "InterfaceDeclaration"; + NodeType[NodeType["ModuleDeclaration"] = 15] = "ModuleDeclaration"; + NodeType[NodeType["ImportDeclaration"] = 16] = "ImportDeclaration"; + NodeType[NodeType["VariableDeclarator"] = 17] = "VariableDeclarator"; + NodeType[NodeType["VariableDeclaration"] = 18] = "VariableDeclaration"; + NodeType[NodeType["Parameter"] = 19] = "Parameter"; + + NodeType[NodeType["Name"] = 20] = "Name"; + NodeType[NodeType["ArrayLiteralExpression"] = 21] = "ArrayLiteralExpression"; + NodeType[NodeType["ObjectLiteralExpression"] = 22] = "ObjectLiteralExpression"; + NodeType[NodeType["OmittedExpression"] = 23] = "OmittedExpression"; + NodeType[NodeType["VoidExpression"] = 24] = "VoidExpression"; + NodeType[NodeType["CommaExpression"] = 25] = "CommaExpression"; + NodeType[NodeType["PlusExpression"] = 26] = "PlusExpression"; + NodeType[NodeType["NegateExpression"] = 27] = "NegateExpression"; + NodeType[NodeType["DeleteExpression"] = 28] = "DeleteExpression"; + NodeType[NodeType["ThisExpression"] = 29] = "ThisExpression"; + NodeType[NodeType["SuperExpression"] = 30] = "SuperExpression"; + NodeType[NodeType["InExpression"] = 31] = "InExpression"; + NodeType[NodeType["MemberAccessExpression"] = 32] = "MemberAccessExpression"; + NodeType[NodeType["InstanceOfExpression"] = 33] = "InstanceOfExpression"; + NodeType[NodeType["TypeOfExpression"] = 34] = "TypeOfExpression"; + NodeType[NodeType["ElementAccessExpression"] = 35] = "ElementAccessExpression"; + NodeType[NodeType["InvocationExpression"] = 36] = "InvocationExpression"; + NodeType[NodeType["ObjectCreationExpression"] = 37] = "ObjectCreationExpression"; + NodeType[NodeType["AssignmentExpression"] = 38] = "AssignmentExpression"; + NodeType[NodeType["AddAssignmentExpression"] = 39] = "AddAssignmentExpression"; + NodeType[NodeType["SubtractAssignmentExpression"] = 40] = "SubtractAssignmentExpression"; + NodeType[NodeType["DivideAssignmentExpression"] = 41] = "DivideAssignmentExpression"; + NodeType[NodeType["MultiplyAssignmentExpression"] = 42] = "MultiplyAssignmentExpression"; + NodeType[NodeType["ModuloAssignmentExpression"] = 43] = "ModuloAssignmentExpression"; + NodeType[NodeType["AndAssignmentExpression"] = 44] = "AndAssignmentExpression"; + NodeType[NodeType["ExclusiveOrAssignmentExpression"] = 45] = "ExclusiveOrAssignmentExpression"; + NodeType[NodeType["OrAssignmentExpression"] = 46] = "OrAssignmentExpression"; + NodeType[NodeType["LeftShiftAssignmentExpression"] = 47] = "LeftShiftAssignmentExpression"; + NodeType[NodeType["SignedRightShiftAssignmentExpression"] = 48] = "SignedRightShiftAssignmentExpression"; + NodeType[NodeType["UnsignedRightShiftAssignmentExpression"] = 49] = "UnsignedRightShiftAssignmentExpression"; + NodeType[NodeType["ConditionalExpression"] = 50] = "ConditionalExpression"; + NodeType[NodeType["LogicalOrExpression"] = 51] = "LogicalOrExpression"; + NodeType[NodeType["LogicalAndExpression"] = 52] = "LogicalAndExpression"; + NodeType[NodeType["BitwiseOrExpression"] = 53] = "BitwiseOrExpression"; + NodeType[NodeType["BitwiseExclusiveOrExpression"] = 54] = "BitwiseExclusiveOrExpression"; + NodeType[NodeType["BitwiseAndExpression"] = 55] = "BitwiseAndExpression"; + NodeType[NodeType["EqualsWithTypeConversionExpression"] = 56] = "EqualsWithTypeConversionExpression"; + NodeType[NodeType["NotEqualsWithTypeConversionExpression"] = 57] = "NotEqualsWithTypeConversionExpression"; + NodeType[NodeType["EqualsExpression"] = 58] = "EqualsExpression"; + NodeType[NodeType["NotEqualsExpression"] = 59] = "NotEqualsExpression"; + NodeType[NodeType["LessThanExpression"] = 60] = "LessThanExpression"; + NodeType[NodeType["LessThanOrEqualExpression"] = 61] = "LessThanOrEqualExpression"; + NodeType[NodeType["GreaterThanExpression"] = 62] = "GreaterThanExpression"; + NodeType[NodeType["GreaterThanOrEqualExpression"] = 63] = "GreaterThanOrEqualExpression"; + NodeType[NodeType["AddExpression"] = 64] = "AddExpression"; + NodeType[NodeType["SubtractExpression"] = 65] = "SubtractExpression"; + NodeType[NodeType["MultiplyExpression"] = 66] = "MultiplyExpression"; + NodeType[NodeType["DivideExpression"] = 67] = "DivideExpression"; + NodeType[NodeType["ModuloExpression"] = 68] = "ModuloExpression"; + NodeType[NodeType["LeftShiftExpression"] = 69] = "LeftShiftExpression"; + NodeType[NodeType["SignedRightShiftExpression"] = 70] = "SignedRightShiftExpression"; + NodeType[NodeType["UnsignedRightShiftExpression"] = 71] = "UnsignedRightShiftExpression"; + NodeType[NodeType["BitwiseNotExpression"] = 72] = "BitwiseNotExpression"; + NodeType[NodeType["LogicalNotExpression"] = 73] = "LogicalNotExpression"; + NodeType[NodeType["PreIncrementExpression"] = 74] = "PreIncrementExpression"; + NodeType[NodeType["PreDecrementExpression"] = 75] = "PreDecrementExpression"; + NodeType[NodeType["PostIncrementExpression"] = 76] = "PostIncrementExpression"; + NodeType[NodeType["PostDecrementExpression"] = 77] = "PostDecrementExpression"; + NodeType[NodeType["CastExpression"] = 78] = "CastExpression"; + NodeType[NodeType["ParenthesizedExpression"] = 79] = "ParenthesizedExpression"; + NodeType[NodeType["Member"] = 80] = "Member"; + + NodeType[NodeType["Block"] = 81] = "Block"; + NodeType[NodeType["BreakStatement"] = 82] = "BreakStatement"; + NodeType[NodeType["ContinueStatement"] = 83] = "ContinueStatement"; + NodeType[NodeType["DebuggerStatement"] = 84] = "DebuggerStatement"; + NodeType[NodeType["DoStatement"] = 85] = "DoStatement"; + NodeType[NodeType["EmptyStatement"] = 86] = "EmptyStatement"; + NodeType[NodeType["ExportAssignment"] = 87] = "ExportAssignment"; + NodeType[NodeType["ExpressionStatement"] = 88] = "ExpressionStatement"; + NodeType[NodeType["ForInStatement"] = 89] = "ForInStatement"; + NodeType[NodeType["ForStatement"] = 90] = "ForStatement"; + NodeType[NodeType["IfStatement"] = 91] = "IfStatement"; + NodeType[NodeType["LabeledStatement"] = 92] = "LabeledStatement"; + NodeType[NodeType["ReturnStatement"] = 93] = "ReturnStatement"; + NodeType[NodeType["SwitchStatement"] = 94] = "SwitchStatement"; + NodeType[NodeType["ThrowStatement"] = 95] = "ThrowStatement"; + NodeType[NodeType["TryStatement"] = 96] = "TryStatement"; + NodeType[NodeType["VariableStatement"] = 97] = "VariableStatement"; + NodeType[NodeType["WhileStatement"] = 98] = "WhileStatement"; + NodeType[NodeType["WithStatement"] = 99] = "WithStatement"; + + NodeType[NodeType["CaseClause"] = 100] = "CaseClause"; + NodeType[NodeType["CatchClause"] = 101] = "CatchClause"; + + NodeType[NodeType["Comment"] = 102] = "Comment"; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + + for (var k in this.table) { + if (this.table[k] !== undefined) { + result.push(k); + } + } + + return result; + }; + + StringHashTable.prototype.add = function (key, data) { + if (this.table[key] !== undefined) { + return false; + } + + this.table[key] = data; + this.itemCount++; + return true; + }; + + StringHashTable.prototype.addOrUpdate = function (key, data) { + if (this.table[key] !== undefined) { + this.table[key] = data; + return false; + } + + this.table[key] = data; + this.itemCount++; + return true; + }; + + StringHashTable.prototype.map = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + + if (data !== undefined) { + fn(k, this.table[k], context); + } + } + }; + + StringHashTable.prototype.every = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + + if (data !== undefined) { + if (!fn(k, this.table[k], context)) { + return false; + } + } + } + + return true; + }; + + StringHashTable.prototype.some = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + + if (data !== undefined) { + if (fn(k, this.table[k], context)) { + return true; + } + } + } + + return false; + }; + + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + return data === undefined ? null : data; + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + + var IdentiferNameHashTable = (function (_super) { + __extends(IdentiferNameHashTable, _super); + function IdentiferNameHashTable() { + _super.apply(this, arguments); + } + IdentiferNameHashTable.prototype.getAllKeys = function () { + var result = []; + + _super.prototype.map.call(this, function (k, v, c) { + if (v !== undefined) { + result.push(k.substring(1)); + } + }, null); + + return result; + }; + + IdentiferNameHashTable.prototype.add = function (key, data) { + return _super.prototype.add.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.addOrUpdate = function (key, data) { + return _super.prototype.addOrUpdate.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.map = function (fn, context) { + return _super.prototype.map.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.every = function (fn, context) { + return _super.prototype.every.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.some = function (fn, context) { + return _super.prototype.some.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.lookup = function (key) { + return _super.prototype.lookup.call(this, "#" + key); + }; + return IdentiferNameHashTable; + })(StringHashTable); + TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; + this.limChar = -1; + this.trailingTriviaWidth = 0; + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + + TypeScript.astID = 0; + + function structuralEqualsNotIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, false); + } + TypeScript.structuralEqualsNotIncludingPosition = structuralEqualsNotIncludingPosition; + + function structuralEqualsIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, true); + } + TypeScript.structuralEqualsIncludingPosition = structuralEqualsIncludingPosition; + + function structuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.nodeType === ast2.nodeType && ast1.structuralEquals(ast2, includingPosition); + } + + function astArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? structuralEqualsIncludingPosition : structuralEqualsNotIncludingPosition); + } + + var AST = (function () { + function AST(nodeType) { + this.nodeType = nodeType; + this.minChar = -1; + this.limChar = -1; + this.trailingTriviaWidth = 0; + this._flags = 0 /* None */; + this.typeCheckPhase = -1; + this.astID = TypeScript.astID++; + this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.docComments = null; + } + AST.prototype.shouldEmit = function () { + return true; + }; + + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + + AST.prototype.getFlags = function () { + return this._flags; + }; + + AST.prototype.setFlags = function (flags) { + this._flags = flags; + }; + + AST.prototype.getLength = function () { + return this.limChar - this.minChar; + }; + + AST.prototype.getID = function () { + return this.astID; + }; + + AST.prototype.isDeclaration = function () { + return false; + }; + + AST.prototype.isStatement = function () { + return false; + }; + + AST.prototype.emit = function (emitter) { + emitter.emitComments(this, true); + emitter.recordSourceMappingStart(this); + this.emitWorker(emitter); + emitter.recordSourceMappingEnd(this); + emitter.emitComments(this, false); + }; + + AST.prototype.emitWorker = function (emitter) { + throw new Error("please implement in derived class"); + }; + + AST.prototype.getDocComments = function () { + if (!this.isDeclaration() || !this.preComments || this.preComments.length === 0) { + return []; + } + + if (!this.docComments) { + var preCommentsLength = this.preComments.length; + var docComments = []; + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (this.preComments[i].isDocComment()) { + var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; + if (prevDocComment === null || (this.preComments[i].limLine === prevDocComment.minLine || this.preComments[i].limLine + 1 === prevDocComment.minLine)) { + docComments.push(this.preComments[i]); + continue; + } + } + break; + } + + this.docComments = docComments.reverse(); + } + + return this.docComments; + }; + + AST.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.minChar !== ast.minChar || this.limChar !== ast.limChar) { + return false; + } + } + + return this._flags === ast._flags && astArrayStructuralEquals(this.preComments, ast.preComments, includingPosition) && astArrayStructuralEquals(this.postComments, ast.postComments, includingPosition); + }; + return AST; + })(); + TypeScript.AST = AST; + + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, 1 /* List */); + this.members = []; + } + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + + ASTList.prototype.emit = function (emitter) { + emitter.recordSourceMappingStart(this); + emitter.emitModuleElements(this); + emitter.recordSourceMappingEnd(this); + }; + + ASTList.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + return Expression; + })(AST); + TypeScript.Expression = Expression; + + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(actualText) { + _super.call(this, 20 /* Name */); + this.actualText = actualText; + this.setText(actualText); + } + Identifier.prototype.setText = function (actualText) { + this.actualText = actualText; + this.text = actualText; + }; + + Identifier.prototype.isMissing = function () { + return false; + }; + + Identifier.prototype.emit = function (emitter) { + emitter.emitName(this, true); + }; + + Identifier.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.text === ast.text && this.actualText === ast.actualText && this.isMissing() === ast.isMissing(); + }; + return Identifier; + })(Expression); + TypeScript.Identifier = Identifier; + + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + + MissingIdentifier.prototype.emit = function (emitter) { + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + + var LiteralExpression = (function (_super) { + __extends(LiteralExpression, _super); + function LiteralExpression(nodeType) { + _super.call(this, nodeType); + } + LiteralExpression.prototype.emitWorker = function (emitter) { + switch (this.nodeType) { + case 8 /* NullLiteral */: + emitter.writeToOutput("null"); + break; + case 4 /* FalseLiteral */: + emitter.writeToOutput("false"); + break; + case 3 /* TrueLiteral */: + emitter.writeToOutput("true"); + break; + default: + throw new Error("please implement in derived class"); + } + }; + + LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return LiteralExpression; + })(Expression); + TypeScript.LiteralExpression = LiteralExpression; + + var ThisExpression = (function (_super) { + __extends(ThisExpression, _super); + function ThisExpression() { + _super.call(this, 29 /* ThisExpression */); + } + ThisExpression.prototype.emitWorker = function (emitter) { + if (emitter.thisFunctionDeclaration && (TypeScript.hasFlag(emitter.thisFunctionDeclaration.getFunctionFlags(), 2048 /* IsFatArrowFunction */))) { + emitter.writeToOutput("_this"); + } else { + emitter.writeToOutput("this"); + } + }; + + ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return ThisExpression; + })(Expression); + TypeScript.ThisExpression = ThisExpression; + + var SuperExpression = (function (_super) { + __extends(SuperExpression, _super); + function SuperExpression() { + _super.call(this, 30 /* SuperExpression */); + } + SuperExpression.prototype.emitWorker = function (emitter) { + emitter.emitSuperReference(); + }; + + SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return SuperExpression; + })(Expression); + TypeScript.SuperExpression = SuperExpression; + + var ParenthesizedExpression = (function (_super) { + __extends(ParenthesizedExpression, _super); + function ParenthesizedExpression(expression) { + _super.call(this, 79 /* ParenthesizedExpression */); + this.expression = expression; + } + ParenthesizedExpression.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("("); + this.expression.emit(emitter); + emitter.writeToOutput(")"); + }; + + ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ParenthesizedExpression; + })(Expression); + TypeScript.ParenthesizedExpression = ParenthesizedExpression; + + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.castTerm = null; + } + UnaryExpression.prototype.emitWorker = function (emitter) { + switch (this.nodeType) { + case 76 /* PostIncrementExpression */: + this.operand.emit(emitter); + emitter.writeToOutput("++"); + break; + case 73 /* LogicalNotExpression */: + emitter.writeToOutput("!"); + this.operand.emit(emitter); + break; + case 77 /* PostDecrementExpression */: + this.operand.emit(emitter); + emitter.writeToOutput("--"); + break; + case 22 /* ObjectLiteralExpression */: + emitter.emitObjectLiteral(this); + break; + case 21 /* ArrayLiteralExpression */: + emitter.emitArrayLiteral(this); + break; + case 72 /* BitwiseNotExpression */: + emitter.writeToOutput("~"); + this.operand.emit(emitter); + break; + case 27 /* NegateExpression */: + emitter.writeToOutput("-"); + if (this.operand.nodeType === 27 /* NegateExpression */ || this.operand.nodeType === 75 /* PreDecrementExpression */) { + emitter.writeToOutput(" "); + } + this.operand.emit(emitter); + break; + case 26 /* PlusExpression */: + emitter.writeToOutput("+"); + if (this.operand.nodeType === 26 /* PlusExpression */ || this.operand.nodeType === 74 /* PreIncrementExpression */) { + emitter.writeToOutput(" "); + } + this.operand.emit(emitter); + break; + case 74 /* PreIncrementExpression */: + emitter.writeToOutput("++"); + this.operand.emit(emitter); + break; + case 75 /* PreDecrementExpression */: + emitter.writeToOutput("--"); + this.operand.emit(emitter); + break; + case 34 /* TypeOfExpression */: + emitter.writeToOutput("typeof "); + this.operand.emit(emitter); + break; + case 28 /* DeleteExpression */: + emitter.writeToOutput("delete "); + this.operand.emit(emitter); + break; + case 24 /* VoidExpression */: + emitter.writeToOutput("void "); + this.operand.emit(emitter); + break; + case 78 /* CastExpression */: + this.operand.emit(emitter); + break; + default: + throw new Error("please implement in derived class"); + } + }; + + UnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.castTerm, ast.castTerm, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, typeArguments, arguments) { + _super.call(this, nodeType); + this.target = target; + this.typeArguments = typeArguments; + this.arguments = arguments; + } + CallExpression.prototype.emitWorker = function (emitter) { + if (this.nodeType === 37 /* ObjectCreationExpression */) { + emitter.emitNew(this.target, this.arguments); + } else { + emitter.emitCall(this, this.target, this.arguments); + } + }; + + CallExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.target, ast.target, includingPosition) && structuralEquals(this.typeArguments, ast.typeArguments, includingPosition) && structuralEquals(this.arguments, ast.arguments, includingPosition); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.getTextForBinaryToken = function (nodeType) { + switch (nodeType) { + case 25 /* CommaExpression */: + return ","; + case 38 /* AssignmentExpression */: + return "="; + case 39 /* AddAssignmentExpression */: + return "+="; + case 40 /* SubtractAssignmentExpression */: + return "-="; + case 42 /* MultiplyAssignmentExpression */: + return "*="; + case 41 /* DivideAssignmentExpression */: + return "/="; + case 43 /* ModuloAssignmentExpression */: + return "%="; + case 44 /* AndAssignmentExpression */: + return "&="; + case 45 /* ExclusiveOrAssignmentExpression */: + return "^="; + case 46 /* OrAssignmentExpression */: + return "|="; + case 47 /* LeftShiftAssignmentExpression */: + return "<<="; + case 48 /* SignedRightShiftAssignmentExpression */: + return ">>="; + case 49 /* UnsignedRightShiftAssignmentExpression */: + return ">>>="; + case 51 /* LogicalOrExpression */: + return "||"; + case 52 /* LogicalAndExpression */: + return "&&"; + case 53 /* BitwiseOrExpression */: + return "|"; + case 54 /* BitwiseExclusiveOrExpression */: + return "^"; + case 55 /* BitwiseAndExpression */: + return "&"; + case 56 /* EqualsWithTypeConversionExpression */: + return "=="; + case 57 /* NotEqualsWithTypeConversionExpression */: + return "!="; + case 58 /* EqualsExpression */: + return "==="; + case 59 /* NotEqualsExpression */: + return "!=="; + case 60 /* LessThanExpression */: + return "<"; + case 62 /* GreaterThanExpression */: + return ">"; + case 61 /* LessThanOrEqualExpression */: + return "<="; + case 63 /* GreaterThanOrEqualExpression */: + return ">="; + case 33 /* InstanceOfExpression */: + return "instanceof"; + case 31 /* InExpression */: + return "in"; + case 69 /* LeftShiftExpression */: + return "<<"; + case 70 /* SignedRightShiftExpression */: + return ">>"; + case 71 /* UnsignedRightShiftExpression */: + return ">>>"; + case 66 /* MultiplyExpression */: + return "*"; + case 67 /* DivideExpression */: + return "/"; + case 68 /* ModuloExpression */: + return "%"; + case 64 /* AddExpression */: + return "+"; + case 65 /* SubtractExpression */: + return "-"; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + BinaryExpression.prototype.emitWorker = function (emitter) { + switch (this.nodeType) { + case 32 /* MemberAccessExpression */: + if (!emitter.tryEmitConstant(this)) { + this.operand1.emit(emitter); + emitter.writeToOutput("."); + emitter.emitName(this.operand2, false); + } + break; + case 35 /* ElementAccessExpression */: + emitter.emitIndex(this.operand1, this.operand2); + break; + + case 80 /* Member */: + if (this.operand2.nodeType === 12 /* FunctionDeclaration */ && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 32 /* GetAccessor */)) { + emitter.writeToOutput("get "); + } else { + emitter.writeToOutput("set "); + } + this.operand1.emit(emitter); + } else { + this.operand1.emit(emitter); + emitter.writeToOutputTrimmable(": "); + } + this.operand2.emit(emitter); + break; + case 25 /* CommaExpression */: + this.operand1.emit(emitter); + emitter.writeToOutput(", "); + this.operand2.emit(emitter); + break; + default: { + this.operand1.emit(emitter); + var binOp = BinaryExpression.getTextForBinaryToken(this.nodeType); + if (binOp === "instanceof") { + emitter.writeToOutput(" instanceof "); + } else if (binOp === "in") { + emitter.writeToOutput(" in "); + } else { + emitter.writeToOutputTrimmable(" " + binOp + " "); + } + this.operand2.emit(emitter); + } + } + }; + + BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand1, ast.operand1, includingPosition) && structuralEquals(this.operand2, ast.operand2, includingPosition); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, 50 /* ConditionalExpression */); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.emitWorker = function (emitter) { + this.operand1.emit(emitter); + emitter.writeToOutput(" ? "); + this.operand2.emit(emitter); + emitter.writeToOutput(" : "); + this.operand3.emit(emitter); + }; + + ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand1, ast.operand1, includingPosition) && structuralEquals(this.operand2, ast.operand2, includingPosition) && structuralEquals(this.operand3, ast.operand3, includingPosition); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, text) { + _super.call(this, 7 /* NumericLiteral */); + this.value = value; + this.text = text; + } + NumberLiteral.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.text); + }; + + NumberLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.value === ast.value && this.text === ast.text; + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(text) { + _super.call(this, 6 /* RegularExpressionLiteral */); + this.text = text; + } + RegexLiteral.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.text); + }; + + RegexLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.text === ast.text; + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(actualText, text) { + _super.call(this, 5 /* StringLiteral */); + this.actualText = actualText; + this.text = text; + } + StringLiteral.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.actualText); + }; + + StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.actualText === ast.actualText; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, 16 /* ImportDeclaration */); + this.id = id; + this.alias = alias; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + + ImportDeclaration.prototype.isDeclaration = function () { + return true; + }; + + ImportDeclaration.prototype.emit = function (emitter) { + if (emitter.importStatementShouldBeEmitted(this)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + + emitter.recordSourceMappingStart(this); + emitter.emitComments(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + var aliasAST = this.alias.nodeType === 11 /* TypeRef */ ? (this.alias).term : this.alias; + + emitter.emitJavascript(aliasAST, false); + emitter.writeToOutput(";"); + + emitter.emitComments(this, false); + emitter.recordSourceMappingEnd(this); + + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (typeof aliasAST === "undefined") { aliasAST = this.alias; } + if (aliasAST.nodeType === 20 /* Name */) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + + ImportDeclaration.prototype.firstAliasedModToString = function () { + if (this.alias.nodeType === 20 /* Name */) { + return (this.alias).actualText; + } else { + var dotExpr = this.alias; + var firstMod = (dotExpr.term).operand1; + return firstMod.actualText; + } + }; + + ImportDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.id, ast.id, includingPosition) && structuralEquals(this.alias, ast.alias, includingPosition); + }; + return ImportDeclaration; + })(AST); + TypeScript.ImportDeclaration = ImportDeclaration; + + var ExportAssignment = (function (_super) { + __extends(ExportAssignment, _super); + function ExportAssignment(id) { + _super.call(this, 87 /* ExportAssignment */); + this.id = id; + } + ExportAssignment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.id, ast.id, includingPosition); + }; + + ExportAssignment.prototype.emit = function (emitter) { + emitter.setExportAssignmentIdentifier(this.id.actualText); + }; + return ExportAssignment; + })(AST); + TypeScript.ExportAssignment = ExportAssignment; + + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType) { + _super.call(this, nodeType); + this.id = id; + this.init = null; + this.isImplicitlyInitialized = false; + this.typeExpr = null; + this._varFlags = 0 /* None */; + } + BoundDecl.prototype.isDeclaration = function () { + return true; + }; + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + + BoundDecl.prototype.getVarFlags = function () { + return this._varFlags; + }; + + BoundDecl.prototype.setVarFlags = function (flags) { + this._varFlags = flags; + }; + + BoundDecl.prototype.isProperty = function () { + return TypeScript.hasFlag(this.getVarFlags(), 256 /* Property */); + }; + + BoundDecl.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._varFlags === ast._varFlags && structuralEquals(this.init, ast.init, includingPosition) && structuralEquals(this.typeExpr, ast.typeExpr, includingPosition) && structuralEquals(this.id, ast.id, includingPosition); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + + var VariableDeclarator = (function (_super) { + __extends(VariableDeclarator, _super); + function VariableDeclarator(id) { + _super.call(this, id, 17 /* VariableDeclarator */); + } + VariableDeclarator.prototype.isExported = function () { + return TypeScript.hasFlag(this.getVarFlags(), 1 /* Exported */); + }; + + VariableDeclarator.prototype.isStatic = function () { + return TypeScript.hasFlag(this.getVarFlags(), 16 /* Static */); + }; + + VariableDeclarator.prototype.emit = function (emitter) { + emitter.emitVariableDeclarator(this); + }; + return VariableDeclarator; + })(BoundDecl); + TypeScript.VariableDeclarator = VariableDeclarator; + + var Parameter = (function (_super) { + __extends(Parameter, _super); + function Parameter(id) { + _super.call(this, id, 19 /* Parameter */); + this.isOptional = false; + } + Parameter.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + + Parameter.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.id.actualText); + }; + + Parameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.isOptional === ast.isOptional; + }; + return Parameter; + })(BoundDecl); + TypeScript.Parameter = Parameter; + + var FunctionDeclaration = (function (_super) { + __extends(FunctionDeclaration, _super); + function FunctionDeclaration(name, block, isConstructor, typeArguments, arguments, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.block = block; + this.isConstructor = isConstructor; + this.typeArguments = typeArguments; + this.arguments = arguments; + this.hint = null; + this._functionFlags = 0 /* None */; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.classDecl = null; + } + FunctionDeclaration.prototype.isDeclaration = function () { + return true; + }; + + FunctionDeclaration.prototype.getFunctionFlags = function () { + return this._functionFlags; + }; + + FunctionDeclaration.prototype.setFunctionFlags = function (flags) { + this._functionFlags = flags; + }; + + FunctionDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._functionFlags === ast._functionFlags && this.hint === ast.hint && this.variableArgList === ast.variableArgList && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && this.isConstructor === ast.isConstructor && structuralEquals(this.typeArguments, ast.typeArguments, includingPosition) && structuralEquals(this.arguments, ast.arguments, includingPosition); + }; + + FunctionDeclaration.prototype.shouldEmit = function () { + return !TypeScript.hasFlag(this.getFunctionFlags(), 128 /* Signature */) && !TypeScript.hasFlag(this.getFunctionFlags(), 8 /* Ambient */); + }; + + FunctionDeclaration.prototype.emit = function (emitter) { + emitter.emitFunction(this); + }; + + FunctionDeclaration.prototype.getNameText = function () { + if (this.name) { + return this.name.actualText; + } else { + return this.hint; + } + }; + + FunctionDeclaration.prototype.isMethod = function () { + return (this.getFunctionFlags() & 256 /* Method */) !== 0 /* None */; + }; + + FunctionDeclaration.prototype.isCallMember = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 512 /* CallMember */); + }; + FunctionDeclaration.prototype.isConstructMember = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 1024 /* ConstructMember */); + }; + FunctionDeclaration.prototype.isIndexerMember = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 4096 /* IndexerMember */); + }; + FunctionDeclaration.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FunctionDeclaration.prototype.isAccessor = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 32 /* GetAccessor */) || TypeScript.hasFlag(this.getFunctionFlags(), 64 /* SetAccessor */); + }; + FunctionDeclaration.prototype.isGetAccessor = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 32 /* GetAccessor */); + }; + FunctionDeclaration.prototype.isSetAccessor = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 64 /* SetAccessor */); + }; + FunctionDeclaration.prototype.isStatic = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 16 /* Static */); + }; + + FunctionDeclaration.prototype.isSignature = function () { + return (this.getFunctionFlags() & 128 /* Signature */) !== 0 /* None */; + }; + return FunctionDeclaration; + })(AST); + TypeScript.FunctionDeclaration = FunctionDeclaration; + + var Script = (function (_super) { + __extends(Script, _super); + function Script() { + _super.call(this, 2 /* Script */); + this.moduleElements = null; + this.referencedFiles = []; + this.requiresExtendsBlock = false; + this.isDeclareFile = false; + this.topLevelMod = null; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + } + Script.prototype.emit = function (emitter) { + if (!this.isDeclareFile) { + emitter.emitScriptElements(this, this.requiresExtendsBlock); + } + }; + + Script.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return Script; + })(AST); + TypeScript.Script = Script; + + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + } + NamedDeclaration.prototype.isDeclaration = function () { + return true; + }; + + NamedDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.members, ast.members, includingPosition); + }; + return NamedDeclaration; + })(AST); + TypeScript.NamedDeclaration = NamedDeclaration; + + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, endingToken) { + _super.call(this, 15 /* ModuleDeclaration */, name, members); + this.endingToken = endingToken; + this._moduleFlags = 0 /* None */; + this.amdDependencies = []; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.getModuleFlags = function () { + return this._moduleFlags; + }; + + ModuleDeclaration.prototype.setModuleFlags = function (flags) { + this._moduleFlags = flags; + }; + + ModuleDeclaration.prototype.structuralEquals = function (ast, includePosition) { + if (_super.prototype.structuralEquals.call(this, ast, includePosition)) { + return this._moduleFlags === ast._moduleFlags; + } + + return false; + }; + + ModuleDeclaration.prototype.isEnum = function () { + return TypeScript.hasFlag(this.getModuleFlags(), 128 /* IsEnum */); + }; + ModuleDeclaration.prototype.isWholeFile = function () { + return TypeScript.hasFlag(this.getModuleFlags(), 256 /* IsWholeFile */); + }; + + ModuleDeclaration.prototype.shouldEmit = function () { + if (TypeScript.hasFlag(this.getModuleFlags(), 8 /* Ambient */)) { + return false; + } + + if (TypeScript.hasFlag(this.getModuleFlags(), 128 /* IsEnum */)) { + return true; + } + + for (var i = 0, n = this.members.members.length; i < n; i++) { + var member = this.members.members[i]; + + if (member.nodeType === 15 /* ModuleDeclaration */) { + if ((member).shouldEmit()) { + return true; + } + } else if (member.nodeType !== 14 /* InterfaceDeclaration */) { + return true; + } + } + + return false; + }; + + ModuleDeclaration.prototype.emit = function (emitter) { + if (this.shouldEmit()) { + emitter.emitComments(this, true); + emitter.emitModule(this); + emitter.emitComments(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, typeParameters, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.typeParameters = typeParameters; + this.extendsList = extendsList; + this.implementsList = implementsList; + this._varFlags = 0 /* None */; + } + TypeDeclaration.prototype.getVarFlags = function () { + return this._varFlags; + }; + + TypeDeclaration.prototype.setVarFlags = function (flags) { + this._varFlags = flags; + }; + + TypeDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._varFlags === ast._varFlags && structuralEquals(this.typeParameters, ast.typeParameters, includingPosition) && structuralEquals(this.extendsList, ast.extendsList, includingPosition) && structuralEquals(this.implementsList, ast.implementsList, includingPosition); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, typeParameters, members, extendsList, implementsList) { + _super.call(this, 13 /* ClassDeclaration */, name, typeParameters, extendsList, implementsList, members); + this.constructorDecl = null; + this.endingToken = null; + } + ClassDeclaration.prototype.shouldEmit = function () { + return !TypeScript.hasFlag(this.getVarFlags(), 8 /* Ambient */); + }; + + ClassDeclaration.prototype.emit = function (emitter) { + emitter.emitClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, typeParameters, members, extendsList, implementsList) { + _super.call(this, 14 /* InterfaceDeclaration */, name, typeParameters, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.shouldEmit = function () { + return false; + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + } + Statement.prototype.isStatement = function () { + return true; + }; + + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + return Statement; + })(AST); + TypeScript.Statement = Statement; + + var ThrowStatement = (function (_super) { + __extends(ThrowStatement, _super); + function ThrowStatement(expression) { + _super.call(this, 95 /* ThrowStatement */); + this.expression = expression; + } + ThrowStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("throw "); + this.expression.emit(emitter); + emitter.writeToOutput(";"); + }; + + ThrowStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ThrowStatement; + })(Statement); + TypeScript.ThrowStatement = ThrowStatement; + + var ExpressionStatement = (function (_super) { + __extends(ExpressionStatement, _super); + function ExpressionStatement(expression) { + _super.call(this, 88 /* ExpressionStatement */); + this.expression = expression; + } + ExpressionStatement.prototype.emitWorker = function (emitter) { + this.expression.emit(emitter); + emitter.writeToOutput(";"); + }; + + ExpressionStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ExpressionStatement; + })(Statement); + TypeScript.ExpressionStatement = ExpressionStatement; + + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(identifier, statement) { + _super.call(this, 92 /* LabeledStatement */); + this.identifier = identifier; + this.statement = statement; + } + LabeledStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.identifier); + emitter.writeToOutput(this.identifier.actualText); + emitter.recordSourceMappingEnd(this.identifier); + emitter.writeLineToOutput(":"); + emitter.emitJavascript(this.statement, true); + }; + + LabeledStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + + var VariableDeclaration = (function (_super) { + __extends(VariableDeclaration, _super); + function VariableDeclaration(declarators) { + _super.call(this, 18 /* VariableDeclaration */); + this.declarators = declarators; + } + VariableDeclaration.prototype.emit = function (emitter) { + emitter.emitVariableDeclaration(this); + }; + + VariableDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declarators, ast.declarators, includingPosition); + }; + return VariableDeclaration; + })(AST); + TypeScript.VariableDeclaration = VariableDeclaration; + + var VariableStatement = (function (_super) { + __extends(VariableStatement, _super); + function VariableStatement(declaration) { + _super.call(this, 97 /* VariableStatement */); + this.declaration = declaration; + } + VariableStatement.prototype.shouldEmit = function () { + if (TypeScript.hasFlag(this.getFlags(), 32 /* EnumMapElement */)) { + return false; + } + + var varDecl = this.declaration.declarators.members[0]; + return !TypeScript.hasFlag(varDecl.getVarFlags(), 8 /* Ambient */) || varDecl.init !== null; + }; + + VariableStatement.prototype.emitWorker = function (emitter) { + if (TypeScript.hasFlag(this.getFlags(), 16 /* EnumElement */)) { + emitter.emitEnumElement(this.declaration.declarators.members[0]); + } else { + this.declaration.emit(emitter); + emitter.writeToOutput(";"); + } + }; + + VariableStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declaration, ast.declaration, includingPosition); + }; + return VariableStatement; + })(Statement); + TypeScript.VariableStatement = VariableStatement; + + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements) { + _super.call(this, 81 /* Block */); + this.statements = statements; + this.closeBraceSpan = null; + } + Block.prototype.emitWorker = function (emitter) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + if (this.statements) { + emitter.emitModuleElements(this.statements); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + }; + + Block.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return Block; + })(Statement); + TypeScript.Block = Block; + + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + + Jump.prototype.emitWorker = function (emitter) { + if (this.nodeType === 82 /* BreakStatement */) { + emitter.writeToOutput("break"); + } else { + emitter.writeToOutput("continue"); + } + if (this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.writeToOutput(";"); + }; + + Jump.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.target === ast.target; + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond, body) { + _super.call(this, 98 /* WhileStatement */); + this.cond = cond; + this.body = body; + } + WhileStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("while ("); + this.cond.emit(emitter); + emitter.writeToOutput(")"); + emitter.emitBlockOrStatement(this.body); + }; + + WhileStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + + var DoStatement = (function (_super) { + __extends(DoStatement, _super); + function DoStatement(body, cond) { + _super.call(this, 85 /* DoStatement */); + this.body = body; + this.cond = cond; + this.whileSpan = null; + } + DoStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("do"); + emitter.emitBlockOrStatement(this.body); + emitter.recordSourceMappingStart(this.whileSpan); + emitter.writeToOutput(" while"); + emitter.recordSourceMappingEnd(this.whileSpan); + emitter.writeToOutput('('); + this.cond.emit(emitter); + emitter.writeToOutput(")"); + emitter.writeToOutput(";"); + }; + + DoStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.body, ast.body, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition); + }; + return DoStatement; + })(Statement); + TypeScript.DoStatement = DoStatement; + + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond, thenBod, elseBod) { + _super.call(this, 91 /* IfStatement */); + this.cond = cond; + this.thenBod = thenBod; + this.elseBod = elseBod; + this.statement = new ASTSpan(); + } + IfStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if ("); + this.cond.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + + emitter.emitBlockOrStatement(this.thenBod); + + if (this.elseBod) { + if (this.elseBod.nodeType === 91 /* IfStatement */) { + emitter.writeToOutput(" else "); + this.elseBod.emit(emitter); + } else { + emitter.writeToOutput(" else"); + emitter.emitBlockOrStatement(this.elseBod); + } + } + }; + + IfStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition) && structuralEquals(this.thenBod, ast.thenBod, includingPosition) && structuralEquals(this.elseBod, ast.elseBod, includingPosition); + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement(returnExpression) { + _super.call(this, 93 /* ReturnStatement */); + this.returnExpression = returnExpression; + } + ReturnStatement.prototype.emitWorker = function (emitter) { + if (this.returnExpression) { + emitter.writeToOutput("return "); + this.returnExpression.emit(emitter); + emitter.writeToOutput(";"); + } else { + emitter.writeToOutput("return;"); + } + }; + + ReturnStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.returnExpression, ast.returnExpression, includingPosition); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj, body) { + _super.call(this, 89 /* ForInStatement */); + this.lval = lval; + this.obj = obj; + this.body = body; + this.statement = new ASTSpan(); + } + ForInStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for ("); + this.lval.emit(emitter); + emitter.writeToOutput(" in "); + this.obj.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitBlockOrStatement(this.body); + }; + + ForInStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.lval, ast.lval, includingPosition) && structuralEquals(this.obj, ast.obj, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init, cond, incr, body) { + _super.call(this, 90 /* ForStatement */); + this.init = init; + this.cond = cond; + this.incr = incr; + this.body = body; + } + ForStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("for ("); + if (this.init) { + if (this.init.nodeType !== 1 /* List */) { + this.init.emit(emitter); + } else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitCommaSeparatedList(this.init); + } + } + + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, false); + emitter.writeToOutput(")"); + emitter.emitBlockOrStatement(this.body); + }; + + ForStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.init, ast.init, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition) && structuralEquals(this.incr, ast.incr, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr, body) { + _super.call(this, 99 /* WithStatement */); + this.expr = expr; + this.body = body; + } + WithStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("with ("); + if (this.expr) { + this.expr.emit(emitter); + } + + emitter.writeToOutput(")"); + emitter.emitBlockOrStatement(this.body); + }; + + WithStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expr, ast.expr, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, 94 /* SwitchStatement */); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch ("); + this.val.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + + var lastEmittedNode = null; + for (var i = 0, n = this.caseList.members.length; i < n; i++) { + var caseExpr = this.caseList.members[i]; + + emitter.emitSpaceBetweenConstructs(lastEmittedNode, caseExpr); + emitter.emitJavascript(caseExpr, true); + + lastEmittedNode = caseExpr; + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + }; + + SwitchStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.caseList, ast.caseList, includingPosition) && structuralEquals(this.val, ast.val, includingPosition); + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + + var CaseClause = (function (_super) { + __extends(CaseClause, _super); + function CaseClause() { + _super.call(this, 100 /* CaseClause */); + this.expr = null; + this.colonSpan = new ASTSpan(); + } + CaseClause.prototype.emitWorker = function (emitter) { + if (this.expr) { + emitter.writeToOutput("case "); + this.expr.emit(emitter); + } else { + emitter.writeToOutput("default"); + } + emitter.recordSourceMappingStart(this.colonSpan); + emitter.writeToOutput(":"); + emitter.recordSourceMappingEnd(this.colonSpan); + + if (this.body.members.length === 1 && this.body.members[0].nodeType === 81 /* Block */) { + this.body.members[0].emit(emitter); + emitter.writeLineToOutput(""); + } else { + emitter.writeLineToOutput(""); + emitter.indenter.increaseIndent(); + this.body.emit(emitter); + emitter.indenter.decreaseIndent(); + } + }; + + CaseClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expr, ast.expr, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return CaseClause; + })(AST); + TypeScript.CaseClause = CaseClause; + + var TypeParameter = (function (_super) { + __extends(TypeParameter, _super); + function TypeParameter(name, constraint) { + _super.call(this, 9 /* TypeParameter */); + this.name = name; + this.constraint = constraint; + } + TypeParameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.constraint, ast.constraint, includingPosition); + }; + return TypeParameter; + })(AST); + TypeScript.TypeParameter = TypeParameter; + + var GenericType = (function (_super) { + __extends(GenericType, _super); + function GenericType(name, typeArguments) { + _super.call(this, 10 /* GenericType */); + this.name = name; + this.typeArguments = typeArguments; + } + GenericType.prototype.emit = function (emitter) { + this.name.emit(emitter); + }; + + GenericType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.typeArguments, ast.typeArguments, includingPosition); + }; + return GenericType; + })(AST); + TypeScript.GenericType = GenericType; + + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, 11 /* TypeRef */); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter) { + throw new Error("should not emit a type ref"); + }; + + TypeReference.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.term, ast.term, includingPosition) && this.arrayCount === ast.arrayCount; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + + var TryStatement = (function (_super) { + __extends(TryStatement, _super); + function TryStatement(tryBody, catchClause, finallyBody) { + _super.call(this, 96 /* TryStatement */); + this.tryBody = tryBody; + this.catchClause = catchClause; + this.finallyBody = finallyBody; + } + TryStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("try "); + this.tryBody.emit(emitter); + emitter.emitJavascript(this.catchClause, false); + + if (this.finallyBody) { + emitter.writeToOutput(" finally"); + this.finallyBody.emit(emitter); + } + }; + + TryStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.tryBody, ast.tryBody, includingPosition) && structuralEquals(this.catchClause, ast.catchClause, includingPosition) && structuralEquals(this.finallyBody, ast.finallyBody, includingPosition); + }; + return TryStatement; + })(Statement); + TypeScript.TryStatement = TryStatement; + + var CatchClause = (function (_super) { + __extends(CatchClause, _super); + function CatchClause(param, body) { + _super.call(this, 101 /* CatchClause */); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + } + CatchClause.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + this.param.id.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + this.body.emit(emitter); + }; + + CatchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.param, ast.param, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return CatchClause; + })(AST); + TypeScript.CatchClause = CatchClause; + + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, 84 /* DebuggerStatement */); + } + DebuggerStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("debugger;"); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; + + var OmittedExpression = (function (_super) { + __extends(OmittedExpression, _super); + function OmittedExpression() { + _super.call(this, 23 /* OmittedExpression */); + } + OmittedExpression.prototype.emitWorker = function (emitter) { + }; + + OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return OmittedExpression; + })(Expression); + TypeScript.OmittedExpression = OmittedExpression; + + var EmptyStatement = (function (_super) { + __extends(EmptyStatement, _super); + function EmptyStatement() { + _super.call(this, 86 /* EmptyStatement */); + } + EmptyStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(";"); + }; + + EmptyStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return EmptyStatement; + })(Statement); + TypeScript.EmptyStatement = EmptyStatement; + + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, 102 /* Comment */); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + this.docCommentText = null; + } + Comment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.minLine === ast.minLine && this.content === ast.content && this.isBlockComment === ast.isBlockComment && this.endsLine === ast.endsLine; + }; + + Comment.prototype.getText = function () { + if (this.text === null) { + if (this.isBlockComment) { + this.text = this.content.split("\n"); + for (var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } else { + this.text = [(this.content.replace(/^\s+|\s+$/g, ''))]; + } + } + + return this.text; + }; + + Comment.prototype.isDocComment = function () { + if (this.isBlockComment) { + return this.content.charAt(2) === "*" && this.content.charAt(3) !== "/"; + } + + return false; + }; + + Comment.prototype.getDocCommentTextValue = function () { + if (this.docCommentText === null) { + this.docCommentText = Comment.cleanJSDocComment(this.content); + } + + return this.docCommentText; + }; + + Comment.consumeLeadingSpace = function (line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if (maxSpacesToRemove !== undefined) { + endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); + } + + for (; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if (charCode !== 32 /* space */ && charCode !== 9 /* tab */) { + return startIndex; + } + } + + if (endIndex !== line.length) { + return endIndex; + } + + return -1; + }; + + Comment.isSpaceChar = function (line, index) { + var length = line.length; + if (index < length) { + var charCode = line.charCodeAt(index); + + return charCode === 32 /* space */ || charCode === 9 /* tab */; + } + + return index === length; + }; + + Comment.cleanDocCommentLine = function (line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); + if (nonSpaceIndex !== -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if (jsDocStyleComment && line.charAt(nonSpaceIndex) === '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + + if (nonSpaceIndex !== -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + + return { + minChar: nonSpaceIndex, + limChar: line.charAt(line.length - 1) === "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + + return null; + }; + + Comment.cleanJSDocComment = function (content, spacesToRemove) { + var docCommentLines = []; + content = content.replace("/**", ""); + if (content.length >= 2 && content.charAt(content.length - 1) === "/" && content.charAt(content.length - 2) === "*") { + content = content.substring(0, content.length - 2); + } + var lines = content.split("\n"); + var inParamTag = false; + for (var l = 0; l < lines.length; l++) { + var line = lines[l]; + var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); + if (!cleanLinePos) { + continue; + } + + var docCommentText = ""; + var prevPos = cleanLinePos.minChar; + for (var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + + if (line.indexOf("param", i + 1) === i + 1 && Comment.isSpaceChar(line, i + 6)) { + if (!wasInParamtag) { + docCommentText += line.substring(prevPos, i); + } + + prevPos = i; + inParamTag = true; + } else if (wasInParamtag) { + prevPos = i; + inParamTag = false; + } + } + + if (!inParamTag) { + docCommentText += line.substring(prevPos, cleanLinePos.limChar); + } + + var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); + if (newCleanPos) { + if (spacesToRemove === undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + + return docCommentLines.join("\n"); + }; + + Comment.getDocCommentText = function (comments) { + var docCommentText = []; + for (var c = 0; c < comments.length; c++) { + var commentText = comments[c].getDocCommentTextValue(); + if (commentText !== "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + + Comment.getParameterDocCommentText = function (param, fncDocComments) { + if (fncDocComments.length === 0 || !fncDocComments[0].isBlockComment) { + return ""; + } + + for (var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].content; + for (var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if (!Comment.isSpaceChar(commentContents, j)) { + continue; + } + + j = Comment.consumeLeadingSpace(commentContents, j); + if (j === -1) { + break; + } + + if (commentContents.charCodeAt(j) === 123 /* openBrace */) { + j++; + + var charCode = 0; + for (var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + break; + } else { + continue; + } + } + + if (charCode === 64 /* at */) { + break; + } + } + + if (j === commentContents.length) { + break; + } + + if (charCode === 64 /* at */) { + continue; + } + + j = Comment.consumeLeadingSpace(commentContents, j + 1); + if (j === -1) { + break; + } + } + + if (param !== commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { + continue; + } + + j = Comment.consumeLeadingSpace(commentContents, j + param.length); + if (j === -1) { + return ""; + } + + var endOfParam = commentContents.indexOf("@", j); + var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); + + var paramSpacesToRemove = undefined; + var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; + if (paramLineIndex !== 0) { + if (paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) === "\r") { + paramLineIndex++; + } + } + var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); + if (startSpaceRemovalIndex !== j && commentContents.charAt(startSpaceRemovalIndex) === "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + + return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + + return ""; + }; + return Comment; + })(AST); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if (preAst === undefined) { + preAst = ast; + } + if (this.options.goChildren) { + this.childrenWalkers[ast.nodeType](ast, parent, this); + } else { + this.options.goChildren = true; + } + + if (this.post) { + var postAst = this.post(preAst, parent, this); + if (postAst === undefined) { + postAst = preAst; + } + return postAst; + } else { + return preAst; + } + }; + return AstWalker; + })(); + + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if (!options) { + options = new AstWalkOptions(); + } + + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[0 /* None */] = ChildrenWalkers.walkNone; + this.childrenWalkers[86 /* EmptyStatement */] = ChildrenWalkers.walkNone; + this.childrenWalkers[23 /* OmittedExpression */] = ChildrenWalkers.walkNone; + this.childrenWalkers[3 /* TrueLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[4 /* FalseLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[29 /* ThisExpression */] = ChildrenWalkers.walkNone; + this.childrenWalkers[30 /* SuperExpression */] = ChildrenWalkers.walkNone; + this.childrenWalkers[5 /* StringLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[6 /* RegularExpressionLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[8 /* NullLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[21 /* ArrayLiteralExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[22 /* ObjectLiteralExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[24 /* VoidExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[25 /* CommaExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[26 /* PlusExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[27 /* NegateExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[28 /* DeleteExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[31 /* InExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[32 /* MemberAccessExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[33 /* InstanceOfExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[34 /* TypeOfExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[7 /* NumericLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[20 /* Name */] = ChildrenWalkers.walkNone; + this.childrenWalkers[9 /* TypeParameter */] = ChildrenWalkers.walkTypeParameterChildren; + this.childrenWalkers[10 /* GenericType */] = ChildrenWalkers.walkGenericTypeChildren; + this.childrenWalkers[11 /* TypeRef */] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[35 /* ElementAccessExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[36 /* InvocationExpression */] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[37 /* ObjectCreationExpression */] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[38 /* AssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[39 /* AddAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[40 /* SubtractAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[41 /* DivideAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[42 /* MultiplyAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[43 /* ModuloAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[44 /* AndAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[45 /* ExclusiveOrAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[46 /* OrAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[47 /* LeftShiftAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[48 /* SignedRightShiftAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[49 /* UnsignedRightShiftAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[50 /* ConditionalExpression */] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[51 /* LogicalOrExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[52 /* LogicalAndExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[53 /* BitwiseOrExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[54 /* BitwiseExclusiveOrExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[55 /* BitwiseAndExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[56 /* EqualsWithTypeConversionExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[57 /* NotEqualsWithTypeConversionExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[58 /* EqualsExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[59 /* NotEqualsExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[60 /* LessThanExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[61 /* LessThanOrEqualExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[62 /* GreaterThanExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[63 /* GreaterThanOrEqualExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[64 /* AddExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[65 /* SubtractExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[66 /* MultiplyExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[67 /* DivideExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[68 /* ModuloExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[69 /* LeftShiftExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[70 /* SignedRightShiftExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[71 /* UnsignedRightShiftExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[72 /* BitwiseNotExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[73 /* LogicalNotExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[74 /* PreIncrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[75 /* PreDecrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[76 /* PostIncrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[77 /* PostDecrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[78 /* CastExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[79 /* ParenthesizedExpression */] = ChildrenWalkers.walkParenthesizedExpressionChildren; + this.childrenWalkers[12 /* FunctionDeclaration */] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[80 /* Member */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[17 /* VariableDeclarator */] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[18 /* VariableDeclaration */] = ChildrenWalkers.walkVariableDeclarationChildren; + this.childrenWalkers[19 /* Parameter */] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[93 /* ReturnStatement */] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[82 /* BreakStatement */] = ChildrenWalkers.walkNone; + this.childrenWalkers[83 /* ContinueStatement */] = ChildrenWalkers.walkNone; + this.childrenWalkers[95 /* ThrowStatement */] = ChildrenWalkers.walkThrowStatementChildren; + this.childrenWalkers[90 /* ForStatement */] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[89 /* ForInStatement */] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[91 /* IfStatement */] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[98 /* WhileStatement */] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[85 /* DoStatement */] = ChildrenWalkers.walkDoStatementChildren; + this.childrenWalkers[81 /* Block */] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[100 /* CaseClause */] = ChildrenWalkers.walkCaseClauseChildren; + this.childrenWalkers[94 /* SwitchStatement */] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[96 /* TryStatement */] = ChildrenWalkers.walkTryStatementChildren; + this.childrenWalkers[101 /* CatchClause */] = ChildrenWalkers.walkCatchClauseChildren; + this.childrenWalkers[1 /* List */] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[2 /* Script */] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[13 /* ClassDeclaration */] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[14 /* InterfaceDeclaration */] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[15 /* ModuleDeclaration */] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[16 /* ImportDeclaration */] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[87 /* ExportAssignment */] = ChildrenWalkers.walkExportAssignmentChildren; + this.childrenWalkers[99 /* WithStatement */] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[88 /* ExpressionStatement */] = ChildrenWalkers.walkExpressionStatementChildren; + this.childrenWalkers[92 /* LabeledStatement */] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[97 /* VariableStatement */] = ChildrenWalkers.walkVariableStatementChildren; + this.childrenWalkers[102 /* Comment */] = ChildrenWalkers.walkNone; + this.childrenWalkers[84 /* DebuggerStatement */] = ChildrenWalkers.walkNone; + + for (var e in TypeScript.NodeType) { + if (TypeScript.NodeType.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.NodeType[e])) { + if (this.childrenWalkers[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + + var globalAstWalkerFactory; + + function getAstWalkerFactory() { + if (!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + + for (var i = 0; i < len; i++) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + + function walkThrowStatementChildren(preAst, parent, walker) { + if (preAst.expression) { + preAst.expression = walker.walk(preAst.expression, preAst); + } + } + ChildrenWalkers.walkThrowStatementChildren = walkThrowStatementChildren; + + function walkUnaryExpressionChildren(preAst, parent, walker) { + if (preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if (preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + + function walkParenthesizedExpressionChildren(preAst, parent, walker) { + if (preAst.expression) { + preAst.expression = walker.walk(preAst.expression, preAst); + } + } + ChildrenWalkers.walkParenthesizedExpressionChildren = walkParenthesizedExpressionChildren; + + function walkBinaryExpressionChildren(preAst, parent, walker) { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if (preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + + function walkTypeParameterChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + + if (preAst.constraint) { + preAst.constraint = walker.walk(preAst.constraint, preAst); + } + } + ChildrenWalkers.walkTypeParameterChildren = walkTypeParameterChildren; + + function walkGenericTypeChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + + if (preAst.typeArguments) { + preAst.typeArguments = walker.walk(preAst.typeArguments, preAst); + } + } + ChildrenWalkers.walkGenericTypeChildren = walkGenericTypeChildren; + + function walkTypeReferenceChildren(preAst, parent, walker) { + if (preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + + function walkCallExpressionChildren(preAst, parent, walker) { + preAst.target = walker.walk(preAst.target, preAst); + + if (preAst.typeArguments) { + preAst.typeArguments = walker.walk(preAst.typeArguments, preAst); + } + + if (preAst.arguments) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if (preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if (preAst.operand3) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + + function walkFuncDeclChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if (preAst.typeArguments) { + preAst.typeArguments = walker.walk(preAst.typeArguments, preAst); + } + if (preAst.arguments) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if (preAst.returnTypeAnnotation) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if (preAst.block) { + preAst.block = walker.walk(preAst.block, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + + function walkBoundDeclChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if (preAst.typeExpr) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + + function walkReturnStatementChildren(preAst, parent, walker) { + if (preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + + function walkForStatementChildren(preAst, parent, walker) { + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + + if (preAst.cond) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + + if (preAst.incr) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + preAst.obj = walker.walk(preAst.obj, preAst); + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.thenBod) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if (preAst.elseBod) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + + function walkDoStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoStatementChildren = walkDoStatementChildren; + + function walkBlockChildren(preAst, parent, walker) { + if (preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + + function walkVariableDeclarationChildren(preAst, parent, walker) { + if (preAst.declarators) { + preAst.declarators = walker.walk(preAst.declarators, preAst); + } + } + ChildrenWalkers.walkVariableDeclarationChildren = walkVariableDeclarationChildren; + + function walkCaseClauseChildren(preAst, parent, walker) { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseClauseChildren = walkCaseClauseChildren; + + function walkSwitchStatementChildren(preAst, parent, walker) { + if (preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + + if (preAst.caseList) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + + function walkTryStatementChildren(preAst, parent, walker) { + if (preAst.tryBody) { + preAst.tryBody = walker.walk(preAst.tryBody, preAst); + } + if (preAst.catchClause) { + preAst.catchClause = walker.walk(preAst.catchClause, preAst); + } + if (preAst.finallyBody) { + preAst.finallyBody = walker.walk(preAst.finallyBody, preAst); + } + } + ChildrenWalkers.walkTryStatementChildren = walkTryStatementChildren; + + function walkCatchClauseChildren(preAst, parent, walker) { + if (preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchClauseChildren = walkCatchClauseChildren; + + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if (preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + + if (preAst.typeParameters) { + preAst.typeParameters = walker.walk(preAst.typeParameters, preAst); + } + + if (preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + + if (preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + + function walkScriptChildren(preAst, parent, walker) { + if (preAst.moduleElements) { + preAst.moduleElements = walker.walk(preAst.moduleElements, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + + if (preAst.typeParameters) { + preAst.typeParameters = walker.walk(preAst.typeParameters, preAst); + } + + if (preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + + if (preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + + function walkImportDeclChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + + function walkExportAssignmentChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + } + ChildrenWalkers.walkExportAssignmentChildren = walkExportAssignmentChildren; + + function walkWithStatementChildren(preAst, parent, walker) { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + + function walkExpressionStatementChildren(preAst, parent, walker) { + preAst.expression = walker.walk(preAst.expression, preAst); + } + ChildrenWalkers.walkExpressionStatementChildren = walkExpressionStatementChildren; + + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.identifier = walker.walk(preAst.identifier, preAst); + preAst.statement = walker.walk(preAst.statement, preAst); + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + + function walkVariableStatementChildren(preAst, parent, walker) { + preAst.declaration = walker.walk(preAst.declaration, preAst); + } + ChildrenWalkers.walkVariableStatementChildren = walkVariableStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + + function AstWalkerCallback(pre, ast, callback) { + var nodeType = ast.nodeType; + var callbackString = TypeScript.NodeType[nodeType] + "Callback"; + if (callback[callbackString]) { + return callback[callbackString](pre, ast); + } + + if (callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + + return true; + } + })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); + var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function (items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + }; + + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + + while (this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + + AstPath.prototype.push = function (ast) { + while (this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + + AstPath.prototype.up = function () { + if (this.top <= -1) + throw new Error("Invalid call to 'up'"); + this.top--; + }; + + AstPath.prototype.down = function () { + if (this.top === this.ast.length - 1) + throw new Error("Invalid call to 'down'"); + this.top++; + }; + + AstPath.prototype.nodeType = function () { + if (this.ast() === null) + return 0 /* None */; + return this.ast().nodeType; + }; + + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + + AstPath.prototype.count = function () { + return this.top + 1; + }; + + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + + AstPath.prototype.isNameOfClass = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 13 /* ClassDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isNameOfInterface = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 14 /* InterfaceDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isNameOfArgument = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 19 /* Parameter */) && ((this.parent()).id === this.ast()); + }; + + AstPath.prototype.isNameOfVariable = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 17 /* VariableDeclarator */) && ((this.parent()).id === this.ast()); + }; + + AstPath.prototype.isNameOfModule = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 15 /* ModuleDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isNameOfFunction = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 12 /* FunctionDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === 12 /* FunctionDeclaration */ && (this.asts[this.top - 1]).block === this.asts[this.top - 0]; + }; + + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === 1 /* List */ && this.asts[this.top - 1].nodeType === 12 /* FunctionDeclaration */ && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + + AstPath.prototype.isTargetOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === 36 /* InvocationExpression */ && (this.asts[this.top - 1]).target === this.asts[this.top]; + }; + + AstPath.prototype.isTargetOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === 37 /* ObjectCreationExpression */ && (this.asts[this.top - 1]).target === this.asts[this.top]; + }; + + AstPath.prototype.isInClassImplementsList = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.parent().nodeType === 13 /* ClassDeclaration */) && (this.isMemberOfList((this.parent()).implementsList, this.ast())); + }; + + AstPath.prototype.isInInterfaceExtendsList = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.parent().nodeType === 14 /* InterfaceDeclaration */) && (this.isMemberOfList((this.parent()).extendsList, this.ast())); + }; + + AstPath.prototype.isMemberOfMemberAccessExpression = function () { + if (this.count() > 1 && this.parent().nodeType === 32 /* MemberAccessExpression */ && (this.parent()).operand2 === this.asts[this.top]) { + return true; + } + + return false; + }; + + AstPath.prototype.isCallExpression = function () { + return this.count() >= 1 && (this.asts[this.top - 0].nodeType === 36 /* InvocationExpression */ || this.asts[this.top - 0].nodeType === 37 /* ObjectCreationExpression */); + }; + + AstPath.prototype.isCallExpressionTarget = function () { + if (this.count() < 2) { + return false; + } + + var current = this.top; + + var nodeType = this.asts[current].nodeType; + if (nodeType === 29 /* ThisExpression */ || nodeType === 30 /* SuperExpression */ || nodeType === 20 /* Name */) { + current--; + } + + while (current >= 0) { + if (current < this.top && this.asts[current].nodeType === 32 /* MemberAccessExpression */ && (this.asts[current]).operand2 === this.asts[current + 1]) { + current--; + continue; + } + + break; + } + + return current < this.top && (this.asts[current].nodeType === 36 /* InvocationExpression */ || this.asts[current].nodeType === 37 /* ObjectCreationExpression */) && this.asts[current + 1] === (this.asts[current]).target; + }; + + AstPath.prototype.isDeclaration = function () { + if (this.ast() !== null) { + switch (this.ast().nodeType) { + case 13 /* ClassDeclaration */: + case 14 /* InterfaceDeclaration */: + case 15 /* ModuleDeclaration */: + case 12 /* FunctionDeclaration */: + case 17 /* VariableDeclarator */: + return true; + } + } + + return false; + }; + + AstPath.prototype.isMemberOfList = function (list, item) { + if (list && list.members) { + for (var i = 0, n = list.members.length; i < n; i++) { + if (list.members[i] === item) { + return true; + } + } + } + + return false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + + function isValidAstNode(ast) { + if (ast === null) + return false; + + if (ast.minChar === -1 || ast.limChar === -1) + return false; + + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + + (function (GetAstPathOptions) { + GetAstPathOptions[GetAstPathOptions["Default"] = 0] = "Default"; + GetAstPathOptions[GetAstPathOptions["EdgeInclusive"] = 1] = "EdgeInclusive"; + + GetAstPathOptions[GetAstPathOptions["DontPruneSearchBasedOnPosition"] = 1 << 1] = "DontPruneSearchBasedOnPosition"; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + + function getAstPathToPosition(script, pos, useTrailingTriviaAsLimChar, options) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof options === "undefined") { options = 0 /* Default */; } + var lookInComments = function (comments) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar + (useTrailingTriviaAsLimChar ? comments[i].trailingTriviaWidth : 0); + if (!comments[i].isBlockComment) { + limChar++; + } + if (pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + + var pre = function (cur, parent, walker) { + if (isValidAstNode(cur)) { + var inclusive = TypeScript.hasFlag(options, 1 /* EdgeInclusive */) || cur.nodeType === 20 /* Name */ || cur.nodeType === 32 /* MemberAccessExpression */ || cur.nodeType === 11 /* TypeRef */ || pos === script.limChar + script.trailingTriviaWidth; + + var minChar = cur.minChar; + var limChar = cur.limChar + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + var previous = ctx.path.ast(); + if (previous === null || (cur.minChar >= previous.minChar && (cur.limChar + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth : 0)) <= (previous.limChar + (useTrailingTriviaAsLimChar ? previous.trailingTriviaWidth : 0)))) { + ctx.path.push(cur); + } else { + } + } + + if (pos < limChar) { + lookInComments(cur.preComments); + } + if (pos >= minChar) { + lookInComments(cur.postComments); + } + + if (!TypeScript.hasFlag(options, 2 /* DontPruneSearchBasedOnPosition */)) { + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { + } + Base64Format.encode = function (inValue) { + if (inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + + Base64Format.decodeChar = function (inChar) { + if (inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + return Base64Format; + })(); + + var Base64VLQFormat = (function () { + function Base64VLQFormat() { + } + Base64VLQFormat.encode = function (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 + Base64Format.encode(currentDigit); + } while(inValue > 0); + + return encodedStr; + }; + + Base64VLQFormat.decode = function (inString) { + var result = 0; + var negative = false; + + var shift = 0; + for (var i = 0; i < inString.length; i++) { + var byte = Base64Format.decodeChar(inString[i]); + if (i === 0) { + if ((byte & 1) === 1) { + negative = true; + } + result = (byte >> 1) & 15; + } else { + result = result | ((byte & 31) << shift); + } + + shift += (i === 0) ? 4 : 5; + + if ((byte & 32) === 32) { + } else { + return { value: negative ? -(result) : result, rest: inString.substr(i + 1) }; + } + } + + throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceMapPosition = (function () { + function SourceMapPosition() { + } + return SourceMapPosition; + })(); + TypeScript.SourceMapPosition = SourceMapPosition; + + var SourceMapping = (function () { + function SourceMapping() { + this.start = new SourceMapPosition(); + this.end = new SourceMapPosition(); + this.nameIndex = -1; + this.childMappings = []; + } + return SourceMapping; + })(); + TypeScript.SourceMapping = SourceMapping; + + var SourceMapper = (function () { + function SourceMapper(tsFileName, jsFileName, sourceMapFileName, jsFile, sourceMapOut, emitFullPathOfSourceMap) { + this.sourceMapFileName = sourceMapFileName; + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.sourceMappings = []; + this.currentMappings = []; + this.names = []; + this.currentNameIndex = []; + this.currentMappings.push(this.sourceMappings); + + jsFileName = TypeScript.switchToForwardSlashes(jsFileName); + this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); + + var removalIndex = jsFileName.lastIndexOf(this.jsFileName); + var fixedPath = jsFileName.substring(0, removalIndex); + + if (emitFullPathOfSourceMap) { + if (jsFileName.indexOf("://") === -1) { + jsFileName = "file:///" + jsFileName; + } + this.jsFileName = jsFileName; + } + + this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); + } + SourceMapper.emitSourceMapping = function (allSourceMappers) { + var sourceMapper = allSourceMappers[0]; + sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); + + var sourceMapOut = sourceMapper.sourceMapOut; + var mappingsString = ""; + var tsFiles = []; + + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var namesList = []; + var namesCount = 0; + var emitComma = false; + + var recordedPosition = null; + for (var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { + sourceMapper = allSourceMappers[sourceMapperIndex]; + + var currentSourceIndex = tsFiles.length; + tsFiles.push(sourceMapper.tsFileName); + + if (sourceMapper.names.length > 0) { + namesList.push.apply(namesList, sourceMapper.names); + } + + var recordSourceMapping = function (mappedPosition, nameIndex) { + if (recordedPosition !== null && recordedPosition.emittedColumn === mappedPosition.emittedColumn && recordedPosition.emittedLine === mappedPosition.emittedLine) { + return; + } + + if (prevEmittedLine !== mappedPosition.emittedLine) { + while (prevEmittedLine < mappedPosition.emittedLine) { + prevEmittedColumn = 0; + mappingsString = mappingsString + ";"; + prevEmittedLine++; + } + emitComma = false; + } else if (emitComma) { + mappingsString = mappingsString + ","; + } + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); + prevSourceIndex = currentSourceIndex; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); + prevSourceLine = mappedPosition.sourceLine - 1; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); + prevSourceColumn = mappedPosition.sourceColumn; + + if (nameIndex >= 0) { + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); + prevNameIndex = namesCount + nameIndex; + } + + emitComma = true; + recordedPosition = mappedPosition; + }; + + var recordSourceMappingSiblings = function (sourceMappings) { + for (var i = 0; i < sourceMappings.length; i++) { + var sourceMapping = sourceMappings[i]; + recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); + recordSourceMappingSiblings(sourceMapping.childMappings); + recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); + } + }; + + recordSourceMappingSiblings(sourceMapper.sourceMappings); + namesCount = namesCount + sourceMapper.names.length; + } + + sourceMapOut.Write(JSON.stringify({ + version: 3, + file: sourceMapper.jsFileName, + sources: tsFiles, + names: namesList, + mappings: mappingsString + })); + + sourceMapOut.Close(); + }; + SourceMapper.MapFileExtension = ".map"; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer[EmitContainer["Prog"] = 0] = "Prog"; + EmitContainer[EmitContainer["Module"] = 1] = "Module"; + EmitContainer[EmitContainer["DynamicModule"] = 2] = "DynamicModule"; + EmitContainer[EmitContainer["Class"] = 3] = "Class"; + EmitContainer[EmitContainer["Constructor"] = 4] = "Constructor"; + EmitContainer[EmitContainer["Function"] = 5] = "Function"; + EmitContainer[EmitContainer["Args"] = 6] = "Args"; + EmitContainer[EmitContainer["Interface"] = 7] = "Interface"; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.container = 0 /* Prog */; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + + var EmitOptions = (function () { + function EmitOptions(compilationSettings) { + this.compilationSettings = compilationSettings; + this.ioHost = null; + this.outputMany = true; + this.commonDirectoryPath = ""; + } + EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { + if (this.outputMany) { + var updatedFileName = fileName; + if (this.compilationSettings.outputOption !== "") { + updatedFileName = fileName.replace(this.commonDirectoryPath, ""); + updatedFileName = this.compilationSettings.outputOption + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(this.compilationSettings.outputOption, true); + } + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + Indenter.prototype.increaseIndent = function () { + this.indentAmt += Indenter.indentStep; + }; + + Indenter.prototype.decreaseIndent = function () { + this.indentAmt -= Indenter.indentStep; + }; + + Indenter.prototype.getIndent = function () { + var indentString = Indenter.indentStrings[this.indentAmt]; + if (indentString === undefined) { + indentString = ""; + for (var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { + indentString += Indenter.indentStepString; + } + Indenter.indentStrings[this.indentAmt] = indentString; + } + return indentString; + }; + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + + var Emitter = (function () { + function Emitter(emittingFileName, outfile, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.thisFunctionDeclaration = null; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.modAliasId = null; + this.firstModAlias = null; + this.allSourceMappers = []; + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.varListCountStack = [0]; + this.pullTypeChecker = null; + this.declStack = []; + this.resolvingContext = new TypeScript.PullTypeResolutionContext(); + this.exportAssignmentIdentifier = null; + this.document = null; + TypeScript.globalSemanticInfoChain = semanticInfoChain; + TypeScript.globalBinder.semanticInfoChain = semanticInfoChain; + this.pullTypeChecker = new TypeScript.PullTypeChecker(emitOptions.compilationSettings, semanticInfoChain); + } + Emitter.prototype.pushDecl = function (decl) { + if (decl) { + this.declStack[this.declStack.length] = decl; + } + }; + + Emitter.prototype.popDecl = function (decl) { + if (decl) { + this.declStack.length--; + } + }; + + Emitter.prototype.getEnclosingDecl = function () { + var declStackLen = this.declStack.length; + var enclosingDecl = declStackLen > 0 ? this.declStack[declStackLen - 1] : null; + return enclosingDecl; + }; + + Emitter.prototype.setTypeCheckerUnit = function (fileName) { + if (!this.pullTypeChecker.resolver) { + this.pullTypeChecker.setUnit(fileName); + return; + } + + this.pullTypeChecker.resolver.setUnitPath(fileName); + }; + + Emitter.prototype.setExportAssignmentIdentifier = function (id) { + this.exportAssignmentIdentifier = id; + }; + + Emitter.prototype.getExportAssignmentIdentifier = function () { + return this.exportAssignmentIdentifier; + }; + + Emitter.prototype.setDocument = function (document) { + this.document = document; + }; + + Emitter.prototype.importStatementShouldBeEmitted = function (importDeclAST, unitPath) { + if (!importDeclAST.isDynamicImport) { + return true; + } + + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST, this.document.fileName); + var pullSymbol = importDecl.getSymbol(); + return pullSymbol.getIsUsedAsValue(); + }; + + Emitter.prototype.setSourceMappings = function (mapper) { + this.allSourceMappers.push(mapper); + this.sourceMapper = mapper; + }; + + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + + this.emitState.column += s.length; + }; + + Emitter.prototype.writeToOutputTrimmable = function (s) { + if (this.emitOptions.compilationSettings.minWhitespace) { + s = s.replace(/[\s]*/g, ''); + } + this.writeToOutput(s); + }; + + Emitter.prototype.writeLineToOutput = function (s) { + if (this.emitOptions.compilationSettings.minWhitespace) { + this.writeToOutput(s); + var c = s.charCodeAt(s.length - 1); + if (!((c === 32 /* space */) || (c === 59 /* semicolon */) || (c === 91 /* openBracket */))) { + this.writeToOutput(' '); + } + } else { + this.outfile.WriteLine(s); + this.emitState.column = 0; + this.emitState.line++; + } + }; + + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.recordSourceMappingStart(ast); + this.writeToOutput(this.captureThisStmtString); + this.recordSourceMappingEnd(ast); + this.writeLineToOutput(""); + }; + + Emitter.prototype.setInVarBlock = function (count) { + this.varListCountStack[this.varListCountStack.length - 1] = count; + }; + + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + + Emitter.prototype.getIndentString = function () { + if (this.emitOptions.compilationSettings.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + + Emitter.prototype.emitCommentInPlace = function (comment) { + var text = comment.getText(); + var hadNewLine = false; + + if (comment.isBlockComment) { + if (this.emitState.column === 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + + if (text.length > 1 || comment.endsLine) { + for (var i = 1; i < text.length; i++) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput(text[i]); + } + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } else { + this.recordSourceMappingEnd(comment); + } + } else { + if (this.emitState.column === 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } + + if (hadNewLine) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + }; + + Emitter.prototype.emitComments = function (ast, pre) { + var comments = pre ? ast.preComments : ast.postComments; + + if (this.emitOptions.compilationSettings.emitComments && comments && comments.length !== 0) { + for (var i = 0; i < comments.length; i++) { + this.emitCommentInPlace(comments[i]); + } + } + }; + + Emitter.prototype.emitObjectLiteral = function (objectLiteral) { + var useNewLines = !TypeScript.hasFlag(objectLiteral.getFlags(), 2 /* SingleLine */); + + this.writeToOutput("{"); + var list = objectLiteral.operand; + if (list.members.length > 0) { + if (useNewLines) { + this.writeLineToOutput(""); + } else { + this.writeToOutput(" "); + } + + this.indenter.increaseIndent(); + this.emitCommaSeparatedList(list, useNewLines); + this.indenter.decreaseIndent(); + if (useNewLines) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + } + this.writeToOutput("}"); + }; + + Emitter.prototype.emitArrayLiteral = function (arrayLiteral) { + var useNewLines = !TypeScript.hasFlag(arrayLiteral.getFlags(), 2 /* SingleLine */); + + this.writeToOutput("["); + var list = arrayLiteral.operand; + if (list.members.length > 0) { + if (useNewLines) { + this.writeLineToOutput(""); + } + + this.indenter.increaseIndent(); + this.emitCommaSeparatedList(list, useNewLines); + this.indenter.decreaseIndent(); + if (useNewLines) { + this.emitIndent(); + } + } + this.writeToOutput("]"); + }; + + Emitter.prototype.emitNew = function (target, args) { + this.writeToOutput("new "); + if (target.nodeType === 11 /* TypeRef */) { + var typeRef = target; + if (typeRef.arrayCount) { + this.writeToOutput("Array()"); + } else { + typeRef.term.emit(this); + this.writeToOutput("()"); + } + } else { + target.emit(this); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitCommaSeparatedList(args); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + + Emitter.prototype.getVarDeclFromIdentifier = function (boundDeclInfo) { + TypeScript.CompilerDiagnostics.assert(boundDeclInfo.boundDecl && boundDeclInfo.boundDecl.init && boundDeclInfo.boundDecl.init.nodeType === 20 /* Name */, "The init expression of bound declaration when emitting as constant has to be indentifier"); + + var init = boundDeclInfo.boundDecl.init; + var ident = init; + + this.setTypeCheckerUnit(this.document.fileName); + var pullSymbol = this.resolvingContext.resolvingTypeReference ? this.pullTypeChecker.resolver.resolveTypeNameExpression(ident, boundDeclInfo.pullDecl.getParentDecl(), this.resolvingContext).symbol : this.pullTypeChecker.resolver.resolveNameExpression(ident, boundDeclInfo.pullDecl.getParentDecl(), this.resolvingContext).symbol; + if (pullSymbol) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + var ast = this.semanticInfoChain.getASTForDecl(pullDecl); + if (ast && ast.nodeType === 17 /* VariableDeclarator */) { + return { boundDecl: ast, pullDecl: pullDecl }; + } + } + } + + return null; + }; + + Emitter.prototype.getConstantValue = function (boundDeclInfo) { + var init = boundDeclInfo.boundDecl.init; + if (init) { + if (init.nodeType === 7 /* NumericLiteral */) { + var numLit = init; + return numLit.value; + } else if (init.nodeType === 69 /* LeftShiftExpression */) { + var binop = init; + if (binop.operand1.nodeType === 7 /* NumericLiteral */ && binop.operand2.nodeType === 7 /* NumericLiteral */) { + return (binop.operand1).value << (binop.operand2).value; + } + } else if (init.nodeType === 20 /* Name */) { + var varDeclInfo = this.getVarDeclFromIdentifier(boundDeclInfo); + if (varDeclInfo) { + return this.getConstantValue(varDeclInfo); + } + } + } + + return null; + }; + + Emitter.prototype.getConstantDecl = function (dotExpr) { + this.setTypeCheckerUnit(this.document.fileName); + var pullSymbol = this.pullTypeChecker.resolver.resolveDottedNameExpression(dotExpr, this.getEnclosingDecl(), this.resolvingContext).symbol; + if (pullSymbol && pullSymbol.hasFlag(524288 /* Constant */)) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + var ast = this.semanticInfoChain.getASTForDecl(pullDecl); + if (ast && ast.nodeType === 17 /* VariableDeclarator */) { + return { boundDecl: ast, pullDecl: pullDecl }; + } + } + } + + return null; + }; + + Emitter.prototype.tryEmitConstant = function (dotExpr) { + if (!this.emitOptions.compilationSettings.propagateConstants) { + return false; + } + var propertyName = dotExpr.operand2; + var boundDeclInfo = this.getConstantDecl(dotExpr); + if (boundDeclInfo) { + var value = this.getConstantValue(boundDeclInfo); + if (value !== null) { + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.actualText; + comment += " */"; + this.writeToOutput(comment); + return true; + } + } + + return false; + }; + + Emitter.prototype.emitCall = function (callNode, target, args) { + if (!this.emitSuperCall(callNode)) { + if (target.nodeType === 12 /* FunctionDeclaration */) { + this.writeToOutput("("); + } + if (callNode.target.nodeType === 30 /* SuperExpression */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, false); + } + if (target.nodeType === 12 /* FunctionDeclaration */) { + this.writeToOutput(")"); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if (callNode.target.nodeType === 30 /* SuperExpression */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("this"); + if (args && args.members.length) { + this.writeToOutput(", "); + } + } + this.emitCommaSeparatedList(args); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + + Emitter.prototype.emitInnerFunction = function (funcDecl, printName, includePreComments) { + if (typeof includePreComments === "undefined") { includePreComments = true; } + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl, this.document.fileName); + this.pushDecl(pullDecl); + + var shouldParenthesize = false; + + if (includePreComments) { + this.emitComments(funcDecl, true); + } + + if (shouldParenthesize) { + this.writeToOutput("("); + } + this.recordSourceMappingStart(funcDecl); + var accessorSymbol = funcDecl.isAccessor() ? TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain, this.document.fileName) : null; + var container = accessorSymbol ? accessorSymbol.getContainer() : null; + var containerKind = container ? container.getKind() : 0 /* None */; + if (!(funcDecl.isAccessor() && containerKind !== 8 /* Class */ && containerKind !== 33554432 /* ConstructorType */)) { + this.writeToOutput("function "); + } + + if (funcDecl.isConstructor) { + this.writeToOutput(this.thisClassNode.name.actualText); + } + + if (printName) { + var id = funcDecl.getNameText(); + if (id && !funcDecl.isAccessor()) { + if (funcDecl.name) { + this.recordSourceMappingStart(funcDecl.name); + } + this.writeToOutput(id); + if (funcDecl.name) { + this.recordSourceMappingEnd(funcDecl.name); + } + } + } + + this.writeToOutput("("); + var argsLen = 0; + if (funcDecl.arguments) { + this.emitComments(funcDecl.arguments, true); + + var tempContainer = this.setContainer(6 /* Args */); + argsLen = funcDecl.arguments.members.length; + var printLen = argsLen; + if (funcDecl.variableArgList) { + printLen--; + } + for (var i = 0; i < printLen; i++) { + var arg = funcDecl.arguments.members[i]; + arg.emit(this); + + if (i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + + this.emitComments(funcDecl.arguments, false); + } + this.writeLineToOutput(") {"); + + if (funcDecl.isConstructor) { + this.recordSourceMappingNameStart("constructor"); + } else if (funcDecl.isGetAccessor()) { + this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); + } else if (funcDecl.isSetAccessor()) { + this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); + } else { + this.recordSourceMappingNameStart(funcDecl.getNameText()); + } + this.indenter.increaseIndent(); + + this.emitDefaultValueAssignments(funcDecl); + this.emitRestParameterInitializer(funcDecl); + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + if (funcDecl.isConstructor) { + this.emitConstructorStatements(funcDecl); + } else { + this.emitModuleElements(funcDecl.block.statements); + } + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(funcDecl.block.closeBraceSpan); + this.writeToOutput("}"); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl.block.closeBraceSpan); + this.recordSourceMappingEnd(funcDecl); + + if (shouldParenthesize) { + this.writeToOutput(")"); + } + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitDefaultValueAssignments = function (funcDecl) { + var n = funcDecl.arguments.members.length; + if (funcDecl.variableArgList) { + n--; + } + + for (var i = 0; i < n; i++) { + var arg = funcDecl.arguments.members[i]; + if (arg.init) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.emitJavascript(arg.init, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + } + }; + + Emitter.prototype.emitRestParameterInitializer = function (funcDecl) { + if (funcDecl.variableArgList) { + var n = funcDecl.arguments.members.length; + var lastArg = funcDecl.arguments.members[n - 1]; + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.recordSourceMappingStart(lastArg.id); + this.writeToOutput(lastArg.id.actualText); + this.recordSourceMappingEnd(lastArg.id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var _i = 0;"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput(" "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i < (arguments.length - " + (n - 1) + ")"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput("; "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i++"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + + this.recordSourceMappingStart(lastArg); + this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (n - 1) + "];"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + }; + + Emitter.prototype.getImportDecls = function (fileName) { + var semanticInfo = this.semanticInfoChain.getUnit(this.document.fileName); + var result = []; + + var queue = semanticInfo.getTopLevelDecls(); + + while (queue.length > 0) { + var decl = queue.shift(); + + if (decl.getKind() & 256 /* TypeAlias */) { + var importStatementAST = semanticInfo.getASTForDecl(decl); + if (importStatementAST.alias.nodeType === 20 /* Name */) { + var text = (importStatementAST.alias).actualText; + if (TypeScript.isQuoted(text)) { + var symbol = decl.getSymbol(); + var typeSymbol = symbol && symbol.getType(); + if (typeSymbol && typeSymbol !== this.semanticInfoChain.anyTypeSymbol && !typeSymbol.isError()) { + result.push(decl); + } + } + } + } + + queue = queue.concat(decl.getChildDecls()); + } + + return result; + }; + + Emitter.prototype.getModuleImportAndDependencyList = function (moduleDecl) { + var importList = ""; + var dependencyList = ""; + + var semanticInfo = this.semanticInfoChain.getUnit(this.document.fileName); + var importDecls = this.getImportDecls(this.document.fileName); + + if (importDecls.length) { + for (var i = 0; i < importDecls.length; i++) { + var importStatementDecl = importDecls[i]; + var importStatementSymbol = importStatementDecl.getSymbol(); + var importStatementAST = semanticInfo.getASTForDecl(importStatementDecl); + + if (importStatementSymbol.getIsUsedAsValue()) { + if (i <= importDecls.length - 1) { + dependencyList += ", "; + importList += ", "; + } + + importList += "__" + importStatementDecl.getName() + "__"; + dependencyList += importStatementAST.firstAliasedModToString(); + } + } + } + + for (var i = 0; i < moduleDecl.amdDependencies.length; i++) { + dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; + } + + return { + importList: importList, + dependencyList: dependencyList + }; + }; + + Emitter.prototype.shouldCaptureThis = function (ast) { + if (ast.nodeType === 2 /* Script */) { + var scriptDecl = this.semanticInfoChain.getUnit(this.document.fileName).getTopLevelDecls()[0]; + return (scriptDecl.getFlags() & 262144 /* MustCaptureThis */) === 262144 /* MustCaptureThis */; + } + + var decl = this.semanticInfoChain.getDeclForAST(ast, this.document.fileName); + if (decl) { + return (decl.getFlags() & 262144 /* MustCaptureThis */) === 262144 /* MustCaptureThis */; + } + + return false; + }; + + Emitter.prototype.emitModule = function (moduleDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl, this.document.fileName); + this.pushDecl(pullDecl); + + var modName = moduleDecl.name.actualText; + if (TypeScript.isTSFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 3)); + } + + var isDynamicMod = TypeScript.hasFlag(moduleDecl.getModuleFlags(), 512 /* IsDynamic */); + var prevOutFile = this.outfile; + var prevOutFileName = this.emittingFileName; + var prevAllSourceMappers = this.allSourceMappers; + var prevSourceMapper = this.sourceMapper; + var prevColumn = this.emitState.column; + var prevLine = this.emitState.line; + var temp = this.setContainer(1 /* Module */); + var svModuleName = this.moduleName; + var isExported = TypeScript.hasFlag(moduleDecl.getModuleFlags(), 1 /* Exported */); + var isWholeFile = TypeScript.hasFlag(moduleDecl.getModuleFlags(), 256 /* IsWholeFile */); + this.moduleName = moduleDecl.name.actualText; + + if (isDynamicMod) { + this.setExportAssignmentIdentifier(null); + this.setContainer(2 /* DynamicModule */); + + this.recordSourceMappingStart(moduleDecl); + if (this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + + var importAndDependencyList = this.getModuleImportAndDependencyList(moduleDecl); + importList += importAndDependencyList.importList; + dependencyList += importAndDependencyList.dependencyList + "]"; + + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } + } else { + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(") {"); + } + + if (!isWholeFile) { + this.recordSourceMappingNameStart(this.moduleName); + } + + if (!isDynamicMod || this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + this.indenter.increaseIndent(); + } + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + this.emitModuleElements(moduleDecl.members); + if (!isDynamicMod || this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + this.indenter.decreaseIndent(); + } + this.emitIndent(); + + if (isDynamicMod) { + var exportAssignmentIdentifier = this.getExportAssignmentIdentifier(); + var exportAssignmentValueSymbol = (pullDecl.getSymbol()).getExportAssignedValueSymbol(); + + if (this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.getKind() & TypeScript.PullElementKind.SomeTypeReference)) { + this.indenter.increaseIndent(); + this.emitIndent(); + this.writeLineToOutput("return " + exportAssignmentIdentifier + ";"); + this.indenter.decreaseIndent(); + } + this.writeToOutput("});"); + } else if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.getKind() & TypeScript.PullElementKind.SomeTypeReference)) { + this.emitIndent(); + this.writeLineToOutput("module.exports = " + exportAssignmentIdentifier + ";"); + } + + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl); + + if (this.outfile !== prevOutFile) { + this.emitSourceMapsAndClose(); + if (prevSourceMapper !== null) { + this.allSourceMappers = prevAllSourceMappers; + this.sourceMapper = prevSourceMapper; + this.emitState.column = prevColumn; + this.emitState.line = prevLine; + } + this.outfile = prevOutFile; + this.emittingFileName = prevOutFileName; + } + } else { + var parentIsDynamic = temp === 2 /* DynamicModule */; + this.recordSourceMappingStart(moduleDecl.endingToken); + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitEnumElement = function (varDecl) { + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(this.moduleName); + this.writeToOutput('["'); + this.writeToOutput(varDecl.id.text); + this.writeToOutput('"] = '); + varDecl.init.emit(this); + this.writeToOutput('] = "'); + this.writeToOutput(varDecl.id.text); + this.writeToOutput('";'); + }; + + Emitter.prototype.emitIndex = function (operand1, operand2) { + operand1.emit(this); + this.writeToOutput("["); + operand2.emit(this); + this.writeToOutput("]"); + }; + + Emitter.prototype.emitFunction = function (funcDecl) { + if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 128 /* Signature */)) { + return; + } + var temp; + var tempFnc = this.thisFunctionDeclaration; + this.thisFunctionDeclaration = funcDecl; + + if (funcDecl.isConstructor) { + temp = this.setContainer(4 /* Constructor */); + } else { + temp = this.setContainer(5 /* Function */); + } + + var funcName = funcDecl.getNameText(); + + if (((temp !== 4 /* Constructor */) || ((funcDecl.getFunctionFlags() & 256 /* Method */) === 0 /* None */))) { + this.recordSourceMappingStart(funcDecl); + this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing())); + } + this.setContainer(temp); + this.thisFunctionDeclaration = tempFnc; + + if (!TypeScript.hasFlag(funcDecl.getFunctionFlags(), 128 /* Signature */)) { + if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 16 /* Static */)) { + if (this.thisClassNode) { + this.writeLineToOutput(""); + if (funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } else if ((this.emitState.container === 1 /* Module */ || this.emitState.container === 2 /* DynamicModule */) && TypeScript.hasFlag(funcDecl.getFunctionFlags(), 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = this.emitState.container === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + if (varDecl.init) { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, false); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + }; + + Emitter.prototype.varListCount = function () { + return this.varListCountStack[this.varListCountStack.length - 1]; + }; + + Emitter.prototype.emitVarDeclVar = function () { + if (this.varListCount() >= 0) { + this.writeToOutput("var "); + this.setInVarBlock(-this.varListCount()); + } + return true; + }; + + Emitter.prototype.onEmitVar = function () { + if (this.varListCount() > 0) { + this.setInVarBlock(this.varListCount() - 1); + } else if (this.varListCount() < 0) { + this.setInVarBlock(this.varListCount() + 1); + } + }; + + Emitter.prototype.emitVariableDeclaration = function (declaration) { + var varDecl = declaration.declarators.members[0]; + + var symbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(varDecl, this.document.fileName); + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.getKind() : 0 /* None */; + var inClass = parentKind === 8 /* Class */; + + this.emitComments(declaration, true); + this.recordSourceMappingStart(declaration); + this.setInVarBlock(declaration.declarators.members.length); + + var isAmbientWithoutInit = TypeScript.hasFlag(varDecl.getVarFlags(), 8 /* Ambient */) && varDecl.init === null; + if (!isAmbientWithoutInit) { + for (var i = 0, n = declaration.declarators.members.length; i < n; i++) { + var declarator = declaration.declarators.members[i]; + + if (i > 0) { + if (inClass) { + this.writeToOutputTrimmable(";"); + } else { + this.writeToOutputTrimmable(", "); + } + } + + declarator.emit(this); + } + } + + this.recordSourceMappingEnd(declaration); + this.emitComments(declaration, false); + }; + + Emitter.prototype.emitVariableDeclarator = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl, this.document.fileName); + this.pushDecl(pullDecl); + if ((varDecl.getVarFlags() & 8 /* Ambient */) === 8 /* Ambient */) { + this.emitAmbientVarDecl(varDecl); + this.onEmitVar(); + } else { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + + var symbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(varDecl, this.document.fileName); + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.getKind() : 0 /* None */; + var associatedParentSymbol = parentSymbol ? parentSymbol.getAssociatedContainerType() : null; + var associatedParentSymbolKind = associatedParentSymbol ? associatedParentSymbol.getKind() : 0 /* None */; + if (parentKind === 8 /* Class */) { + if (this.emitState.container !== 6 /* Args */) { + if (varDecl.isStatic()) { + this.writeToOutput(parentSymbol.getName() + "."); + } else { + this.writeToOutput("this."); + } + } + } else if (parentKind === 64 /* Enum */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 64 /* Enum */) { + if (!varDecl.isExported() && !varDecl.isProperty()) { + this.emitVarDeclVar(); + } else { + if (this.emitState.container === 2 /* DynamicModule */) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + this.emitVarDeclVar(); + } + + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + var hasInitializer = (varDecl.init !== null); + if (hasInitializer) { + this.writeToOutputTrimmable(" = "); + + this.varListCountStack.push(0); + varDecl.init.emit(this); + this.varListCountStack.pop(); + } + + if (parentKind === 8 /* Class */) { + if (this.emitState.container !== 6 /* Args */) { + this.writeToOutput(";"); + } + } + + this.onEmitVar(); + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + this.popDecl(pullDecl); + }; + + Emitter.prototype.symbolIsUsedInItsEnclosingContainer = function (symbol, dynamic) { + if (typeof dynamic === "undefined") { dynamic = false; } + var symDecls = symbol.getDeclarations(); + + if (symDecls.length) { + var enclosingDecl = this.getEnclosingDecl(); + if (enclosingDecl) { + var parentDecl = symDecls[0].getParentDecl(); + if (parentDecl) { + var symbolDeclarationEnclosingContainer = parentDecl; + var enclosingContainer = enclosingDecl; + + while (symbolDeclarationEnclosingContainer) { + if (symbolDeclarationEnclosingContainer.getKind() === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + symbolDeclarationEnclosingContainer = symbolDeclarationEnclosingContainer.getParentDecl(); + } + + if (symbolDeclarationEnclosingContainer) { + while (enclosingContainer) { + if (enclosingContainer.getKind() === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + + enclosingContainer = enclosingContainer.getParentDecl(); + } + } + + if (symbolDeclarationEnclosingContainer && enclosingContainer) { + var same = symbolDeclarationEnclosingContainer === enclosingContainer; + + if (!same && symbol.hasFlag(32768 /* InitializedModule */)) { + same = symbolDeclarationEnclosingContainer === enclosingContainer.getParentDecl(); + } + + return same; + } + } + } + } + + return false; + }; + + Emitter.prototype.emitName = function (name, addThis) { + this.emitComments(name, true); + this.recordSourceMappingStart(name); + if (!name.isMissing()) { + this.setTypeCheckerUnit(this.document.fileName); + var pullSymbolAndDiagnostics = this.resolvingContext.resolvingTypeReference ? this.pullTypeChecker.resolver.resolveTypeNameExpression(name, this.getEnclosingDecl(), this.resolvingContext) : this.pullTypeChecker.resolver.resolveNameExpression(name, this.getEnclosingDecl(), this.resolvingContext); + var pullSymbol = pullSymbolAndDiagnostics.symbol; + var pullSymbolAlias = pullSymbolAndDiagnostics.symbolAlias; + var pullSymbolKind = pullSymbol.getKind(); + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() == this.getEnclosingDecl()); + if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { + var pullSymbolContainer = pullSymbol.getContainer(); + + if (pullSymbolContainer) { + var pullSymbolContainerKind = pullSymbolContainer.getKind(); + + if (pullSymbolContainerKind === 8 /* Class */) { + if (pullSymbol.hasFlag(16 /* Static */)) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } else if (pullSymbolKind === 4096 /* Property */) { + this.emitThis(); + this.writeToOutput("."); + } + } else if (pullSymbolContainerKind === 4 /* Container */ || pullSymbolContainerKind === 64 /* Enum */ || pullSymbolContainer.hasFlag(32768 /* InitializedModule */ | 131072 /* InitializedEnum */)) { + if (pullSymbolKind === 4096 /* Property */ || pullSymbolKind === 67108864 /* EnumMember */) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } else if (pullSymbol.hasFlag(1 /* Exported */) && pullSymbolKind === 1024 /* Variable */ && !pullSymbol.hasFlag(32768 /* InitializedModule */ | 131072 /* InitializedEnum */)) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } else if (pullSymbol.hasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(pullSymbol)) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } + } else if (pullSymbolContainerKind === 32 /* DynamicModule */ || pullSymbolContainer.hasFlag(65536 /* InitializedDynamicModule */)) { + if (pullSymbolKind === 4096 /* Property */) { + this.writeToOutput("exports."); + } else if (pullSymbol.hasFlag(1 /* Exported */) && !isLocalAlias && !pullSymbol.hasFlag(TypeScript.PullElementFlags.ImplicitVariable) && pullSymbol.getKind() !== 32768 /* ConstructorMethod */ && pullSymbol.getKind() !== 8 /* Class */ && pullSymbol.getKind() !== 64 /* Enum */) { + this.writeToOutput("exports."); + } + } else if (pullSymbolKind === 4096 /* Property */) { + if (pullSymbolContainer.getKind() === 8 /* Class */) { + this.emitThis(); + this.writeToOutput("."); + } + } else { + var pullDecls = pullSymbol.getDeclarations(); + var emitContainerName = true; + for (var i = 0; i < pullDecls.length; i++) { + if (pullDecls[i].getScriptName() === this.document.fileName) { + emitContainerName = false; + } + } + if (emitContainerName) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } + } + } + } + + if (pullSymbol && pullSymbolKind === 32 /* DynamicModule */) { + if (this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + this.writeToOutput("__" + this.modAliasId + "__"); + } else { + var moduleDecl = this.semanticInfoChain.getASTForSymbol(pullSymbol, this.document.fileName); + var modPath = name.actualText; + var isAmbient = pullSymbol.hasFlag(8 /* Ambient */); + modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); + modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); + this.writeToOutput("require(" + modPath + ")"); + } + } else { + this.writeToOutput(name.actualText); + } + } + + this.recordSourceMappingEnd(name); + this.emitComments(name, false); + }; + + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if (this.sourceMapper) { + var finalName = name; + if (!name) { + finalName = ""; + } else if (this.sourceMapper.currentNameIndex.length > 0) { + finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]] + "." + name; + } + + this.sourceMapper.names.push(finalName); + this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); + } + }; + + Emitter.prototype.recordSourceMappingNameEnd = function () { + if (this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + + Emitter.prototype.recordSourceMappingStart = function (ast) { + if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + var lineCol = { line: -1, character: -1 }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + + var lineMap = this.document.lineMap; + lineMap.fillLineAndCharacterFromPosition(ast.minChar, lineCol); + sourceMapping.start.sourceColumn = lineCol.character; + sourceMapping.start.sourceLine = lineCol.line + 1; + lineMap.fillLineAndCharacterFromPosition(ast.limChar, lineCol); + sourceMapping.end.sourceColumn = lineCol.character; + sourceMapping.end.sourceLine = lineCol.line + 1; + if (this.sourceMapper.currentNameIndex.length > 0) { + sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + } + + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + siblings.push(sourceMapping); + this.sourceMapper.currentMappings.push(sourceMapping.childMappings); + } + }; + + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + this.sourceMapper.currentMappings.pop(); + + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + var sourceMapping = siblings[siblings.length - 1]; + + sourceMapping.end.emittedColumn = this.emitState.column; + sourceMapping.end.emittedLine = this.emitState.line; + } + }; + + Emitter.prototype.emitSourceMapsAndClose = function () { + if (this.sourceMapper !== null) { + TypeScript.SourceMapper.emitSourceMapping(this.allSourceMappers); + } + + try { + this.outfile.Close(); + } catch (e) { + Emitter.throwEmitterError(e); + } + }; + + Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { + var constructorDecl = this.thisClassNode.constructorDecl; + + if (constructorDecl && constructorDecl.arguments) { + for (var i = 0, n = constructorDecl.arguments.members.length; i < n; i++) { + var arg = constructorDecl.arguments.members[i]; + if ((arg.getVarFlags() & 256 /* Property */) !== 0 /* None */) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + + for (var i = 0, n = this.thisClassNode.members.members.length; i < n; i++) { + if (this.thisClassNode.members.members[i].nodeType === 17 /* VariableDeclarator */) { + var varDecl = this.thisClassNode.members.members[i]; + if (!TypeScript.hasFlag(varDecl.getVarFlags(), 16 /* Static */) && varDecl.init) { + this.emitIndent(); + this.emitVariableDeclarator(varDecl); + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.emitCommaSeparatedList = function (list, startLine) { + if (typeof startLine === "undefined") { startLine = false; } + if (list === null) { + return; + } else { + for (var i = 0, n = list.members.length; i < n; i++) { + var emitNode = list.members[i]; + this.emitJavascript(emitNode, startLine); + + if (i < (n - 1)) { + this.writeToOutput(startLine ? "," : ", "); + } + + if (startLine) { + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.emitModuleElements = function (list) { + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = 0, n = list.members.length; i < n; i++) { + var node = list.members[i]; + + if (node.shouldEmit()) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.isDirectivePrologueElement = function (node) { + if (node.nodeType === 88 /* ExpressionStatement */) { + var exprStatement = node; + return exprStatement.expression.nodeType === 5 /* StringLiteral */; + } + + return false; + }; + + Emitter.prototype.emitSpaceBetweenConstructs = function (node1, node2) { + if (node1 === null || node2 === null) { + return; + } + + if (node1.minChar === -1 || node1.limChar === -1 || node2.minChar === -1 || node2.limChar === -1) { + return; + } + + var lineMap = this.document.lineMap; + var node1EndLine = lineMap.getLineNumberFromPosition(node1.limChar); + var node2StartLine = lineMap.getLineNumberFromPosition(node2.minChar); + + if ((node2StartLine - node1EndLine) > 1) { + this.writeLineToOutput(""); + } + }; + + Emitter.prototype.emitScriptElements = function (script, requiresExtendsBlock) { + var list = script.moduleElements; + this.emitComments(list, true); + + for (var i = 0, n = list.members.length; i < n; i++) { + var node = list.members[i]; + + if (!this.isDirectivePrologueElement(node)) { + break; + } + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + } + + this.emitPrologue(script, requiresExtendsBlock); + var lastEmittedNode = null; + + for (; i < n; i++) { + var node = list.members[i]; + + if (node.shouldEmit()) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitConstructorStatements = function (funcDecl) { + var list = funcDecl.block.statements; + + if (list === null) { + return; + } + + this.emitComments(list, true); + + var emitPropertyAssignmentsAfterSuperCall = this.thisClassNode.extendsList && this.thisClassNode.extendsList.members.length > 0; + var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; + var lastEmittedNode = null; + + for (var i = 0, n = list.members.length; i < n; i++) { + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + var node = list.members[i]; + + if (node.shouldEmit()) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitJavascript = function (ast, startLine) { + if (ast === null) { + return; + } + + if (startLine && this.indenter.indentAmt > 0) { + this.emitIndent(); + } + + ast.emit(this); + }; + + Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { + if (!TypeScript.hasFlag(funcDecl.getFunctionFlags(), 32 /* GetAccessor */)) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain, this.document.fileName); + if (accessorSymbol.getGetter()) { + return; + } + } + + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); + this.indenter.increaseIndent(); + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain, this.document.fileName); + if (accessors.getter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.getter); + this.writeToOutput("get: "); + this.emitInnerFunction(accessors.getter, false); + this.writeLineToOutput(","); + } + + if (accessors.setter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.setter); + this.writeToOutput("set: "); + this.emitInnerFunction(accessors.setter, false); + this.writeLineToOutput(","); + } + + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + }; + + Emitter.prototype.emitPrototypeMember = function (funcDecl, className) { + if (funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, className, true); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.emitComments(funcDecl, true); + this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); + this.emitInnerFunction(funcDecl, false, false); + this.writeLineToOutput(";"); + } + }; + + Emitter.prototype.emitClass = function (classDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(classDecl, this.document.fileName); + this.pushDecl(pullDecl); + + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var className = classDecl.name.actualText; + this.emitComments(classDecl, true); + var temp = this.setContainer(3 /* Class */); + + this.recordSourceMappingStart(classDecl); + this.writeToOutput("var " + className); + + var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; + var baseNameDecl = null; + var baseName = null; + var varDecl = null; + + if (hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + + if (hasBaseClass) { + baseNameDecl = classDecl.extendsList.members[0]; + baseName = baseNameDecl.nodeType === 36 /* InvocationExpression */ ? (baseNameDecl).target : baseNameDecl; + this.emitIndent(); + this.writeLineToOutput("__extends(" + className + ", _super);"); + } + + this.emitIndent(); + + var constrDecl = classDecl.constructorDecl; + + if (constrDecl) { + constrDecl.emit(this); + this.writeLineToOutput(""); + } else { + this.recordSourceMappingStart(classDecl); + + this.indenter.increaseIndent(); + this.writeLineToOutput("function " + classDecl.name.actualText + "() {"); + this.recordSourceMappingNameStart("constructor"); + if (hasBaseClass) { + this.emitIndent(); + this.writeLineToOutput("_super.apply(this, arguments);"); + } + + this.emitParameterPropertyAndMemberVariableAssignments(); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + + this.emitClassMembers(classDecl); + + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeLineToOutput("return " + className + ";"); + this.recordSourceMappingEnd(classDecl.endingToken); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl.endingToken); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if (hasBaseClass) { + this.resolvingContext.resolvingTypeReference = true; + this.emitJavascript(baseName, false); + this.resolvingContext.resolvingTypeReference = false; + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + + if ((temp === 1 /* Module */ || temp === 2 /* DynamicModule */) && TypeScript.hasFlag(classDecl.getVarFlags(), 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(classDecl); + this.writeToOutput(modName + "." + className + " = " + className + ";"); + this.recordSourceMappingEnd(classDecl); + } + + this.recordSourceMappingEnd(classDecl); + this.emitComments(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClassMembers = function (classDecl) { + var lastEmittedMember = null; + + for (var i = 0, n = classDecl.members.members.length; i < n; i++) { + var memberDecl = classDecl.members.members[i]; + + if (memberDecl.nodeType === 12 /* FunctionDeclaration */) { + var fn = memberDecl; + + if (TypeScript.hasFlag(fn.getFunctionFlags(), 256 /* Method */) && !fn.isSignature()) { + this.emitSpaceBetweenConstructs(lastEmittedMember, fn); + + if (!TypeScript.hasFlag(fn.getFunctionFlags(), 16 /* Static */)) { + this.emitPrototypeMember(fn, classDecl.name.actualText); + } else { + if (fn.isAccessor()) { + this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(fn); + this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); + this.emitInnerFunction(fn, false); + this.writeLineToOutput(";"); + } + } + + lastEmittedMember = fn; + } + } + } + + for (var i = 0, n = classDecl.members.members.length; i < n; i++) { + var memberDecl = classDecl.members.members[i]; + + if (memberDecl.nodeType === 17 /* VariableDeclarator */) { + var varDecl = memberDecl; + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 16 /* Static */) && varDecl.init) { + this.emitSpaceBetweenConstructs(lastEmittedMember, varDecl); + + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); + varDecl.init.emit(this); + + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(varDecl); + + lastEmittedMember = varDecl; + } + } + } + }; + + Emitter.prototype.emitPrologue = function (script, requiresExtendsBlock) { + if (!this.extendsPrologueEmitted) { + if (requiresExtendsBlock) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + + if (!this.globalThisCapturePrologueEmitted) { + if (this.shouldCaptureThis(script)) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + + Emitter.prototype.emitSuperReference = function () { + this.writeToOutput("_super.prototype"); + }; + + Emitter.prototype.emitSuperCall = function (callEx) { + if (callEx.target.nodeType === 32 /* MemberAccessExpression */) { + var dotNode = callEx.target; + if (dotNode.operand1.nodeType === 30 /* SuperExpression */) { + dotNode.emit(this); + this.writeToOutput(".call("); + this.emitThis(); + if (callEx.arguments && callEx.arguments.members.length > 0) { + this.writeToOutput(", "); + this.emitCommaSeparatedList(callEx.arguments); + } + this.writeToOutput(")"); + return true; + } + } + return false; + }; + + Emitter.prototype.emitThis = function () { + if (this.thisFunctionDeclaration && !this.thisFunctionDeclaration.isMethod() && (!this.thisFunctionDeclaration.isConstructor)) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + + Emitter.prototype.emitBlockOrStatement = function (node) { + if (node.nodeType === 81 /* Block */) { + node.emit(this); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascript(node, true); + this.indenter.decreaseIndent(); + } + }; + + Emitter.throwEmitterError = function (e) { + var error = new Error(e.message); + error.isEmitterError = true; + throw error; + }; + + Emitter.handleEmitterError = function (fileName, e) { + if ((e).isEmitterError === true) { + return [new TypeScript.Diagnostic(fileName, 0, 0, 275 /* Emit_Error__0 */, [e.message])]; + } + + throw e; + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (typeof markerBaseLength === "undefined") { markerBaseLength = 0; } + var result = memberName.prefix; + + if (memberName.isString()) { + result += (memberName).text; + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + + result += memberName.suffix; + return result; + }; + + MemberName.create = function (arg1, arg2, arg3) { + if (typeof arg1 === "string") { + return new MemberNameString(arg1); + } else { + var result = new MemberNameArray(); + if (arg2) + result.prefix = arg2; + if (arg3) + result.suffix = arg3; + result.entries.push(arg1); + return result; + } + }; + return MemberName; + })(); + TypeScript.MemberName = MemberName; + + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.call(this); + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + + MemberNameArray.prototype.addAll = function (entries) { + for (var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripQuotes(str) { + return str.replace(/"/g, "").replace(/'/g, ""); + } + TypeScript.stripQuotes = stripQuotes; + + function isSingleQuoted(str) { + return str.indexOf("'") !== -1; + } + TypeScript.isSingleQuoted = isSingleQuoted; + + function isQuoted(str) { + return str.indexOf("\"") !== -1 || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + + function swapQuotes(str) { + if (str.indexOf("\"") !== -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } else { + str = str.replace("'", "\""); + str = str.replace("'", "\""); + } + + return str; + } + TypeScript.swapQuotes = swapQuotes; + + function switchToForwardSlashes(path) { + return path.replace(/\\/g, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + + function trimModName(modName) { + if (modName.length > 5 && modName.substring(modName.length - 5, modName.length) === ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if (modName.length > 3 && modName.substring(modName.length - 3, modName.length) === ".ts") { + return modName.substring(0, modName.length - 3); + } + + if (modName.length > 3 && modName.substring(modName.length - 3, modName.length) === ".js") { + return modName.substring(0, modName.length - 3); + } + + return modName; + } + TypeScript.trimModName = trimModName; + + function getDeclareFilePath(fname) { + return isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) === invariantExt; + } + + function isJSFile(fname) { + return isFileOfExtension(fname, ".js"); + } + TypeScript.isJSFile = isJSFile; + + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + + function getPrettyName(modPath, quote, treatAsFileName) { + if (typeof quote === "undefined") { quote = true; } + if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { + absoluteModPath = switchToForwardSlashes(absoluteModPath); + + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + + var joinStartIndex = 0; + for (; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if (fixedModComponents[joinStartIndex] !== modComponents[joinStartIndex]) { + break; + } + } + + if (joinStartIndex !== 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for (; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if (fixedModComponents[joinStartIndex] !== "") { + relativePath = relativePath + "../"; + } + } + + return relativePath + relativePathComponents.join("/"); + } + + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + + function quoteBaseName(modPath) { + var modName = trimModName(stripQuotes(modPath)); + var path = getRootFilePath(modName); + if (path === "") { + return modPath; + } else { + var components = modName.split(path); + var fileIndex = components.length > 1 ? 1 : 0; + return quoteStr(components[fileIndex]); + } + } + TypeScript.quoteBaseName = quoteBaseName; + + function changePathToDTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + + function isRelative(path) { + return path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.charAt(0) === "\\" || path.charAt(0) === "/" || (path.indexOf(":\\") !== -1) || (path.indexOf(":/") !== -1); + } + TypeScript.isRooted = isRooted; + + function getRootFilePath(outFname) { + if (outFname === "") { + return outFname; + } else { + var isPath = outFname.indexOf("/") !== -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + + function normalizePath(path) { + if (/^\\\\[^\\]/.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + + normalizedParts.push(part); + } + + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnit = (function () { + function SourceUnit(path, fileInformation) { + this.path = path; + this.fileInformation = fileInformation; + this.referencedFiles = null; + this.lineStarts = null; + } + SourceUnit.prototype.getText = function (start, end) { + return this.fileInformation.contents().substring(start, end); + }; + + SourceUnit.prototype.getLength = function () { + return this.fileInformation.contents().length; + }; + + SourceUnit.prototype.getLineStartPositions = function () { + if (this.lineStarts === null) { + this.lineStarts = TypeScript.LineMap.fromString(this.fileInformation.contents()).lineStarts(); + } + + return this.lineStarts; + }; + + SourceUnit.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return SourceUnit; + })(); + TypeScript.SourceUnit = SourceUnit; + + var CompilationEnvironment = (function () { + function CompilationEnvironment(compilationSettings, ioHost) { + this.compilationSettings = compilationSettings; + this.ioHost = ioHost; + this.code = []; + this.inputFileNameToOutputFileName = new TypeScript.StringHashTable(); + } + CompilationEnvironment.prototype.getSourceUnit = function (path) { + var normalizedPath = TypeScript.switchToForwardSlashes(path.toUpperCase()); + for (var i = 0, n = this.code.length; i < n; i++) { + var sourceUnit = this.code[i]; + var soruceUnitNormalizedPath = TypeScript.switchToForwardSlashes(sourceUnit.path.toUpperCase()); + if (normalizedPath === soruceUnitNormalizedPath) { + return sourceUnit; + } + } + + return null; + }; + return CompilationEnvironment; + })(); + TypeScript.CompilationEnvironment = CompilationEnvironment; + + var CodeResolver = (function () { + function CodeResolver(environment) { + this.environment = environment; + this.visited = {}; + } + CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { + var resolvedFile = { fileInformation: null, path: referencePath }; + + var ioHost = this.environment.ioHost; + + var isRelativePath = TypeScript.isRelative(referencePath); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); + var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); + + if (!TypeScript.isTSFile(normalizedPath)) { + normalizedPath += ".ts"; + } + + normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); + var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); + + if (!this.visited[absoluteModuleID]) { + if (isRelativePath || isRootedPath || !performSearch) { + try { + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + + try { + resolvedFile.fileInformation = ioHost.readFile(normalizedPath); + } catch (err1) { + if (TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.fileInformation = ioHost.readFile(normalizedPath); + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); + + resolvedFile.path = normalizedPath; + this.visited[absoluteModuleID] = true; + } catch (err4) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); + + return false; + } + } else { + try { + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + + if (!resolvedFile) { + if (TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + } + } catch (e) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + normalizedPath); + + return false; + } + + if (resolvedFile) { + resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); + TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); + resolvedFile.fileInformation = resolvedFile.fileInformation; + this.visited[absoluteModuleID] = true; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); + } + } + + if (resolvedFile && resolvedFile.fileInformation !== null) { + var rootDir = ioHost.dirName(resolvedFile.path); + var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.fileInformation); + var preProcessedFileInfo = TypeScript.preProcessFile(resolvedFile.path, sourceUnit, this.environment.compilationSettings); + var resolvedFilePath = ioHost.resolvePath(resolvedFile.path); + var resolutionResult; + + sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; + + for (var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { + var fileReference = preProcessedFileInfo.referencedFiles[i]; + + normalizedPath = TypeScript.isRooted(fileReference.path) ? fileReference.path : rootDir + "/" + fileReference.path; + normalizedPath = ioHost.resolvePath(normalizedPath); + + if (resolvedFilePath === normalizedPath) { + resolutionDispatcher.errorReporter.addDiagnostic(new TypeScript.Diagnostic(normalizedPath, fileReference.position, fileReference.length, 270 /* A_file_cannot_have_a_reference_itself */, null)); + continue; + } + + resolutionResult = this.resolveCode(fileReference.path, rootDir, false, resolutionDispatcher); + + if (!resolutionResult) { + resolutionDispatcher.errorReporter.addDiagnostic(new TypeScript.Diagnostic(resolvedFilePath, fileReference.position, fileReference.length, 271 /* Cannot_resolve_referenced_file___0_ */, [fileReference.path])); + } + } + + for (var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { + var fileImport = preProcessedFileInfo.importedFiles[i]; + + resolutionResult = this.resolveCode(fileImport.path, rootDir, true, resolutionDispatcher); + + if (!resolutionResult) { + resolutionDispatcher.errorReporter.addDiagnostic(new TypeScript.Diagnostic(resolvedFilePath, fileImport.position, fileImport.length, 272 /* Cannot_resolve_imported_file___0_ */, [fileImport.path])); + } + } + + resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); + } + } + return true; + }; + return CodeResolver; + })(); + TypeScript.CodeResolver = CodeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CompilationSettings = (function () { + function CompilationSettings() { + this.propagateConstants = false; + this.minWhitespace = false; + this.emitComments = false; + this.watch = false; + this.exec = false; + this.resolve = true; + this.disallowBool = false; + this.allowAutomaticSemicolonInsertion = true; + this.allowModuleKeywordInExternalModuleReference = true; + this.useDefaultLib = true; + this.codeGenTarget = 0 /* EcmaScript3 */; + this.moduleGenTarget = 0 /* Synchronous */; + this.outputOption = ""; + this.mapSourceFiles = false; + this.emitFullSourceMapPath = false; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + this.gatherDiagnostics = false; + this.updateTC = false; + this.implicitAny = false; + } + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + + function getFileReferenceFromReferencePath(comment) { + var referencesRegEx = /^(\/\/\/\s*/gim; + var match = referencesRegEx.exec(comment); + + if (match) { + var path = TypeScript.normalizePath(match[3]); + var adjustedPath = TypeScript.normalizePath(path); + + var isResident = match.length >= 7 && match[6] === "true"; + if (isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } else { + return null; + } + } + + function getImplicitImport(comment) { + var implicitImportRegEx = /^(\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(comment); + + if (match) { + return true; + } + + return false; + } + TypeScript.getImplicitImport = getImplicitImport; + + function getReferencedFiles(fileName, sourceText) { + var preProcessInfo = preProcessFile(fileName, sourceText, null, false); + return preProcessInfo.referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; + + var scannerWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + var scannerDiagnostics = []; + + function processImports(lineMap, scanner, token, importedFiles) { + var position = 0; + var lineChar = { line: -1, character: -1 }; + + while (token.tokenKind !== 10 /* EndOfFileToken */) { + if (token.tokenKind === 49 /* ImportKeyword */) { + var importStart = position + token.leadingTriviaWidth(); + token = scanner.scan(scannerDiagnostics, false); + + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 108 /* EqualsToken */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 66 /* ModuleKeyword */ || token.tokenKind === 67 /* RequireKeyword */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 73 /* OpenParenToken */) { + var afterOpenParenPosition = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + + lineMap.fillLineAndCharacterFromPosition(importStart, lineChar); + + if (token.tokenKind === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: afterOpenParenPosition + token.leadingTriviaWidth(), + length: token.width(), + path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + + position = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + } + } + + function processTripleSlashDirectives(lineMap, firstToken, settings, referencedFiles) { + var leadingTrivia = firstToken.leadingTrivia(); + + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(triviaText); + + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + + referencedFiles.push(referencedCode); + } + + if (settings) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + var isNoDefaultLibMatch = isNoDefaultLibRegex.exec(triviaText); + if (isNoDefaultLibMatch) { + noDefaultLib = (isNoDefaultLibMatch[3] === "true"); + } + } + } + + position += trivia.fullWidth(); + } + + return { noDefaultLib: noDefaultLib }; + } + + function preProcessFile(fileName, sourceText, settings, readImportFiles) { + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + settings = settings || new CompilationSettings(); + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = new TypeScript.Scanner(fileName, text, settings.codeGenTarget, scannerWindow); + + var firstToken = scanner.scan(scannerDiagnostics, false); + + var importedFiles = []; + if (readImportFiles) { + processImports(text.lineMap(), scanner, firstToken, importedFiles); + } + + var referencedFiles = []; + var properties = processTripleSlashDirectives(text.lineMap(), firstToken, settings, referencedFiles); + + scannerDiagnostics.length = 0; + return { settings: settings, referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib }; + } + TypeScript.preProcessFile = preProcessFile; + + function getParseOptions(settings) { + return new TypeScript.ParseOptions(settings.allowAutomaticSemicolonInsertion, settings.allowModuleKeywordInExternalModuleReference); + } + TypeScript.getParseOptions = getParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextWriter = (function () { + function TextWriter(ioHost, path, writeByteOrderMark) { + this.ioHost = ioHost; + this.path = path; + this.writeByteOrderMark = writeByteOrderMark; + this.contents = ""; + this.onNewLine = true; + } + TextWriter.prototype.Write = function (s) { + this.contents += s; + this.onNewLine = false; + }; + + TextWriter.prototype.WriteLine = function (s) { + this.contents += s; + this.contents += "\r\n"; + this.onNewLine = true; + }; + + TextWriter.prototype.Close = function () { + try { + this.ioHost.writeFile(this.path, this.contents, this.writeByteOrderMark); + } catch (e) { + TypeScript.Emitter.throwEmitterError(e); + } + }; + return TextWriter; + })(); + TypeScript.TextWriter = TextWriter; + + var DeclarationEmitter = (function () { + function DeclarationEmitter(emittingFileName, semanticInfoChain, emitOptions, writeByteOrderMark) { + this.emittingFileName = emittingFileName; + this.semanticInfoChain = semanticInfoChain; + this.emitOptions = emitOptions; + this.writeByteOrderMark = writeByteOrderMark; + this.fileName = null; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.declarationContainerStack = []; + this.isDottedModuleName = []; + this.ignoreCallbackAst = null; + this.singleDeclFile = null; + this.varListCount = 0; + this.declFile = new TextWriter(emitOptions.ioHost, emittingFileName, writeByteOrderMark); + } + DeclarationEmitter.prototype.widenType = function (type) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol) { + return this.semanticInfoChain.anyTypeSymbol; + } + + return type; + }; + + DeclarationEmitter.prototype.close = function () { + try { + this.declFile.Close(); + } catch (e) { + TypeScript.Emitter.throwEmitterError(e); + } + }; + + DeclarationEmitter.prototype.emitDeclarations = function (script) { + TypeScript.AstWalkerWithDetailCallback.walk(script, this); + }; + + DeclarationEmitter.prototype.getAstDeclarationContainer = function () { + return this.declarationContainerStack[this.declarationContainerStack.length - 1]; + }; + + DeclarationEmitter.prototype.emitDottedModuleName = function () { + return (this.isDottedModuleName.length === 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; + }; + + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + if (this.emitOptions.compilationSettings.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + + DeclarationEmitter.prototype.canEmitSignature = function (declFlags, declAST, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { + if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } + if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } + var container; + if (useDeclarationContainerTop) { + container = this.getAstDeclarationContainer(); + } else { + container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; + } + + if (container.nodeType === 15 /* ModuleDeclaration */ && !TypeScript.hasFlag(declFlags, 1 /* Exported */)) { + var declSymbol = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(declAST, this.fileName).symbol; + return declSymbol && declSymbol.isExternallyVisible(); + } + + if (!canEmitGlobalAmbientDecl && container.nodeType === 2 /* Script */ && TypeScript.hasFlag(declFlags, 8 /* Ambient */)) { + return false; + } + + return true; + }; + + DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { + if (this.ignoreCallbackAst) { + TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst !== astWithPrePostCallback, "Ignore Callback AST mismatch"); + this.ignoreCallbackAst = null; + return false; + } else if (preCallback && !this.canEmitSignature(declFlags, astWithPrePostCallback, true, preCallback)) { + this.ignoreCallbackAst = astWithPrePostCallback; + return false; + } + + return true; + }; + + DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { + var result = this.getIndentString(); + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + result += "private "; + } + result += "static "; + } else { + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + result += "private "; + } else if (TypeScript.hasFlag(declFlags, 4 /* Public */)) { + result += "public "; + } else { + var emitDeclare = !TypeScript.hasFlag(declFlags, 1 /* Exported */); + + var container = this.getAstDeclarationContainer(); + if (container.nodeType === 15 /* ModuleDeclaration */ && TypeScript.hasFlag((container).getModuleFlags(), 256 /* IsWholeFile */) && TypeScript.hasFlag(declFlags, 1 /* Exported */)) { + result += "export "; + emitDeclare = true; + } + + if (emitDeclare && typeString !== "interface") { + result += "declare "; + } + + result += typeString + " "; + } + } + + return result; + }; + + DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { + this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); + }; + + DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { + if (typeof declFlag === "undefined") { declFlag = 0 /* None */; } + return !TypeScript.hasFlag(declFlag, 2 /* Private */); + }; + + DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { + this.declarationContainerStack.push(ast); + }; + + DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { + TypeScript.CompilerDiagnostics.assert(ast !== this.getAstDeclarationContainer(), 'Declaration container mismatch'); + this.declarationContainerStack.pop(); + }; + + DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { + if (typeof emitIndent === "undefined") { emitIndent = false; } + if (memberName.prefix === "{ ") { + if (emitIndent) { + this.emitIndent(); + } + + this.declFile.WriteLine("{"); + this.indenter.increaseIndent(); + emitIndent = true; + } else if (memberName.prefix !== "") { + if (emitIndent) { + this.emitIndent(); + } + + this.declFile.Write(memberName.prefix); + emitIndent = false; + } + + if (memberName.isString()) { + if (emitIndent) { + this.emitIndent(); + } + + this.declFile.Write((memberName).text); + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + this.emitTypeNamesMember(ar.entries[index], emitIndent); + if (ar.delim === "; ") { + this.declFile.WriteLine(";"); + } + } + } + + if (memberName.suffix === "}") { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.Write(memberName.suffix); + } else { + this.declFile.Write(memberName.suffix); + } + }; + + DeclarationEmitter.prototype.emitTypeSignature = function (type) { + var declarationContainerAst = this.getAstDeclarationContainer(); + var declarationContainerDecl = this.semanticInfoChain.getDeclForAST(declarationContainerAst, this.fileName); + var declarationPullSymbol = declarationContainerDecl.getSymbol(); + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol); + this.emitTypeNamesMember(typeNameMembers); + }; + + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = comment.getText(); + if (this.declFile.onNewLine) { + this.emitIndent(); + } else if (!comment.isBlockComment) { + this.declFile.WriteLine(""); + this.emitIndent(); + } + + this.declFile.Write(text[0]); + + for (var i = 1; i < text.length; i++) { + this.declFile.WriteLine(""); + this.emitIndent(); + this.declFile.Write(text[i]); + } + + if (comment.endsLine || !comment.isBlockComment) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (!this.emitOptions.compilationSettings.emitComments) { + return; + } + + var declComments = astOrSymbol.getDocComments(); + this.writeDeclarationComments(declComments, endLine); + }; + + DeclarationEmitter.prototype.writeDeclarationComments = function (declComments, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (declComments.length > 0) { + for (var i = 0; i < declComments.length; i++) { + this.emitComment(declComments[i]); + } + + if (endLine) { + if (!this.declFile.onNewLine) { + this.declFile.WriteLine(""); + } + } else { + if (this.declFile.onNewLine) { + this.emitIndent(); + } + } + } + }; + + DeclarationEmitter.prototype.emitTypeOfBoundDecl = function (boundDecl) { + var decl = this.semanticInfoChain.getDeclForAST(boundDecl, this.fileName); + var pullSymbol = decl.getSymbol(); + var type = this.widenType(pullSymbol.getType()); + if (!type) { + return; + } + + if (boundDecl.typeExpr || (boundDecl.init && type !== this.semanticInfoChain.anyTypeSymbol)) { + this.declFile.Write(": "); + this.emitTypeSignature(type); + } + }; + + DeclarationEmitter.prototype.VariableDeclaratorCallback = function (pre, varDecl) { + if (pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.getVarFlags()), varDecl, false)) { + var interfaceMember = (this.getAstDeclarationContainer().nodeType === 14 /* InterfaceDeclaration */); + this.emitDeclarationComments(varDecl); + if (!interfaceMember) { + if (this.varListCount >= 0) { + this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.getVarFlags()), "var"); + this.varListCount = -this.varListCount; + } + + this.declFile.Write(varDecl.id.actualText); + } else { + this.emitIndent(); + this.declFile.Write(varDecl.id.actualText); + if (TypeScript.hasFlag(varDecl.id.getFlags(), 4 /* OptionalName */)) { + this.declFile.Write("?"); + } + } + + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.getVarFlags()))) { + this.emitTypeOfBoundDecl(varDecl); + } + + if (this.varListCount > 0) { + this.varListCount--; + } else if (this.varListCount < 0) { + this.varListCount++; + } + + if (this.varListCount < 0) { + this.declFile.Write(", "); + } else { + this.declFile.WriteLine(";"); + } + } + return false; + }; + + DeclarationEmitter.prototype.BlockCallback = function (pre, block) { + return false; + }; + + DeclarationEmitter.prototype.VariableStatementCallback = function (pre, variableDeclaration) { + return true; + }; + + DeclarationEmitter.prototype.VariableDeclarationCallback = function (pre, variableDeclaration) { + if (pre) { + this.varListCount = variableDeclaration.declarators.members.length; + } else { + this.varListCount = 0; + } + return true; + }; + + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { + this.indenter.increaseIndent(); + + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(argDecl.id.actualText); + if (argDecl.isOptionalArg()) { + this.declFile.Write("?"); + } + + this.indenter.decreaseIndent(); + + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()))) { + this.emitTypeOfBoundDecl(argDecl); + } + }; + + DeclarationEmitter.prototype.isOverloadedCallSignature = function (funcDecl) { + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDecl, this.fileName); + var funcSymbol = functionDecl.getSymbol(); + var funcTypeSymbol = funcSymbol.getType(); + var signatures = funcTypeSymbol.getCallSignatures(); + return signatures && signatures.length > 1; + }; + + DeclarationEmitter.prototype.FunctionDeclarationCallback = function (pre, funcDecl) { + if (!pre) { + return false; + } + + if (funcDecl.isAccessor()) { + return this.emitPropertyAccessorSignature(funcDecl); + } + + var isInterfaceMember = (this.getAstDeclarationContainer().nodeType === 14 /* InterfaceDeclaration */); + + var funcSymbol = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(funcDecl, this.fileName).symbol; + var funcTypeSymbol = funcSymbol.getType(); + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return false; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return false; + } + } else if (!isInterfaceMember && TypeScript.hasFlag(funcDecl.getFunctionFlags(), 2 /* Private */) && this.isOverloadedCallSignature(funcDecl)) { + var callSignatures = funcTypeSymbol.getCallSignatures(); + TypeScript.Debug.assert(callSignatures && callSignatures.length > 1); + var firstSignature = callSignatures[0].isDefinition() ? callSignatures[1] : callSignatures[0]; + var firstSignatureDecl = firstSignature.getDeclarations()[0]; + var firstFuncDecl = this.semanticInfoChain.getASTForDecl(firstSignatureDecl); + if (firstFuncDecl !== funcDecl) { + return false; + } + } + + if (!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()), funcDecl, false)) { + return false; + } + + var funcSignature = this.semanticInfoChain.getDeclForAST(funcDecl, this.fileName).getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + if (funcDecl.isConstructor) { + this.emitIndent(); + this.declFile.Write("constructor"); + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } else { + var id = funcDecl.getNameText(); + if (!isInterfaceMember) { + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()), "function"); + if (id !== "__missing" || !funcDecl.name || !funcDecl.name.isMissing()) { + this.declFile.Write(id); + } else if (funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } + + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } else { + this.emitIndent(); + if (funcDecl.isConstructMember()) { + this.declFile.Write("new"); + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } else if (!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { + this.declFile.Write(id); + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + if (TypeScript.hasFlag(funcDecl.name.getFlags(), 4 /* OptionalName */)) { + this.declFile.Write("? "); + } + } else { + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } + } + } + + if (!funcDecl.isIndexerMember()) { + this.declFile.Write("("); + } else { + this.declFile.Write("["); + } + + if (funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if (funcDecl.variableArgList) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + this.emitArgDecl(argDecl, funcDecl); + if (i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + } + + if (funcDecl.variableArgList) { + var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; + if (funcDecl.arguments.members.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + + this.emitArgDecl(lastArg, funcDecl); + } + + if (!funcDecl.isIndexerMember()) { + this.declFile.Write(")"); + } else { + this.declFile.Write("]"); + } + + if (!funcDecl.isConstructor && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()))) { + var returnType = funcSignature.getReturnType(); + if (funcDecl.returnTypeAnnotation || (returnType && returnType !== this.semanticInfoChain.anyTypeSymbol)) { + this.declFile.Write(": "); + this.emitTypeSignature(returnType); + } + } + + this.declFile.WriteLine(";"); + + return false; + }; + + DeclarationEmitter.prototype.emitBaseExpression = function (bases, index) { + var baseTypeAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(bases.members[index], this.fileName); + var baseType = baseTypeAndDiagnostics && baseTypeAndDiagnostics.symbol; + this.emitTypeSignature(baseType); + }; + + DeclarationEmitter.prototype.emitBaseList = function (typeDecl, useExtendsList) { + var bases = useExtendsList ? typeDecl.extendsList : typeDecl.implementsList; + if (bases && (bases.members.length > 0)) { + var qual = useExtendsList ? "extends" : "implements"; + this.declFile.Write(" " + qual + " "); + var basesLen = bases.members.length; + for (var i = 0; i < basesLen; i++) { + if (i > 0) { + this.declFile.Write(", "); + } + this.emitBaseExpression(bases, i); + } + } + }; + + DeclarationEmitter.prototype.emitAccessorDeclarationComments = function (funcDecl) { + if (!this.emitOptions.compilationSettings.emitComments) { + return; + } + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain, this.fileName); + var comments = []; + if (accessors.getter) { + comments = comments.concat(accessors.getter.getDocComments()); + } + if (accessors.setter) { + comments = comments.concat(accessors.setter.getDocComments()); + } + this.writeDeclarationComments(comments); + }; + + DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain, this.fileName); + if (!TypeScript.hasFlag(funcDecl.getFunctionFlags(), 32 /* GetAccessor */) && accessorSymbol.getGetter()) { + return false; + } + + this.emitAccessorDeclarationComments(funcDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()), "var"); + this.declFile.Write(funcDecl.name.actualText); + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()))) { + this.declFile.Write(" : "); + var type = accessorSymbol.getType(); + this.emitTypeSignature(type); + } + this.declFile.WriteLine(";"); + + return false; + }; + + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + if (funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if (funcDecl.variableArgList) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + if (TypeScript.hasFlag(argDecl.getVarFlags(), 256 /* Property */)) { + this.emitDeclarationComments(argDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.getVarFlags()), "var"); + this.declFile.Write(argDecl.id.actualText); + + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.getVarFlags()))) { + this.emitTypeOfBoundDecl(argDecl); + } + this.declFile.WriteLine(";"); + } + } + } + }; + + DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { + if (!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.getVarFlags()), classDecl, pre)) { + return false; + } + + if (pre) { + var className = classDecl.name.actualText; + this.emitDeclarationComments(classDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.getVarFlags()), "class"); + this.declFile.Write(className); + this.pushDeclarationContainer(classDecl); + this.emitTypeParameters(classDecl.typeParameters); + this.emitBaseList(classDecl, true); + this.emitBaseList(classDecl, false); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + if (classDecl.constructorDecl) { + this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); + } + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(classDecl); + + this.emitIndent(); + this.declFile.WriteLine("}"); + } + + return true; + }; + + DeclarationEmitter.prototype.emitTypeParameters = function (typeParams, funcSignature) { + if (!typeParams || !typeParams.members.length) { + return; + } + + this.declFile.Write("<"); + var containerAst = this.getAstDeclarationContainer(); + var containerDecl = this.semanticInfoChain.getDeclForAST(containerAst, this.fileName); + var containerSymbol = containerDecl.getSymbol(); + var typars; + if (funcSignature) { + typars = funcSignature.getTypeParameters(); + } else { + typars = containerSymbol.getTypeArguments(); + if (!typars || !typars.length) { + typars = containerSymbol.getTypeParameters(); + } + } + + for (var i = 0; i < typars.length; i++) { + if (i) { + this.declFile.Write(", "); + } + + var memberName = typars[i].getScopedNameEx(containerSymbol, true); + this.emitTypeNamesMember(memberName); + } + + this.declFile.Write(">"); + }; + + DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { + if (!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.getVarFlags()), interfaceDecl, pre)) { + return false; + } + + if (pre) { + var interfaceName = interfaceDecl.name.actualText; + this.emitDeclarationComments(interfaceDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.getVarFlags()), "interface"); + this.declFile.Write(interfaceName); + this.pushDeclarationContainer(interfaceDecl); + this.emitTypeParameters(interfaceDecl.typeParameters); + this.emitBaseList(interfaceDecl, true); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(interfaceDecl); + + this.emitIndent(); + this.declFile.WriteLine("}"); + } + + return true; + }; + + DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDeclAST) { + if (pre) { + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST, this.fileName); + var importSymbol = importDecl.getSymbol(); + if (importSymbol.getTypeUsedExternally() || TypeScript.PullContainerTypeSymbol.usedAsSymbol(importSymbol.getContainer(), importSymbol)) { + this.emitDeclarationComments(importDeclAST); + this.emitIndent(); + this.declFile.Write("import "); + + this.declFile.Write(importDeclAST.id.actualText + " = "); + if (importDeclAST.isDynamicImport) { + this.declFile.WriteLine("require(" + importDeclAST.getAliasName() + ");"); + } else { + this.declFile.WriteLine(importDeclAST.getAliasName() + ";"); + } + } + } + + return false; + }; + + DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { + if (!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), moduleDecl)) { + return false; + } + + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), "enum"); + this.declFile.WriteLine(moduleDecl.name.actualText + " {"); + + this.indenter.increaseIndent(); + var membersLen = moduleDecl.members.members.length; + for (var j = 0; j < membersLen; j++) { + var memberDecl = moduleDecl.members.members[j]; + if (memberDecl.nodeType === 97 /* VariableStatement */ && !TypeScript.hasFlag(memberDecl.getFlags(), 32 /* EnumMapElement */)) { + var variableStatement = memberDecl; + this.emitDeclarationComments(memberDecl); + this.emitIndent(); + this.declFile.WriteLine((variableStatement.declaration.declarators.members[0]).id.actualText + ","); + } + } + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + + return false; + }; + + DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 256 /* IsWholeFile */)) { + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 512 /* IsDynamic */)) { + if (pre) { + if (!this.emitOptions.outputMany) { + this.singleDeclFile = this.declFile; + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt === 0, "Indent has to be 0 when outputing new file"); + + var declareFileName = this.emitOptions.mapOutputFileName(this.fileName, TypeScript.TypeScriptCompiler.mapToDTSFileName); + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.compilationSettings.emitComments && moduleDecl.containsUnicodeCharInComment); + + this.declFile = new TextWriter(this.emitOptions.ioHost, declareFileName, this.writeByteOrderMark); + } + this.pushDeclarationContainer(moduleDecl); + } else { + if (!this.emitOptions.outputMany) { + TypeScript.CompilerDiagnostics.assert(this.singleDeclFile !== this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt === 0, "Indent has to be 0 when outputing new file"); + + try { + this.declFile.Close(); + } catch (e) { + TypeScript.Emitter.throwEmitterError(e); + } + + this.declFile = this.singleDeclFile; + } + + this.popDeclarationContainer(moduleDecl); + } + } + + return true; + } + + if (moduleDecl.isEnum()) { + if (pre) { + this.emitEnumSignature(moduleDecl); + } + return false; + } + + if (!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), moduleDecl, pre)) { + return false; + } + + if (pre) { + if (this.emitDottedModuleName()) { + this.dottedModuleEmit += "."; + } else { + this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), "module"); + } + + this.dottedModuleEmit += moduleDecl.name.actualText; + + var isCurrentModuleDotted = (moduleDecl.members.members.length === 1 && moduleDecl.members.members[0].nodeType === 15 /* ModuleDeclaration */ && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).getModuleFlags(), 1 /* Exported */)); + + var moduleDeclComments = moduleDecl.getDocComments(); + isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments === null || moduleDeclComments.length === 0); + + this.isDottedModuleName.push(isCurrentModuleDotted); + this.pushDeclarationContainer(moduleDecl); + + if (!isCurrentModuleDotted) { + this.emitDeclarationComments(moduleDecl); + this.declFile.Write(this.dottedModuleEmit); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + } + } else { + if (!this.emitDottedModuleName()) { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + + this.popDeclarationContainer(moduleDecl); + this.isDottedModuleName.pop(); + } + + return true; + }; + + DeclarationEmitter.prototype.ExportAssignmentCallback = function (pre, ast) { + if (pre) { + this.emitIndent(); + this.declFile.Write("export = "); + this.declFile.Write((ast).id.actualText); + this.declFile.WriteLine(";"); + } + + return false; + }; + + DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { + if (pre) { + if (this.emitOptions.outputMany) { + for (var i = 0; i < script.referencedFiles.length; i++) { + var referencePath = script.referencedFiles[i].path; + var declareFileName; + if (TypeScript.isRooted(referencePath)) { + declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } else { + declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); + } + this.declFile.WriteLine('/// '); + } + } + this.pushDeclarationContainer(script); + } else { + this.popDeclarationContainer(script); + } + return true; + }; + + DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { + return !ast.isStatement(); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + + var sizeInEvenBytes = (m + 7) & ~7; + + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + + BloomFilter.prototype.computeHash = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = this.getCharacter(key, index); + var c2 = this.getCharacter(key, index + 1); + + var k = Math.abs(c1 | (c2 << 16)); + + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft == 1) { + h ^= this.getCharacter(key, index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + + return Math.round(h); + }; + + BloomFilter.prototype.getCharacter = function (key, index) { + return key.charCodeAt(index); + }; + + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + this.add(name); + } + }; + + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + + return true; + }; + + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount == filter.hashFunctionCount; + }; + + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length != array2.length) { + return false; + } + + for (var i = 0; i < array1.length; i++) { + if (array1[i] != array2[i]) { + return false; + } + } + + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IdentifierWalker = (function (_super) { + __extends(IdentifierWalker, _super); + function IdentifierWalker(list) { + _super.call(this); + this.list = list; + } + IdentifierWalker.prototype.visitToken = function (token) { + this.list[token.text()] = true; + }; + return IdentifierWalker; + })(TypeScript.SyntaxWalker); + TypeScript.IdentifierWalker = IdentifierWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DataMap = (function () { + function DataMap() { + this.map = {}; + } + DataMap.prototype.link = function (id, data) { + this.map[id] = data; + }; + + DataMap.prototype.unlink = function (id) { + this.map[id] = undefined; + }; + + DataMap.prototype.read = function (id) { + return this.map[id]; + }; + + DataMap.prototype.flush = function () { + this.map = {}; + }; + + DataMap.prototype.unpatch = function () { + return null; + }; + return DataMap; + })(); + TypeScript.DataMap = DataMap; + + var PatchedDataMap = (function (_super) { + __extends(PatchedDataMap, _super); + function PatchedDataMap(parent) { + _super.call(this); + this.parent = parent; + this.diffs = {}; + } + PatchedDataMap.prototype.link = function (id, data) { + this.diffs[id] = data; + }; + + PatchedDataMap.prototype.unlink = function (id) { + this.diffs[id] = undefined; + }; + + PatchedDataMap.prototype.read = function (id) { + var data = this.diffs[id]; + + if (data) { + return data; + } + + return this.parent.read(id); + }; + + PatchedDataMap.prototype.flush = function () { + this.diffs = {}; + }; + + PatchedDataMap.prototype.unpatch = function () { + this.flush(); + return this.parent; + }; + return PatchedDataMap; + })(DataMap); + TypeScript.PatchedDataMap = PatchedDataMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullElementFlags) { + PullElementFlags[PullElementFlags["None"] = 0] = "None"; + PullElementFlags[PullElementFlags["Exported"] = 1] = "Exported"; + PullElementFlags[PullElementFlags["Private"] = 1 << 1] = "Private"; + PullElementFlags[PullElementFlags["Public"] = 1 << 2] = "Public"; + PullElementFlags[PullElementFlags["Ambient"] = 1 << 3] = "Ambient"; + PullElementFlags[PullElementFlags["Static"] = 1 << 4] = "Static"; + PullElementFlags[PullElementFlags["GetAccessor"] = 1 << 5] = "GetAccessor"; + PullElementFlags[PullElementFlags["SetAccessor"] = 1 << 6] = "SetAccessor"; + PullElementFlags[PullElementFlags["Optional"] = 1 << 7] = "Optional"; + PullElementFlags[PullElementFlags["Call"] = 1 << 8] = "Call"; + PullElementFlags[PullElementFlags["Constructor"] = 1 << 9] = "Constructor"; + PullElementFlags[PullElementFlags["Index"] = 1 << 10] = "Index"; + PullElementFlags[PullElementFlags["Signature"] = 1 << 11] = "Signature"; + PullElementFlags[PullElementFlags["Enum"] = 1 << 12] = "Enum"; + PullElementFlags[PullElementFlags["FatArrow"] = 1 << 13] = "FatArrow"; + + PullElementFlags[PullElementFlags["ClassConstructorVariable"] = 1 << 14] = "ClassConstructorVariable"; + PullElementFlags[PullElementFlags["InitializedModule"] = 1 << 15] = "InitializedModule"; + PullElementFlags[PullElementFlags["InitializedDynamicModule"] = 1 << 16] = "InitializedDynamicModule"; + PullElementFlags[PullElementFlags["InitializedEnum"] = 1 << 17] = "InitializedEnum"; + + PullElementFlags[PullElementFlags["MustCaptureThis"] = 1 << 18] = "MustCaptureThis"; + PullElementFlags[PullElementFlags["Constant"] = 1 << 19] = "Constant"; + + PullElementFlags[PullElementFlags["ExpressionElement"] = 1 << 20] = "ExpressionElement"; + + PullElementFlags[PullElementFlags["DeclaredInAWithBlock"] = 1 << 21] = "DeclaredInAWithBlock"; + + PullElementFlags[PullElementFlags["ImplicitVariable"] = PullElementFlags.ClassConstructorVariable | PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.InitializedEnum] = "ImplicitVariable"; + PullElementFlags[PullElementFlags["SomeInitializedModule"] = PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.InitializedEnum] = "SomeInitializedModule"; + })(TypeScript.PullElementFlags || (TypeScript.PullElementFlags = {})); + var PullElementFlags = TypeScript.PullElementFlags; + + (function (PullElementKind) { + PullElementKind[PullElementKind["None"] = 0] = "None"; + PullElementKind[PullElementKind["Global"] = 0] = "Global"; + + PullElementKind[PullElementKind["Script"] = 1] = "Script"; + PullElementKind[PullElementKind["Primitive"] = 1 << 1] = "Primitive"; + + PullElementKind[PullElementKind["Container"] = 1 << 2] = "Container"; + PullElementKind[PullElementKind["Class"] = 1 << 3] = "Class"; + PullElementKind[PullElementKind["Interface"] = 1 << 4] = "Interface"; + PullElementKind[PullElementKind["DynamicModule"] = 1 << 5] = "DynamicModule"; + PullElementKind[PullElementKind["Enum"] = 1 << 6] = "Enum"; + PullElementKind[PullElementKind["Array"] = 1 << 7] = "Array"; + PullElementKind[PullElementKind["TypeAlias"] = 1 << 8] = "TypeAlias"; + PullElementKind[PullElementKind["ObjectLiteral"] = 1 << 9] = "ObjectLiteral"; + + PullElementKind[PullElementKind["Variable"] = 1 << 10] = "Variable"; + PullElementKind[PullElementKind["Parameter"] = 1 << 11] = "Parameter"; + PullElementKind[PullElementKind["Property"] = 1 << 12] = "Property"; + PullElementKind[PullElementKind["TypeParameter"] = 1 << 13] = "TypeParameter"; + + PullElementKind[PullElementKind["Function"] = 1 << 14] = "Function"; + PullElementKind[PullElementKind["ConstructorMethod"] = 1 << 15] = "ConstructorMethod"; + PullElementKind[PullElementKind["Method"] = 1 << 16] = "Method"; + PullElementKind[PullElementKind["FunctionExpression"] = 1 << 17] = "FunctionExpression"; + + PullElementKind[PullElementKind["GetAccessor"] = 1 << 18] = "GetAccessor"; + PullElementKind[PullElementKind["SetAccessor"] = 1 << 19] = "SetAccessor"; + + PullElementKind[PullElementKind["CallSignature"] = 1 << 20] = "CallSignature"; + PullElementKind[PullElementKind["ConstructSignature"] = 1 << 21] = "ConstructSignature"; + PullElementKind[PullElementKind["IndexSignature"] = 1 << 22] = "IndexSignature"; + + PullElementKind[PullElementKind["ObjectType"] = 1 << 23] = "ObjectType"; + PullElementKind[PullElementKind["FunctionType"] = 1 << 24] = "FunctionType"; + PullElementKind[PullElementKind["ConstructorType"] = 1 << 25] = "ConstructorType"; + + PullElementKind[PullElementKind["EnumMember"] = 1 << 26] = "EnumMember"; + PullElementKind[PullElementKind["ErrorType"] = 1 << 27] = "ErrorType"; + + PullElementKind[PullElementKind["Expression"] = 1 << 28] = "Expression"; + + PullElementKind[PullElementKind["WithBlock"] = 1 << 29] = "WithBlock"; + PullElementKind[PullElementKind["CatchBlock"] = 1 << 30] = "CatchBlock"; + + PullElementKind[PullElementKind["All"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Container | PullElementKind.Class | PullElementKind.Interface | PullElementKind.DynamicModule | PullElementKind.Enum | PullElementKind.Array | PullElementKind.TypeAlias | PullElementKind.ObjectLiteral | PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.TypeParameter | PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.EnumMember | PullElementKind.ErrorType | PullElementKind.Expression | PullElementKind.WithBlock | PullElementKind.CatchBlock] = "All"; + + PullElementKind[PullElementKind["SomeFunction"] = PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeFunction"; + + PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; + + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Array | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter | PullElementKind.ErrorType] = "SomeType"; + + PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; + + PullElementKind[PullElementKind["SomeContainer"] = PullElementKind.Container | PullElementKind.DynamicModule | PullElementKind.TypeAlias] = "SomeContainer"; + + PullElementKind[PullElementKind["SomeBlock"] = PullElementKind.WithBlock | PullElementKind.CatchBlock] = "SomeBlock"; + + PullElementKind[PullElementKind["SomeSignature"] = PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeSignature"; + + PullElementKind[PullElementKind["SomeAccessor"] = PullElementKind.GetAccessor | PullElementKind.SetAccessor] = "SomeAccessor"; + + PullElementKind[PullElementKind["SomeTypeReference"] = PullElementKind.Interface | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "SomeTypeReference"; + + PullElementKind[PullElementKind["SomeLHS"] = PullElementKind.Variable | PullElementKind.Property | PullElementKind.Parameter | PullElementKind.SetAccessor | PullElementKind.Method] = "SomeLHS"; + + PullElementKind[PullElementKind["InterfaceTypeExtension"] = PullElementKind.Interface | PullElementKind.Class | PullElementKind.Enum] = "InterfaceTypeExtension"; + PullElementKind[PullElementKind["ClassTypeExtension"] = PullElementKind.Interface | PullElementKind.Class] = "ClassTypeExtension"; + PullElementKind[PullElementKind["EnumTypeExtension"] = PullElementKind.Interface | PullElementKind.Enum] = "EnumTypeExtension"; + })(TypeScript.PullElementKind || (TypeScript.PullElementKind = {})); + var PullElementKind = TypeScript.PullElementKind; + + (function (SymbolLinkKind) { + SymbolLinkKind[SymbolLinkKind["TypedAs"] = 0] = "TypedAs"; + SymbolLinkKind[SymbolLinkKind["ContextuallyTypedAs"] = 1] = "ContextuallyTypedAs"; + SymbolLinkKind[SymbolLinkKind["ProvidesInferredType"] = 2] = "ProvidesInferredType"; + SymbolLinkKind[SymbolLinkKind["ArrayType"] = 3] = "ArrayType"; + + SymbolLinkKind[SymbolLinkKind["ArrayOf"] = 4] = "ArrayOf"; + + SymbolLinkKind[SymbolLinkKind["PublicMember"] = 5] = "PublicMember"; + SymbolLinkKind[SymbolLinkKind["PrivateMember"] = 6] = "PrivateMember"; + + SymbolLinkKind[SymbolLinkKind["ConstructorMethod"] = 7] = "ConstructorMethod"; + + SymbolLinkKind[SymbolLinkKind["Aliases"] = 8] = "Aliases"; + SymbolLinkKind[SymbolLinkKind["ExportAliases"] = 9] = "ExportAliases"; + + SymbolLinkKind[SymbolLinkKind["ContainedBy"] = 10] = "ContainedBy"; + + SymbolLinkKind[SymbolLinkKind["Extends"] = 11] = "Extends"; + SymbolLinkKind[SymbolLinkKind["Implements"] = 12] = "Implements"; + + SymbolLinkKind[SymbolLinkKind["Parameter"] = 13] = "Parameter"; + SymbolLinkKind[SymbolLinkKind["ReturnType"] = 14] = "ReturnType"; + + SymbolLinkKind[SymbolLinkKind["CallSignature"] = 15] = "CallSignature"; + SymbolLinkKind[SymbolLinkKind["ConstructSignature"] = 16] = "ConstructSignature"; + SymbolLinkKind[SymbolLinkKind["IndexSignature"] = 17] = "IndexSignature"; + + SymbolLinkKind[SymbolLinkKind["TypeParameter"] = 18] = "TypeParameter"; + SymbolLinkKind[SymbolLinkKind["TypeArgument"] = 19] = "TypeArgument"; + SymbolLinkKind[SymbolLinkKind["TypeParameterSpecializedTo"] = 20] = "TypeParameterSpecializedTo"; + SymbolLinkKind[SymbolLinkKind["SpecializedTo"] = 21] = "SpecializedTo"; + + SymbolLinkKind[SymbolLinkKind["TypeConstraint"] = 22] = "TypeConstraint"; + + SymbolLinkKind[SymbolLinkKind["ContributesToExpression"] = 23] = "ContributesToExpression"; + + SymbolLinkKind[SymbolLinkKind["GetterFunction"] = 24] = "GetterFunction"; + SymbolLinkKind[SymbolLinkKind["SetterFunction"] = 25] = "SetterFunction"; + })(TypeScript.SymbolLinkKind || (TypeScript.SymbolLinkKind = {})); + var SymbolLinkKind = TypeScript.SymbolLinkKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullDeclID = 0; + TypeScript.lastBoundPullDeclId = 0; + + var PullDecl = (function () { + function PullDecl(declName, displayName, declType, declFlags, span, scriptName) { + this.symbol = null; + this.declGroups = new TypeScript.BlockIntrinsics(); + this.signatureSymbol = null; + this.specializingSignatureSymbol = null; + this.childDecls = []; + this.typeParameters = []; + this.childDeclTypeCache = new TypeScript.BlockIntrinsics(); + this.childDeclValueCache = new TypeScript.BlockIntrinsics(); + this.childDeclNamespaceCache = new TypeScript.BlockIntrinsics(); + this.childDeclTypeParameterCache = new TypeScript.BlockIntrinsics(); + this.declID = TypeScript.pullDeclID++; + this.declFlags = 0 /* None */; + this.diagnostics = null; + this.parentDecl = null; + this._parentPath = null; + this._isBound = false; + this.synthesizedValDecl = null; + this.declName = declName; + this.declType = declType; + this.declFlags = declFlags; + this.span = span; + this.scriptName = scriptName; + + if (displayName !== this.declName) { + this.declDisplayName = displayName; + } + } + PullDecl.prototype.getDeclID = function () { + return this.declID; + }; + + PullDecl.prototype.getName = function () { + return this.declName; + }; + PullDecl.prototype.getKind = function () { + return this.declType; + }; + + PullDecl.prototype.getDisplayName = function () { + return this.declDisplayName === undefined ? this.declName : this.declDisplayName; + }; + + PullDecl.prototype.setSymbol = function (symbol) { + this.symbol = symbol; + }; + + PullDecl.prototype.ensureSymbolIsBound = function (bindSignatureSymbol) { + if (typeof bindSignatureSymbol === "undefined") { bindSignatureSymbol = false; } + if (!((bindSignatureSymbol && this.signatureSymbol) || this.symbol) && !this._isBound && this.declType != 1 /* Script */) { + var prevUnit = TypeScript.globalBinder.semanticInfo; + TypeScript.globalBinder.setUnit(this.scriptName); + TypeScript.globalBinder.bindDeclToPullSymbol(this); + if (prevUnit) { + TypeScript.globalBinder.setUnit(prevUnit.getPath()); + } + } + }; + + PullDecl.prototype.getSymbol = function () { + if (this.declType == 1 /* Script */) { + return null; + } + + this.ensureSymbolIsBound(); + + return this.symbol; + }; + + PullDecl.prototype.hasSymbol = function () { + return this.symbol != null; + }; + + PullDecl.prototype.setSignatureSymbol = function (signature) { + this.signatureSymbol = signature; + }; + PullDecl.prototype.getSignatureSymbol = function () { + this.ensureSymbolIsBound(true); + + return this.signatureSymbol; + }; + + PullDecl.prototype.hasSignature = function () { + return this.signatureSymbol != null; + }; + + PullDecl.prototype.setSpecializingSignatureSymbol = function (signature) { + this.specializingSignatureSymbol = signature; + }; + PullDecl.prototype.getSpecializingSignatureSymbol = function () { + if (this.specializingSignatureSymbol) { + return this.specializingSignatureSymbol; + } + + return this.signatureSymbol; + }; + + PullDecl.prototype.getFlags = function () { + return this.declFlags; + }; + PullDecl.prototype.setFlags = function (flags) { + this.declFlags = flags; + }; + + PullDecl.prototype.getSpan = function () { + return this.span; + }; + PullDecl.prototype.setSpan = function (span) { + this.span = span; + }; + + PullDecl.prototype.getScriptName = function () { + return this.scriptName; + }; + + PullDecl.prototype.setValueDecl = function (valDecl) { + this.synthesizedValDecl = valDecl; + }; + PullDecl.prototype.getValueDecl = function () { + return this.synthesizedValDecl; + }; + + PullDecl.prototype.isEqual = function (other) { + return (this.declName === other.declName) && (this.declType === other.declType) && (this.declFlags === other.declFlags) && (this.scriptName === other.scriptName) && (this.span.start() === other.span.start()) && (this.span.end() === other.span.end()); + }; + + PullDecl.prototype.getParentDecl = function () { + return this.parentDecl; + }; + + PullDecl.prototype.setParentDecl = function (parentDecl) { + this.parentDecl = parentDecl; + }; + + PullDecl.prototype.addDiagnostic = function (diagnostic) { + if (diagnostic) { + if (!this.diagnostics) { + this.diagnostics = []; + } + + this.diagnostics[this.diagnostics.length] = diagnostic; + } + }; + + PullDecl.prototype.getDiagnostics = function () { + return this.diagnostics; + }; + + PullDecl.prototype.setErrors = function (diagnostics) { + if (diagnostics) { + this.diagnostics = []; + + for (var i = 0; i < diagnostics.length; i++) { + diagnostics[i].adjustOffset(this.span.start()); + this.diagnostics[this.diagnostics.length] = diagnostics[i]; + } + } + }; + + PullDecl.prototype.resetErrors = function () { + this.diagnostics = []; + }; + + PullDecl.prototype.getChildDeclCache = function (declKind) { + return declKind === 8192 /* TypeParameter */ ? this.childDeclTypeParameterCache : TypeScript.hasFlag(declKind, TypeScript.PullElementKind.SomeContainer) ? this.childDeclNamespaceCache : TypeScript.hasFlag(declKind, TypeScript.PullElementKind.SomeType) ? this.childDeclTypeCache : this.childDeclValueCache; + }; + + PullDecl.prototype.addChildDecl = function (childDecl) { + if (childDecl.getKind() === 8192 /* TypeParameter */) { + this.typeParameters[this.typeParameters.length] = childDecl; + } else { + this.childDecls[this.childDecls.length] = childDecl; + } + + var declName = childDecl.getName(); + var cache = this.getChildDeclCache(childDecl.getKind()); + var childrenOfName = cache[declName]; + if (!childrenOfName) { + childrenOfName = []; + } + + childrenOfName.push(childDecl); + cache[declName] = childrenOfName; + }; + + PullDecl.prototype.searchChildDecls = function (declName, searchKind) { + var cache = (searchKind & TypeScript.PullElementKind.SomeType) ? this.childDeclTypeCache : (searchKind & TypeScript.PullElementKind.SomeContainer) ? this.childDeclNamespaceCache : this.childDeclValueCache; + + var cacheVal = cache[declName]; + + if (cacheVal) { + return cacheVal; + } else { + if (searchKind & TypeScript.PullElementKind.SomeType) { + cacheVal = this.childDeclTypeParameterCache[declName]; + + if (cacheVal) { + return cacheVal; + } + } + + return []; + } + }; + + PullDecl.prototype.getChildDecls = function () { + return this.childDecls; + }; + PullDecl.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + + PullDecl.prototype.addVariableDeclToGroup = function (decl) { + var declGroup = this.declGroups[decl.getName()]; + if (declGroup) { + declGroup.addDecl(decl); + } else { + declGroup = new PullDeclGroup(decl.getName()); + declGroup.addDecl(decl); + this.declGroups[decl.getName()] = declGroup; + } + }; + + PullDecl.prototype.getVariableDeclGroups = function () { + var declGroups = []; + + for (var declName in this.declGroups) { + if (this.declGroups[declName]) { + declGroups[declGroups.length] = this.declGroups[declName].getDecls(); + } + } + + return declGroups; + }; + + PullDecl.prototype.getParentPath = function () { + return this._parentPath; + }; + + PullDecl.prototype.setParentPath = function (path) { + this._parentPath = path; + }; + + PullDecl.prototype.setIsBound = function (isBinding) { + this._isBound = isBinding; + }; + + PullDecl.prototype.isBound = function () { + return this._isBound; + }; + return PullDecl; + })(); + TypeScript.PullDecl = PullDecl; + + var PullFunctionExpressionDecl = (function (_super) { + __extends(PullFunctionExpressionDecl, _super); + function PullFunctionExpressionDecl(expressionName, declFlags, span, scriptName) { + _super.call(this, "", "", 131072 /* FunctionExpression */, declFlags, span, scriptName); + this.functionExpressionName = expressionName; + } + PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { + return this.functionExpressionName; + }; + return PullFunctionExpressionDecl; + })(PullDecl); + TypeScript.PullFunctionExpressionDecl = PullFunctionExpressionDecl; + + var PullDeclGroup = (function () { + function PullDeclGroup(name) { + this.name = name; + this._decls = []; + } + PullDeclGroup.prototype.addDecl = function (decl) { + if (decl.getName() === this.name) { + this._decls[this._decls.length] = decl; + } + }; + + PullDeclGroup.prototype.getDecls = function () { + return this._decls; + }; + return PullDeclGroup; + })(); + TypeScript.PullDeclGroup = PullDeclGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullSymbolID = 0; + TypeScript.lastBoundPullSymbolID = 0; + TypeScript.globalTyvarID = 0; + + var PullSymbol = (function () { + function PullSymbol(name, declKind) { + this.pullSymbolID = TypeScript.pullSymbolID++; + this.outgoingLinks = new TypeScript.LinkList(); + this.incomingLinks = new TypeScript.LinkList(); + this.declarations = new TypeScript.LinkList(); + this.cachedPathIDs = {}; + this.cachedContainerLink = null; + this.cachedTypeLink = null; + this.cachedDeclarations = null; + this.hasBeenResolved = false; + this.isOptional = false; + this.inResolution = false; + this.isSynthesized = false; + this.isBound = false; + this.rebindingID = 0; + this.isVarArg = false; + this.isSpecialized = false; + this.isBeingSpecialized = false; + this.rootSymbol = null; + this.typeChangeUpdateVersion = -1; + this.addUpdateVersion = -1; + this.removeUpdateVersion = -1; + this.docComments = null; + this.isPrinting = false; + this.name = name; + this.declKind = declKind; + } + PullSymbol.prototype.getSymbolID = function () { + return this.pullSymbolID; + }; + + PullSymbol.prototype.isType = function () { + return (this.declKind & TypeScript.PullElementKind.SomeType) != 0; + }; + + PullSymbol.prototype.isSignature = function () { + return (this.declKind & TypeScript.PullElementKind.SomeSignature) != 0; + }; + + PullSymbol.prototype.isArray = function () { + return (this.declKind & 128 /* Array */) != 0; + }; + + PullSymbol.prototype.isPrimitive = function () { + return this.declKind === 2 /* Primitive */; + }; + + PullSymbol.prototype.isAccessor = function () { + return false; + }; + + PullSymbol.prototype.isError = function () { + return false; + }; + + PullSymbol.prototype.isAlias = function () { + return false; + }; + PullSymbol.prototype.isContainer = function () { + return false; + }; + + PullSymbol.prototype.findAliasedType = function (decls) { + for (var i = 0; i < decls.length; i++) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; j++) { + if (childDecls[j].getKind() === 256 /* TypeAlias */) { + var symbol = childDecls[j].getSymbol(); + if (PullContainerTypeSymbol.usedAsSymbol(symbol, this)) { + return symbol; + } + } + } + } + + return null; + }; + + PullSymbol.prototype.getAliasedSymbol = function (scopeSymbol) { + if (!scopeSymbol) { + return null; + } + + var scopePath = scopeSymbol.pathToRoot(); + if (scopePath.length && scopePath[scopePath.length - 1].getKind() === 32 /* DynamicModule */) { + var decls = scopePath[scopePath.length - 1].getDeclarations(); + var symbol = this.findAliasedType(decls); + return symbol; + } + + return null; + }; + + PullSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var symbol = this.getAliasedSymbol(scopeSymbol); + if (symbol) { + return symbol.getName(); + } + + return this.name; + }; + + PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName) { + var symbol = this.getAliasedSymbol(scopeSymbol); + if (symbol) { + return symbol.getDisplayName(); + } + + return this.getDeclarations()[0].getDisplayName(); + }; + + PullSymbol.prototype.getKind = function () { + return this.declKind; + }; + PullSymbol.prototype.setKind = function (declType) { + this.declKind = declType; + }; + + PullSymbol.prototype.setIsOptional = function () { + this.isOptional = true; + }; + PullSymbol.prototype.getIsOptional = function () { + return this.isOptional; + }; + + PullSymbol.prototype.getIsVarArg = function () { + return this.isVarArg; + }; + PullSymbol.prototype.setIsVarArg = function () { + this.isVarArg = true; + }; + + PullSymbol.prototype.setIsSynthesized = function () { + this.isSynthesized = true; + }; + PullSymbol.prototype.getIsSynthesized = function () { + return this.isSynthesized; + }; + + PullSymbol.prototype.setIsSpecialized = function () { + this.isSpecialized = true; + this.isBeingSpecialized = false; + }; + PullSymbol.prototype.getIsSpecialized = function () { + return this.isSpecialized; + }; + PullSymbol.prototype.currentlyBeingSpecialized = function () { + return this.isBeingSpecialized; + }; + PullSymbol.prototype.setIsBeingSpecialized = function () { + this.isBeingSpecialized = true; + }; + PullSymbol.prototype.setValueIsBeingSpecialized = function (val) { + this.isBeingSpecialized = val; + }; + + PullSymbol.prototype.getRootSymbol = function () { + if (!this.rootSymbol) { + return this; + } + return this.rootSymbol; + }; + PullSymbol.prototype.setRootSymbol = function (symbol) { + this.rootSymbol = symbol; + }; + + PullSymbol.prototype.setIsBound = function (rebindingID) { + this.isBound = true; + this.rebindingID = rebindingID; + }; + + PullSymbol.prototype.getRebindingID = function () { + return this.rebindingID; + }; + + PullSymbol.prototype.getIsBound = function () { + return this.isBound; + }; + + PullSymbol.prototype.addCacheID = function (cacheID) { + if (!this.cachedPathIDs[cacheID]) { + this.cachedPathIDs[cacheID] = true; + } + }; + + PullSymbol.prototype.invalidateCachedIDs = function (cache) { + for (var id in this.cachedPathIDs) { + if (cache[id]) { + cache[id] = undefined; + } + } + }; + + PullSymbol.prototype.addDeclaration = function (decl) { + TypeScript.Debug.assert(!!decl); + + if (this.rootSymbol) { + return; + } + + this.declarations.addItem(decl); + + if (!this.cachedDeclarations) { + this.cachedDeclarations = [decl]; + } else { + this.cachedDeclarations[this.cachedDeclarations.length] = decl; + } + }; + + PullSymbol.prototype.getDeclarations = function () { + if (this.rootSymbol) { + return this.rootSymbol.getDeclarations(); + } + + if (!this.cachedDeclarations) { + this.cachedDeclarations = []; + } + + return this.cachedDeclarations; + }; + + PullSymbol.prototype.removeDeclaration = function (decl) { + if (this.rootSymbol) { + return; + } + + this.declarations.remove(function (d) { + return d === decl; + }); + this.cachedDeclarations = this.declarations.find(function (d) { + return d; + }); + }; + + PullSymbol.prototype.updateDeclarations = function (map, context) { + if (this.rootSymbol) { + return; + } + + this.declarations.update(map, context); + }; + + PullSymbol.prototype.addOutgoingLink = function (linkTo, kind) { + var link = new TypeScript.PullSymbolLink(this, linkTo, kind); + this.outgoingLinks.addItem(link); + linkTo.incomingLinks.addItem(link); + + return link; + }; + + PullSymbol.prototype.findOutgoingLinks = function (p) { + return this.outgoingLinks.find(p); + }; + + PullSymbol.prototype.findIncomingLinks = function (p) { + return this.incomingLinks.find(p); + }; + + PullSymbol.prototype.removeOutgoingLink = function (link) { + if (link) { + this.outgoingLinks.remove(function (p) { + return p === link; + }); + + if (link.end.incomingLinks) { + link.end.incomingLinks.remove(function (p) { + return p === link; + }); + } + } + }; + + PullSymbol.prototype.updateOutgoingLinks = function (map, context) { + if (this.outgoingLinks) { + this.outgoingLinks.update(map, context); + } + }; + + PullSymbol.prototype.updateIncomingLinks = function (map, context) { + if (this.incomingLinks) { + this.incomingLinks.update(map, context); + } + }; + + PullSymbol.prototype.removeAllLinks = function () { + var _this = this; + this.updateOutgoingLinks(function (item) { + return _this.removeOutgoingLink(item); + }, null); + this.updateIncomingLinks(function (item) { + return item.start.removeOutgoingLink(item); + }, null); + }; + + PullSymbol.prototype.setContainer = function (containerSymbol) { + var link = this.addOutgoingLink(containerSymbol, 10 /* ContainedBy */); + this.cachedContainerLink = link; + + containerSymbol.addContainedByLink(link); + }; + + PullSymbol.prototype.getContainer = function () { + if (this.cachedContainerLink) { + return this.cachedContainerLink.end; + } + + if (this.getIsSpecialized()) { + var specializations = this.findIncomingLinks(function (symbolLink) { + return symbolLink.kind == 21 /* SpecializedTo */; + }); + if (specializations.length == 1) { + return specializations[0].start.getContainer(); + } + } + + return null; + }; + + PullSymbol.prototype.unsetContainer = function () { + if (this.cachedContainerLink) { + this.removeOutgoingLink(this.cachedContainerLink); + } + + this.invalidate(); + }; + + PullSymbol.prototype.setType = function (typeRef) { + if (this.cachedTypeLink) { + this.unsetType(); + } + + this.cachedTypeLink = this.addOutgoingLink(typeRef, 0 /* TypedAs */); + }; + + PullSymbol.prototype.getType = function () { + if (this.cachedTypeLink) { + return this.cachedTypeLink.end; + } + + return null; + }; + + PullSymbol.prototype.unsetType = function () { + var foundType = false; + + if (this.cachedTypeLink) { + this.removeOutgoingLink(this.cachedTypeLink); + foundType = true; + } + + if (foundType) { + this.invalidate(); + } + }; + + PullSymbol.prototype.isTyped = function () { + return this.getType() != null; + }; + + PullSymbol.prototype.setResolved = function () { + this.hasBeenResolved = true; + this.inResolution = false; + }; + PullSymbol.prototype.isResolved = function () { + return this.hasBeenResolved; + }; + + PullSymbol.prototype.startResolving = function () { + this.inResolution = true; + }; + PullSymbol.prototype.isResolving = function () { + return this.inResolution; + }; + + PullSymbol.prototype.setUnresolved = function () { + this.hasBeenResolved = false; + this.isBound = false; + this.inResolution = false; + }; + + PullSymbol.prototype.invalidate = function () { + this.docComments = null; + + this.hasBeenResolved = false; + this.isBound = false; + + this.declarations.update(function (pullDecl) { + return pullDecl.resetErrors(); + }, null); + }; + + PullSymbol.prototype.hasFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if ((declarations[i].getFlags() & flag) !== 0 /* None */) { + return true; + } + } + return false; + }; + + PullSymbol.prototype.allDeclsHaveFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (!((declarations[i].getFlags() & flag) !== 0 /* None */)) { + return false; + } + } + return true; + }; + + PullSymbol.prototype.pathToRoot = function () { + var path = []; + var node = this; + while (node) { + if (node.isType()) { + var associatedContainerSymbol = (node).getAssociatedContainerType(); + if (associatedContainerSymbol) { + node = associatedContainerSymbol; + } + } + path[path.length] = node; + node = node.getContainer(); + } + return path; + }; + + PullSymbol.prototype.findCommonAncestorPath = function (b) { + var aPath = this.pathToRoot(); + if (aPath.length === 1) { + return aPath; + } + + var bPath; + if (b) { + bPath = b.pathToRoot(); + } else { + return aPath; + } + + var commonNodeIndex = -1; + for (var i = 0, aLen = aPath.length; i < aLen; i++) { + var aNode = aPath[i]; + for (var j = 0, bLen = bPath.length; j < bLen; j++) { + var bNode = bPath[j]; + if (aNode === bNode) { + var aDecl = null; + if (i > 0) { + var decls = aPath[i - 1].getDeclarations(); + if (decls.length) { + aDecl = decls[0].getParentDecl(); + } + } + var bDecl = null; + if (j > 0) { + var decls = bPath[j - 1].getDeclarations(); + if (decls.length) { + bDecl = decls[0].getParentDecl(); + } + } + if (!aDecl || !bDecl || aDecl == bDecl) { + commonNodeIndex = i; + break; + } + } + } + if (commonNodeIndex >= 0) { + break; + } + } + + if (commonNodeIndex >= 0) { + return aPath.slice(0, commonNodeIndex); + } else { + return aPath; + } + }; + + PullSymbol.prototype.toString = function (useConstraintInName) { + var str = this.getNameAndTypeName(); + return str; + }; + + PullSymbol.prototype.getNamePartForFullName = function () { + return this.getDisplayName(null, true); + }; + + PullSymbol.prototype.fullName = function (scopeSymbol) { + var path = this.pathToRoot(); + var fullName = ""; + var aliasedSymbol = this.getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + return aliasedSymbol.getDisplayName(); + } + + for (var i = 1; i < path.length; i++) { + aliasedSymbol = path[i].getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + fullName = aliasedSymbol.getDisplayName() + "." + fullName; + break; + } else { + var scopedName = path[i].getNamePartForFullName(); + if (path[i].getKind() == 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + break; + } + + if (scopedName === "") { + break; + } + + fullName = scopedName + "." + fullName; + } + } + + fullName = fullName + this.getNamePartForFullName(); + return fullName; + }; + + PullSymbol.prototype.getScopedName = function (scopeSymbol, useConstraintInName) { + var path = this.findCommonAncestorPath(scopeSymbol); + var fullName = ""; + var aliasedSymbol = this.getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + return aliasedSymbol.getDisplayName(); + } + + for (var i = 1; i < path.length; i++) { + var kind = path[i].getKind(); + if (kind === 4 /* Container */ || kind === 32 /* DynamicModule */) { + aliasedSymbol = path[i].getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + fullName = aliasedSymbol.getDisplayName() + "." + fullName; + break; + } else if (kind === 4 /* Container */) { + fullName = path[i].getDisplayName() + "." + fullName; + } else { + var displayName = path[i].getDisplayName(); + if (TypeScript.isQuoted(displayName)) { + fullName = displayName + "." + fullName; + } + break; + } + } else { + break; + } + } + fullName = fullName + this.getDisplayName(scopeSymbol, useConstraintInName); + return fullName; + }; + + PullSymbol.prototype.getScopedNameEx = function (scopeSymbol, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo) { + var name = this.getScopedName(scopeSymbol, useConstraintInName); + return TypeScript.MemberName.create(name); + }; + + PullSymbol.prototype.getTypeName = function (scopeSymbol, getPrettyTypeName) { + var memberName = this.getTypeNameEx(scopeSymbol, getPrettyTypeName); + return memberName.toString(); + }; + + PullSymbol.prototype.getTypeNameEx = function (scopeSymbol, getPrettyTypeName) { + var type = this.getType(); + if (type) { + var memberName = getPrettyTypeName ? this.getTypeNameForFunctionSignature("", scopeSymbol, getPrettyTypeName) : null; + if (!memberName) { + memberName = type.getScopedNameEx(scopeSymbol, true, getPrettyTypeName); + } + + return memberName; + } + return TypeScript.MemberName.create(""); + }; + + PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { + var type = this.getType(); + if (type && !type.isNamedTypeSymbol() && this.declKind != 4096 /* Property */ && this.declKind != 1024 /* Variable */ && this.declKind != 2048 /* Parameter */) { + var signatures = type.getCallSignatures(); + var typeName = new TypeScript.MemberNameArray(); + var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); + typeName.addAll(signatureName); + return typeName; + } + + return null; + }; + + PullSymbol.prototype.getNameAndTypeName = function (scopeSymbol) { + var nameAndTypeName = this.getNameAndTypeNameEx(scopeSymbol); + return nameAndTypeName.toString(); + }; + + PullSymbol.prototype.getNameAndTypeNameEx = function (scopeSymbol) { + var type = this.getType(); + var nameEx = this.getScopedNameEx(scopeSymbol); + if (type) { + var nameStr = nameEx.toString() + (this.getIsOptional() ? "?" : ""); + var memberName = this.getTypeNameForFunctionSignature(nameStr, scopeSymbol); + if (!memberName) { + var typeNameEx = type.getScopedNameEx(scopeSymbol); + memberName = TypeScript.MemberName.create(typeNameEx, nameStr + ": ", ""); + } + return memberName; + } + return nameEx; + }; + + PullSymbol.getTypeParameterString = function (typars, scopeSymbol, useContraintInName) { + return PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, undefined, useContraintInName).toString(); + }; + + PullSymbol.getTypeParameterStringEx = function (typeParameters, scopeSymbol, getTypeParamMarkerInfo, useContraintInName) { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = ""; + + if (typeParameters && typeParameters.length) { + builder.add(TypeScript.MemberName.create("<")); + + for (var i = 0; i < typeParameters.length; i++) { + if (i) { + builder.add(TypeScript.MemberName.create(", ")); + } + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + + builder.add(typeParameters[i].getScopedNameEx(scopeSymbol, useContraintInName)); + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + } + + builder.add(TypeScript.MemberName.create(">")); + } + + return builder; + }; + + PullSymbol.getIsExternallyVisible = function (symbol, fromIsExternallyVisibleSymbol, inIsExternallyVisibleSymbols) { + if (inIsExternallyVisibleSymbols) { + for (var i = 0; i < inIsExternallyVisibleSymbols.length; i++) { + if (inIsExternallyVisibleSymbols[i] === symbol) { + return true; + } + } + } else { + inIsExternallyVisibleSymbols = []; + } + + if (fromIsExternallyVisibleSymbol === symbol) { + return true; + } + inIsExternallyVisibleSymbols = inIsExternallyVisibleSymbols.concat(fromIsExternallyVisibleSymbol); + + return symbol.isExternallyVisible(inIsExternallyVisibleSymbols); + }; + + PullSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var kind = this.getKind(); + if (kind === 2 /* Primitive */) { + return true; + } + + if (this.isType()) { + var associatedContainerSymbol = (this).getAssociatedContainerType(); + if (associatedContainerSymbol) { + return PullSymbol.getIsExternallyVisible(associatedContainerSymbol, this, inIsExternallyVisibleSymbols); + } + } + + if (this.hasFlag(2 /* Private */)) { + return false; + } + + var container = this.getContainer(); + if (container === null) { + return true; + } + + if (container.getKind() == 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().getKind() == 32 /* DynamicModule */)) { + var containerTypeSymbol = container.getKind() == 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (PullContainerTypeSymbol.usedAsSymbol(containerTypeSymbol, this)) { + return true; + } + } + + if (!this.hasFlag(1 /* Exported */) && kind != 4096 /* Property */ && kind != 65536 /* Method */) { + return false; + } + + return PullSymbol.getIsExternallyVisible(container, this, inIsExternallyVisibleSymbols); + }; + return PullSymbol; + })(); + TypeScript.PullSymbol = PullSymbol; + + var PullExpressionSymbol = (function (_super) { + __extends(PullExpressionSymbol, _super); + function PullExpressionSymbol() { + _super.call(this, "", 268435456 /* Expression */); + this.contributingSymbols = []; + } + PullExpressionSymbol.prototype.addContributingSymbol = function (symbol) { + var link = this.addOutgoingLink(symbol, 23 /* ContributesToExpression */); + + this.contributingSymbols[this.contributingSymbols.length] = symbol; + }; + + PullExpressionSymbol.prototype.getContributingSymbols = function () { + return this.contributingSymbols; + }; + return PullExpressionSymbol; + })(PullSymbol); + TypeScript.PullExpressionSymbol = PullExpressionSymbol; + + var PullSignatureSymbol = (function (_super) { + __extends(PullSignatureSymbol, _super); + function PullSignatureSymbol(kind) { + _super.call(this, "", kind); + this.parameterLinks = null; + this.typeParameterLinks = null; + this.returnTypeLink = null; + this.hasOptionalParam = false; + this.nonOptionalParamCount = 0; + this.hasVarArgs = false; + this.specializationCache = {}; + this.memberTypeParameterNameCache = null; + this.hasAGenericParameter = false; + this.stringConstantOverload = undefined; + } + PullSignatureSymbol.prototype.isDefinition = function () { + return false; + }; + + PullSignatureSymbol.prototype.hasVariableParamList = function () { + return this.hasVarArgs; + }; + PullSignatureSymbol.prototype.setHasVariableParamList = function () { + this.hasVarArgs = true; + }; + + PullSignatureSymbol.prototype.setHasGenericParameter = function () { + this.hasAGenericParameter = true; + }; + PullSignatureSymbol.prototype.hasGenericParameter = function () { + return this.hasAGenericParameter; + }; + + PullSignatureSymbol.prototype.isGeneric = function () { + return this.hasAGenericParameter || (this.typeParameterLinks && this.typeParameterLinks.length != 0); + }; + + PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { + if (typeof isOptional === "undefined") { isOptional = false; } + if (!this.parameterLinks) { + this.parameterLinks = []; + } + + var link = this.addOutgoingLink(parameter, 13 /* Parameter */); + this.parameterLinks[this.parameterLinks.length] = link; + this.hasOptionalParam = isOptional; + + if (!isOptional) { + this.nonOptionalParamCount++; + } + }; + + PullSignatureSymbol.prototype.addSpecialization = function (signature, typeArguments) { + if (typeArguments && typeArguments.length) { + this.specializationCache[getIDForTypeSubstitutions(typeArguments)] = signature; + } + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArguments) { + if (typeArguments) { + var sig = this.specializationCache[getIDForTypeSubstitutions(typeArguments)]; + + if (sig) { + return sig; + } + } + + return null; + }; + + PullSignatureSymbol.prototype.addTypeParameter = function (parameter) { + if (!this.typeParameterLinks) { + this.typeParameterLinks = []; + } + + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + } + + var link = this.addOutgoingLink(parameter, 18 /* TypeParameter */); + this.typeParameterLinks[this.typeParameterLinks.length] = link; + + this.memberTypeParameterNameCache[link.end.getName()] = link.end; + }; + + PullSignatureSymbol.prototype.getNonOptionalParameterCount = function () { + return this.nonOptionalParamCount; + }; + + PullSignatureSymbol.prototype.setReturnType = function (returnType) { + if (returnType) { + if (this.returnTypeLink) { + this.removeOutgoingLink(this.returnTypeLink); + } + this.returnTypeLink = this.addOutgoingLink(returnType, 14 /* ReturnType */); + } + }; + + PullSignatureSymbol.prototype.getParameters = function () { + var params = []; + + if (this.parameterLinks) { + for (var i = 0; i < this.parameterLinks.length; i++) { + params[params.length] = this.parameterLinks[i].end; + } + } + + return params; + }; + + PullSignatureSymbol.prototype.getTypeParameters = function () { + var params = []; + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + params[params.length] = this.typeParameterLinks[i].end; + } + } + + return params; + }; + + PullSignatureSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + this.memberTypeParameterNameCache[this.typeParameterLinks[i].end.getName()] = this.typeParameterLinks[i].end; + } + } + } + + memberSymbol = this.memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullSignatureSymbol.prototype.removeParameter = function (parameterSymbol) { + var paramLink; + + if (this.parameterLinks) { + for (var i = 0; i < this.parameterLinks.length; i++) { + if (parameterSymbol === this.parameterLinks[i].end) { + paramLink = this.parameterLinks[i]; + this.removeOutgoingLink(paramLink); + break; + } + } + } + + this.invalidate(); + }; + + PullSignatureSymbol.prototype.mimicSignature = function (signature, resolver) { + var typeParameters = signature.getTypeParameters(); + var typeParameter; + + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + } + + var parameters = signature.getParameters(); + var parameter; + + if (parameters) { + for (var j = 0; j < parameters.length; j++) { + parameter = new PullSymbol(parameters[j].getName(), 2048 /* Parameter */); + parameter.setRootSymbol(parameters[j]); + + if (parameters[j].getIsOptional()) { + parameter.setIsOptional(); + } + if (parameters[j].getIsVarArg()) { + parameter.setIsVarArg(); + this.setHasVariableParamList(); + } + this.addParameter(parameter); + } + } + + var returnType = signature.getReturnType(); + + if (!resolver.isTypeArgumentOrWrapper(returnType)) { + this.setReturnType(returnType); + } + }; + + PullSignatureSymbol.prototype.getReturnType = function () { + if (this.returnTypeLink) { + return this.returnTypeLink.end; + } else { + var rtl = this.findOutgoingLinks(function (p) { + return p.kind === 14 /* ReturnType */; + }); + + if (rtl.length) { + this.returnTypeLink = rtl[0]; + return this.returnTypeLink.end; + } + + return null; + } + }; + + PullSignatureSymbol.prototype.parametersAreFixed = function () { + if (!this.isGeneric()) { + return true; + } + + if (this.parameterLinks) { + var paramType; + for (var i = 0; i < this.parameterLinks.length; i++) { + paramType = this.parameterLinks[i].end.getType(); + + if (paramType && !paramType.isFixed()) { + return false; + } + } + } + + return true; + }; + + PullSignatureSymbol.prototype.isFixed = function () { + if (!this.isGeneric()) { + return true; + } + + if (this.parameterLinks) { + var parameterType = null; + + for (var i = 0; i < this.parameterLinks.length; i++) { + parameterType = this.parameterLinks[i].end.getType(); + + if (parameterType && !parameterType.isFixed()) { + return false; + } + } + } + + if (this.returnTypeLink) { + var returnType = this.returnTypeLink.end; + + return returnType.isFixed(); + } + + return true; + }; + + PullSignatureSymbol.prototype.invalidate = function () { + this.parameterLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 13 /* Parameter */; + }); + this.nonOptionalParamCount = 0; + this.hasOptionalParam = false; + this.hasAGenericParameter = false; + this.stringConstantOverload = undefined; + + if (this.parameterLinks) { + for (var i = 0; i < this.parameterLinks.length; i++) { + this.parameterLinks[i].end.invalidate(); + + if (!this.parameterLinks[i].end.getIsOptional()) { + this.nonOptionalParamCount++; + } else { + this.hasOptionalParam; + break; + } + } + } + + _super.prototype.invalidate.call(this); + }; + + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { + if (this.stringConstantOverload === undefined) { + var params = this.getParameters(); + this.stringConstantOverload = false; + for (var i = 0; i < params.length; i++) { + var paramType = params[i].getType(); + if (paramType && paramType.isPrimitive() && (paramType).isStringConstant()) { + this.stringConstantOverload = true; + } + } + } + + return this.stringConstantOverload; + }; + + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { + var allMemberNames = new TypeScript.MemberNameArray(); + var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); + allMemberNames.addAll(signatureMemberName); + return allMemberNames; + }; + + PullSignatureSymbol.getSignaturesTypeNameEx = function (signatures, prefix, shortform, brackets, scopeSymbol, getPrettyTypeName, candidateSignature) { + var result = []; + var len = signatures.length; + if (!getPrettyTypeName && len > 1) { + shortform = false; + } + + var foundDefinition = false; + if (candidateSignature && candidateSignature.isDefinition() && len > 1) { + candidateSignature = null; + } + + for (var i = 0; i < len; i++) { + if (len > 1 && signatures[i].isDefinition()) { + foundDefinition = true; + continue; + } + + var signature = signatures[i]; + if (getPrettyTypeName && candidateSignature) { + signature = candidateSignature; + } + + result.push(signature.getSignatureTypeNameEx(prefix, shortform, brackets, scopeSymbol)); + if (getPrettyTypeName) { + break; + } + } + + if (getPrettyTypeName && result.length && len > 1) { + var lastMemberName = result[result.length - 1]; + for (var i = i + 1; i < len; i++) { + if (signatures[i].isDefinition()) { + foundDefinition = true; + break; + } + } + var overloadString = " (+ " + (foundDefinition ? len - 2 : len - 1) + " overload(s))"; + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + + return result; + }; + + PullSignatureSymbol.prototype.toString = function (useConstraintInName) { + var s = this.getSignatureTypeNameEx(this.getScopedNameEx().toString(), false, false, undefined, undefined, useConstraintInName).toString(); + return s; + }; + + PullSignatureSymbol.prototype.getSignatureTypeNameEx = function (prefix, shortform, brackets, scopeSymbol, getParamMarkerInfo, getTypeParamMarkerInfo) { + var typeParamterBuilder = new TypeScript.MemberNameArray(); + + typeParamterBuilder.add(PullSymbol.getTypeParameterStringEx(this.getTypeParameters(), scopeSymbol, getTypeParamMarkerInfo, true)); + + if (brackets) { + typeParamterBuilder.add(TypeScript.MemberName.create("[")); + } else { + typeParamterBuilder.add(TypeScript.MemberName.create("(")); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = prefix; + + if (getTypeParamMarkerInfo) { + builder.prefix = prefix; + builder.addAll(typeParamterBuilder.entries); + } else { + builder.prefix = prefix + typeParamterBuilder.toString(); + } + + var params = this.getParameters(); + var paramLen = params.length; + for (var i = 0; i < paramLen; i++) { + var paramType = params[i].getType(); + var typeString = paramType ? ": " : ""; + var paramIsVarArg = params[i].getIsVarArg(); + var varArgPrefix = paramIsVarArg ? "..." : ""; + var optionalString = (!paramIsVarArg && params[i].getIsOptional()) ? "?" : ""; + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + builder.add(TypeScript.MemberName.create(varArgPrefix + params[i].getScopedNameEx(scopeSymbol).toString() + optionalString + typeString)); + if (paramType) { + builder.add(paramType.getScopedNameEx(scopeSymbol)); + } + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + if (i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + + if (shortform) { + if (brackets) { + builder.add(TypeScript.MemberName.create("] => ")); + } else { + builder.add(TypeScript.MemberName.create(") => ")); + } + } else { + if (brackets) { + builder.add(TypeScript.MemberName.create("]: ")); + } else { + builder.add(TypeScript.MemberName.create("): ")); + } + } + + var returnType = this.getReturnType(); + + if (returnType) { + builder.add(returnType.getScopedNameEx(scopeSymbol)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + + return builder; + }; + return PullSignatureSymbol; + })(PullSymbol); + TypeScript.PullSignatureSymbol = PullSignatureSymbol; + + var PullTypeSymbol = (function (_super) { + __extends(PullTypeSymbol, _super); + function PullTypeSymbol() { + _super.apply(this, arguments); + this.memberLinks = null; + this.typeParameterLinks = null; + this.specializationLinks = null; + this.containedByLinks = null; + this.memberNameCache = null; + this.memberTypeNameCache = null; + this.memberTypeParameterNameCache = null; + this.containedMemberCache = null; + this.typeArguments = null; + this.specializedTypeCache = null; + this.memberCache = null; + this.implementedTypeLinks = null; + this.extendedTypeLinks = null; + this.callSignatureLinks = null; + this.constructSignatureLinks = null; + this.indexSignatureLinks = null; + this.arrayType = null; + this.hasGenericSignature = false; + this.hasGenericMember = false; + this.knownBaseTypeCount = 0; + this._hasBaseTypeConflict = false; + this.invalidatedSpecializations = false; + this.associatedContainerTypeSymbol = null; + this.constructorMethod = null; + this.hasDefaultConstructor = false; + } + PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { + return this.knownBaseTypeCount; + }; + PullTypeSymbol.prototype.resetKnownBaseTypeCount = function () { + this.knownBaseTypeCount = 0; + }; + PullTypeSymbol.prototype.incrementKnownBaseCount = function () { + this.knownBaseTypeCount++; + }; + PullTypeSymbol.prototype.setHasBaseTypeConflict = function () { + this._hasBaseTypeConflict = true; + }; + PullTypeSymbol.prototype.hasBaseTypeConflict = function () { + return this._hasBaseTypeConflict; + }; + + PullTypeSymbol.prototype.setUnresolved = function () { + _super.prototype.setUnresolved.call(this); + + var specializations = this.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].setUnresolved(); + } + }; + + PullTypeSymbol.prototype.isType = function () { + return true; + }; + PullTypeSymbol.prototype.isClass = function () { + return this.getKind() == 8 /* Class */ || (this.constructorMethod != null); + }; + + PullTypeSymbol.prototype.hasMembers = function () { + var thisHasMembers = this.memberLinks && this.memberLinks.length != 0; + + if (thisHasMembers) { + return true; + } + + var parents = this.getExtendedTypes(); + + for (var i = 0; i < parents.length; i++) { + if (parents[i].hasMembers()) { + return true; + } + } + + return false; + }; + PullTypeSymbol.prototype.isFunction = function () { + return false; + }; + PullTypeSymbol.prototype.isConstructor = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeParameter = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeVariable = function () { + return false; + }; + PullTypeSymbol.prototype.isError = function () { + return false; + }; + + PullTypeSymbol.prototype.setHasGenericSignature = function () { + this.hasGenericSignature = true; + }; + PullTypeSymbol.prototype.getHasGenericSignature = function () { + return this.hasGenericSignature; + }; + + PullTypeSymbol.prototype.setHasGenericMember = function () { + this.hasGenericMember = true; + }; + PullTypeSymbol.prototype.getHasGenericMember = function () { + return this.hasGenericMember; + }; + + PullTypeSymbol.prototype.setAssociatedContainerType = function (type) { + this.associatedContainerTypeSymbol = type; + }; + + PullTypeSymbol.prototype.getAssociatedContainerType = function () { + return this.associatedContainerTypeSymbol; + }; + + PullTypeSymbol.prototype.getType = function () { + return this; + }; + + PullTypeSymbol.prototype.getArrayType = function () { + return this.arrayType; + }; + + PullTypeSymbol.prototype.getElementType = function () { + var arrayOfLinks = this.findOutgoingLinks(function (link) { + return link.kind === 4 /* ArrayOf */; + }); + + if (arrayOfLinks.length) { + return arrayOfLinks[0].end; + } + + return null; + }; + PullTypeSymbol.prototype.setArrayType = function (arrayType) { + this.arrayType = arrayType; + + arrayType.addOutgoingLink(this, 4 /* ArrayOf */); + }; + + PullTypeSymbol.prototype.addContainedByLink = function (containedByLink) { + if (!this.containedByLinks) { + this.containedByLinks = []; + } + + if (!this.containedMemberCache) { + this.containedMemberCache = new TypeScript.BlockIntrinsics(); + } + + this.containedByLinks[this.containedByLinks.length] = containedByLink; + this.containedMemberCache[containedByLink.start.getName()] = containedByLink.start; + }; + + PullTypeSymbol.prototype.findContainedMember = function (name) { + if (!this.containedByLinks) { + this.containedByLinks = this.findIncomingLinks(function (psl) { + return psl.kind === 10 /* ContainedBy */; + }); + this.containedMemberCache = new TypeScript.BlockIntrinsics(); + + for (var i = 0; i < this.containedByLinks.length; i++) { + this.containedMemberCache[this.containedByLinks[i].start.getName()] = this.containedByLinks[i].start; + } + } + + return this.containedMemberCache[name]; + }; + + PullTypeSymbol.prototype.addMember = function (memberSymbol, linkKind, doNotChangeContainer) { + var link = this.addOutgoingLink(memberSymbol, linkKind); + + if (!doNotChangeContainer) { + memberSymbol.setContainer(this); + } + + if (!this.memberLinks) { + this.memberLinks = []; + } + + if (!this.memberCache || !this.memberNameCache) { + this.populateMemberCache(); + } + + if (!memberSymbol.isType()) { + this.memberLinks[this.memberLinks.length] = link; + + this.memberCache[this.memberCache.length] = memberSymbol; + + if (!this.memberNameCache) { + this.populateMemberCache(); + } + this.memberNameCache[memberSymbol.getName()] = memberSymbol; + } else { + if ((memberSymbol).isTypeParameter()) { + if (!this.typeParameterLinks) { + this.typeParameterLinks = []; + } + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + } + this.typeParameterLinks[this.typeParameterLinks.length] = link; + this.memberTypeParameterNameCache[memberSymbol.getName()] = memberSymbol; + } else { + if (!this.memberTypeNameCache) { + this.memberTypeNameCache = new TypeScript.BlockIntrinsics(); + } + this.memberLinks[this.memberLinks.length] = link; + this.memberTypeNameCache[memberSymbol.getName()] = memberSymbol; + this.memberCache[this.memberCache.length] = memberSymbol; + } + } + }; + + PullTypeSymbol.prototype.removeMember = function (memberSymbol) { + var memberLink; + var child; + + var links = (memberSymbol.isType() && (memberSymbol).isTypeParameter()) ? this.typeParameterLinks : this.memberLinks; + + if (links) { + for (var i = 0; i < links.length; i++) { + if (memberSymbol === links[i].end) { + memberLink = links[i]; + child = memberLink.end; + child.unsetContainer(); + this.removeOutgoingLink(memberLink); + break; + } + } + } + + this.invalidate(); + }; + + PullTypeSymbol.prototype.getMembers = function () { + if (this.memberCache) { + return this.memberCache; + } else { + var members = []; + + if (this.memberLinks) { + for (var i = 0; i < this.memberLinks.length; i++) { + members[members.length] = this.memberLinks[i].end; + } + } + + if (members.length) { + this.memberCache = members; + } + + return members; + } + }; + + PullTypeSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + this.hasDefaultConstructor = hasOne; + }; + + PullTypeSymbol.prototype.getHasDefaultConstructor = function () { + return this.hasDefaultConstructor; + }; + + PullTypeSymbol.prototype.getConstructorMethod = function () { + return this.constructorMethod; + }; + + PullTypeSymbol.prototype.setConstructorMethod = function (constructorMethod) { + this.constructorMethod = constructorMethod; + }; + + PullTypeSymbol.prototype.getTypeParameters = function () { + var members = []; + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + members[members.length] = this.typeParameterLinks[i].end; + } + } + + return members; + }; + + PullTypeSymbol.prototype.isGeneric = function () { + return (this.typeParameterLinks && this.typeParameterLinks.length != 0) || this.hasGenericSignature || this.hasGenericMember || (this.typeArguments && this.typeArguments.length); + }; + + PullTypeSymbol.prototype.isFixed = function () { + if (!this.isGeneric()) { + return true; + } + + if (this.typeParameterLinks && this.typeArguments) { + if (!this.typeArguments.length || this.typeArguments.length < this.typeParameterLinks.length) { + return false; + } + + for (var i = 0; i < this.typeArguments.length; i++) { + if (!this.typeArguments[i].isFixed()) { + return false; + } + } + + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { + if (!substitutingTypes || !substitutingTypes.length) { + return; + } + + if (!this.specializedTypeCache) { + this.specializedTypeCache = new TypeScript.BlockIntrinsics(); + } + + if (!this.specializationLinks) { + this.specializationLinks = []; + } + + this.specializationLinks[this.specializationLinks.length] = this.addOutgoingLink(specializedVersionOfThisType, 21 /* SpecializedTo */); + + this.specializedTypeCache[getIDForTypeSubstitutions(substitutingTypes)] = specializedVersionOfThisType; + }; + + PullTypeSymbol.prototype.getSpecialization = function (substitutingTypes) { + if (!substitutingTypes || !substitutingTypes.length) { + return null; + } + + if (!this.specializedTypeCache) { + this.specializedTypeCache = new TypeScript.BlockIntrinsics(); + + return null; + } + + var specialization = this.specializedTypeCache[getIDForTypeSubstitutions(substitutingTypes)]; + + if (!specialization) { + return null; + } + + return specialization; + }; + + PullTypeSymbol.prototype.getKnownSpecializations = function () { + var specializations = []; + + if (this.specializedTypeCache) { + for (var specializationID in this.specializedTypeCache) { + if (this.specializedTypeCache[specializationID]) { + specializations[specializations.length] = this.specializedTypeCache[specializationID]; + } + } + } + + return specializations; + }; + + PullTypeSymbol.prototype.invalidateSpecializations = function () { + if (this.invalidatedSpecializations) { + return; + } + + var specializations = this.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + + if (this.specializationLinks && this.specializationLinks.length) { + for (var i = 0; i < this.specializationLinks.length; i++) { + this.removeOutgoingLink(this.specializationLinks[i]); + } + } + + this.specializationLinks = null; + + this.specializedTypeCache = null; + + this.invalidatedSpecializations = true; + }; + + PullTypeSymbol.prototype.removeSpecialization = function (specializationType) { + if (this.specializationLinks && this.specializationLinks.length) { + for (var i = 0; i < this.specializationLinks.length; i++) { + if (this.specializationLinks[i].end === specializationType) { + this.removeOutgoingLink(this.specializationLinks[i]); + break; + } + } + } + + if (this.specializedTypeCache) { + for (var specializationID in this.specializedTypeCache) { + if (this.specializedTypeCache[specializationID] === specializationType) { + this.specializedTypeCache[specializationID] = undefined; + } + } + } + }; + + PullTypeSymbol.prototype.getTypeArguments = function () { + return this.typeArguments; + }; + PullTypeSymbol.prototype.setTypeArguments = function (typeArgs) { + this.typeArguments = typeArgs; + }; + + PullTypeSymbol.prototype.addCallSignature = function (callSignature) { + if (!this.callSignatureLinks) { + this.callSignatureLinks = []; + } + + var link = this.addOutgoingLink(callSignature, 15 /* CallSignature */); + this.callSignatureLinks[this.callSignatureLinks.length] = link; + + if (callSignature.isGeneric()) { + this.hasGenericSignature = true; + } + }; + + PullTypeSymbol.prototype.addCallSignatures = function (callSignatures) { + if (!this.callSignatureLinks) { + this.callSignatureLinks = []; + } + + for (var i = 0; i < callSignatures.length; i++) { + this.addCallSignature(callSignatures[i]); + } + }; + + PullTypeSymbol.prototype.addConstructSignature = function (constructSignature) { + if (!this.constructSignatureLinks) { + this.constructSignatureLinks = []; + } + + var link = this.addOutgoingLink(constructSignature, 16 /* ConstructSignature */); + this.constructSignatureLinks[this.constructSignatureLinks.length] = link; + + if (constructSignature.isGeneric()) { + this.hasGenericSignature = true; + } + }; + + PullTypeSymbol.prototype.addConstructSignatures = function (constructSignatures) { + if (!this.constructSignatureLinks) { + this.constructSignatureLinks = []; + } + + for (var i = 0; i < constructSignatures.length; i++) { + this.addConstructSignature(constructSignatures[i]); + } + }; + + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { + if (!this.indexSignatureLinks) { + this.indexSignatureLinks = []; + } + + var link = this.addOutgoingLink(indexSignature, 17 /* IndexSignature */); + this.indexSignatureLinks[this.indexSignatureLinks.length] = link; + + if (indexSignature.isGeneric()) { + this.hasGenericSignature = true; + } + }; + + PullTypeSymbol.prototype.addIndexSignatures = function (indexSignatures) { + if (!this.indexSignatureLinks) { + this.indexSignatureLinks = []; + } + + for (var i = 0; i < indexSignatures.length; i++) { + this.addIndexSignature(indexSignatures[i]); + } + }; + + PullTypeSymbol.prototype.hasOwnCallSignatures = function () { + return !!this.callSignatureLinks; + }; + + PullTypeSymbol.prototype.getCallSignatures = function (collectBaseSignatures) { + if (typeof collectBaseSignatures === "undefined") { collectBaseSignatures = true; } + var members = []; + + if (this.callSignatureLinks) { + for (var i = 0; i < this.callSignatureLinks.length; i++) { + members[members.length] = this.callSignatureLinks[i].end; + } + } + + if (collectBaseSignatures) { + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(this)) { + continue; + } + members = members.concat(extendedTypes[i].getCallSignatures()); + } + } + + return members; + }; + + PullTypeSymbol.prototype.hasOwnConstructSignatures = function () { + return !!this.constructSignatureLinks; + }; + + PullTypeSymbol.prototype.getConstructSignatures = function (collectBaseSignatures) { + if (typeof collectBaseSignatures === "undefined") { collectBaseSignatures = true; } + var members = []; + + if (this.constructSignatureLinks) { + for (var i = 0; i < this.constructSignatureLinks.length; i++) { + members[members.length] = this.constructSignatureLinks[i].end; + } + } + + if (collectBaseSignatures) { + if (!(this.getKind() == 33554432 /* ConstructorType */)) { + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(this)) { + continue; + } + members = members.concat(extendedTypes[i].getConstructSignatures()); + } + } + } + + return members; + }; + + PullTypeSymbol.prototype.hasOwnIndexSignatures = function () { + return !!this.indexSignatureLinks; + }; + + PullTypeSymbol.prototype.getIndexSignatures = function (collectBaseSignatures) { + if (typeof collectBaseSignatures === "undefined") { collectBaseSignatures = true; } + var members = []; + + if (this.indexSignatureLinks) { + for (var i = 0; i < this.indexSignatureLinks.length; i++) { + members[members.length] = this.indexSignatureLinks[i].end; + } + } + + if (collectBaseSignatures) { + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(this)) { + continue; + } + members = members.concat(extendedTypes[i].getIndexSignatures()); + } + } + + return members; + }; + + PullTypeSymbol.prototype.removeCallSignature = function (signature, invalidate) { + if (typeof invalidate === "undefined") { invalidate = true; } + var signatureLink; + + if (this.callSignatureLinks) { + for (var i = 0; i < this.callSignatureLinks.length; i++) { + if (signature === this.callSignatureLinks[i].end) { + signatureLink = this.callSignatureLinks[i]; + this.removeOutgoingLink(signatureLink); + break; + } + } + } + + if (invalidate) { + this.invalidate(); + } + }; + + PullTypeSymbol.prototype.recomputeCallSignatures = function () { + this.callSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 15 /* CallSignature */; + }); + }; + + PullTypeSymbol.prototype.removeConstructSignature = function (signature, invalidate) { + if (typeof invalidate === "undefined") { invalidate = true; } + var signatureLink; + + if (this.constructSignatureLinks) { + for (var i = 0; i < this.constructSignatureLinks.length; i++) { + if (signature === this.constructSignatureLinks[i].end) { + signatureLink = this.constructSignatureLinks[i]; + this.removeOutgoingLink(signatureLink); + break; + } + } + } + + if (invalidate) { + this.invalidate(); + } + }; + + PullTypeSymbol.prototype.recomputeConstructSignatures = function () { + this.constructSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 16 /* ConstructSignature */; + }); + }; + + PullTypeSymbol.prototype.removeIndexSignature = function (signature, invalidate) { + if (typeof invalidate === "undefined") { invalidate = true; } + var signatureLink; + + if (this.indexSignatureLinks) { + for (var i = 0; i < this.indexSignatureLinks.length; i++) { + if (signature === this.indexSignatureLinks[i].end) { + signatureLink = this.indexSignatureLinks[i]; + this.removeOutgoingLink(signatureLink); + break; + } + } + } + + if (invalidate) { + this.invalidate(); + } + }; + + PullTypeSymbol.prototype.recomputeIndexSignatures = function () { + this.indexSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 17 /* IndexSignature */; + }); + }; + + PullTypeSymbol.prototype.addImplementedType = function (interfaceType) { + if (!this.implementedTypeLinks) { + this.implementedTypeLinks = []; + } + + var link = this.addOutgoingLink(interfaceType, 12 /* Implements */); + this.implementedTypeLinks[this.implementedTypeLinks.length] = link; + }; + + PullTypeSymbol.prototype.getImplementedTypes = function () { + var members = []; + + if (this.implementedTypeLinks) { + for (var i = 0; i < this.implementedTypeLinks.length; i++) { + members[members.length] = this.implementedTypeLinks[i].end; + } + } + + return members; + }; + + PullTypeSymbol.prototype.removeImplementedType = function (implementedType) { + var typeLink; + + if (this.implementedTypeLinks) { + for (var i = 0; i < this.implementedTypeLinks.length; i++) { + if (implementedType === this.implementedTypeLinks[i].end) { + typeLink = this.implementedTypeLinks[i]; + this.removeOutgoingLink(typeLink); + break; + } + } + } + + this.invalidate(); + }; + + PullTypeSymbol.prototype.addExtendedType = function (extendedType) { + if (!this.extendedTypeLinks) { + this.extendedTypeLinks = []; + } + + var link = this.addOutgoingLink(extendedType, 11 /* Extends */); + this.extendedTypeLinks[this.extendedTypeLinks.length] = link; + }; + + PullTypeSymbol.prototype.getExtendedTypes = function () { + var members = []; + + if (this.extendedTypeLinks) { + for (var i = 0; i < this.extendedTypeLinks.length; i++) { + members[members.length] = this.extendedTypeLinks[i].end; + } + } + + return members; + }; + + PullTypeSymbol.prototype.hasBase = function (potentialBase, origin) { + if (typeof origin === "undefined") { origin = null; } + if (this === potentialBase) { + return true; + } + + if (origin && (this === origin || this.getRootSymbol() === origin)) { + return true; + } + + if (!origin) { + origin = this; + } + + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(potentialBase, origin)) { + return true; + } + } + + var implementedTypes = this.getImplementedTypes(); + + for (var i = 0; i < implementedTypes.length; i++) { + if (implementedTypes[i].hasBase(potentialBase, origin)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + if (baseType.isError()) { + return false; + } + + var thisIsClass = this.isClass(); + if (isExtendedType) { + if (thisIsClass) { + return baseType.getKind() === 8 /* Class */; + } + } else { + if (!thisIsClass) { + return false; + } + } + + return !!(baseType.getKind() & (16 /* Interface */ | 8 /* Class */ | 128 /* Array */)); + }; + + PullTypeSymbol.prototype.removeExtendedType = function (extendedType) { + var typeLink; + + if (this.extendedTypeLinks) { + for (var i = 0; i < this.extendedTypeLinks.length; i++) { + if (extendedType === this.extendedTypeLinks[i].end) { + typeLink = this.extendedTypeLinks[i]; + this.removeOutgoingLink(typeLink); + break; + } + } + } + + this.invalidate(); + }; + + PullTypeSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + var memberSymbol; + + if (!this.memberNameCache) { + this.populateMemberCache(); + } + + memberSymbol = this.memberNameCache[name]; + + if (!lookInParent) { + return memberSymbol; + } else if (memberSymbol) { + return memberSymbol; + } + + if (!memberSymbol && this.extendedTypeLinks) { + for (var i = 0; i < this.extendedTypeLinks.length; i++) { + memberSymbol = (this.extendedTypeLinks[i].end).findMember(name); + + if (memberSymbol) { + return memberSymbol; + } + } + } + + return this.findNestedType(name); + }; + + PullTypeSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this.memberTypeNameCache) { + this.populateMemberTypeCache(); + } + + memberSymbol = this.memberTypeNameCache[name]; + + if (memberSymbol && kind != 0 /* None */) { + memberSymbol = ((memberSymbol.getKind() & kind) != 0) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.populateMemberCache = function () { + if (!this.memberNameCache || !this.memberCache) { + this.memberNameCache = new TypeScript.BlockIntrinsics(); + this.memberCache = []; + + if (this.memberLinks) { + for (var i = 0; i < this.memberLinks.length; i++) { + this.memberNameCache[this.memberLinks[i].end.getName()] = this.memberLinks[i].end; + this.memberCache[this.memberCache.length] = this.memberLinks[i].end; + } + } + } + }; + + PullTypeSymbol.prototype.populateMemberTypeCache = function () { + if (!this.memberTypeNameCache) { + this.memberTypeNameCache = new TypeScript.BlockIntrinsics(); + + var setAll = false; + + if (!this.memberCache) { + this.memberCache = []; + this.memberNameCache = new TypeScript.BlockIntrinsics(); + setAll = true; + } + + if (this.memberLinks) { + for (var i = 0; i < this.memberLinks.length; i++) { + if (this.memberLinks[i].end.isType()) { + this.memberTypeNameCache[this.memberLinks[i].end.getName()] = this.memberLinks[i].end; + this.memberCache[this.memberCache.length] = this.memberLinks[i].end; + } else if (setAll) { + this.memberNameCache[this.memberLinks[i].end.getName()] = this.memberLinks[i].end; + this.memberCache[this.memberCache.length] = this.memberLinks[i].end; + } + } + } + } + }; + + PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, includePrivate) { + var allMembers = []; + var i = 0; + var j = 0; + var m = 0; + var n = 0; + + if (!this.memberCache) { + this.populateMemberCache(); + } + + if (!this.memberTypeNameCache) { + this.populateMemberTypeCache(); + } + + if (!this.memberNameCache) { + this.populateMemberCache(); + } + + for (var i = 0, n = this.memberCache.length; i < n; i++) { + var member = this.memberCache[i]; + if ((member.getKind() & searchDeclKind) && (includePrivate || !member.hasFlag(2 /* Private */))) { + allMembers[allMembers.length] = member; + } + } + + if (this.extendedTypeLinks) { + for (var i = 0, n = this.extendedTypeLinks.length; i < n; i++) { + var extendedMembers = (this.extendedTypeLinks[i].end).getAllMembers(searchDeclKind, includePrivate); + + for (var j = 0, m = extendedMembers.length; j < m; j++) { + var extendedMember = extendedMembers[j]; + if (!this.memberNameCache[extendedMember.getName()]) { + allMembers[allMembers.length] = extendedMember; + } + } + } + } + + return allMembers; + }; + + PullTypeSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + this.memberTypeParameterNameCache[this.typeParameterLinks[i].end.getName()] = this.typeParameterLinks[i].end; + } + } + } + + memberSymbol = this.memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullTypeSymbol.prototype.cleanTypeParameters = function () { + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + this.removeOutgoingLink(this.typeParameterLinks[i]); + } + } + + this.typeParameterLinks = null; + this.memberTypeParameterNameCache = null; + }; + + PullTypeSymbol.prototype.setResolved = function () { + this.invalidatedSpecializations = true; + _super.prototype.setResolved.call(this); + }; + + PullTypeSymbol.prototype.invalidate = function () { + if (this.constructorMethod) { + this.constructorMethod.invalidate(); + } + + this.memberNameCache = null; + this.memberCache = null; + this.memberTypeNameCache = null; + this.containedMemberCache = null; + + this.invalidatedSpecializations = false; + + this.containedByLinks = null; + + this.memberLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 6 /* PrivateMember */ || psl.kind === 5 /* PublicMember */; + }); + + this.typeParameterLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 18 /* TypeParameter */; + }); + + this.callSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 15 /* CallSignature */; + }); + + this.constructSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 16 /* ConstructSignature */; + }); + + this.indexSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 17 /* IndexSignature */; + }); + + this.implementedTypeLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 12 /* Implements */; + }); + + this.extendedTypeLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 11 /* Extends */; + }); + + this.knownBaseTypeCount = 0; + + _super.prototype.invalidate.call(this); + }; + + PullTypeSymbol.prototype.getNamePartForFullName = function () { + var name = _super.prototype.getNamePartForFullName.call(this); + + var typars = this.getTypeArguments(); + if (!typars || !typars.length) { + typars = this.getTypeParameters(); + } + + var typarString = PullSymbol.getTypeParameterString(typars, this, true); + return name + typarString; + }; + + PullTypeSymbol.prototype.getScopedName = function (scopeSymbol, useConstraintInName) { + return this.getScopedNameEx(scopeSymbol, useConstraintInName).toString(); + }; + + PullTypeSymbol.prototype.isNamedTypeSymbol = function () { + var kind = this.getKind(); + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 256 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.getName() != "")) { + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.toString = function (useConstraintInName) { + var s = this.getScopedNameEx(null, useConstraintInName).toString(); + return s; + }; + + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo) { + if (!this.isNamedTypeSymbol()) { + return this.getMemberTypeNameEx(true, scopeSymbol, getPrettyTypeName); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = _super.prototype.getScopedName.call(this, scopeSymbol, useConstraintInName); + + var typars = this.getTypeArguments(); + if (!typars || !typars.length) { + typars = this.getTypeParameters(); + } + + builder.add(PullSymbol.getTypeParameterStringEx(typars, this, getTypeParamMarkerInfo, useConstraintInName)); + + return builder; + }; + + PullTypeSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + return members.length === 0 && constructSignatures.length === 0 && callSignatures.length > 1; + }; + + PullTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + var indexSignatures = this.getIndexSignatures(); + + if (members.length > 0 || callSignatures.length > 0 || constructSignatures.length > 0 || indexSignatures.length > 0) { + var allMemberNames = new TypeScript.MemberNameArray(); + var curlies = !topLevel || indexSignatures.length != 0; + var delim = "; "; + for (var i = 0; i < members.length; i++) { + var memberTypeName = members[i].getNameAndTypeNameEx(scopeSymbol); + + if (memberTypeName.isArray() && (memberTypeName).delim === delim) { + allMemberNames.addAll((memberTypeName).entries); + } else { + allMemberNames.add(memberTypeName); + } + curlies = true; + } + + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.hasOnlyOverloadCallSignatures(); + + var signatureCount = callSignatures.length + constructSignatures.length + indexSignatures.length; + if (signatureCount != 0 || members.length != 0) { + var useShortFormSignature = !curlies && (signatureCount === 1); + var signatureMemberName; + + if (callSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(callSignatures, "", useShortFormSignature, false, scopeSymbol, getPrettyFunctionOverload); + allMemberNames.addAll(signatureMemberName); + } + + if (constructSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(constructSignatures, "new", useShortFormSignature, false, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if (indexSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(indexSignatures, "", useShortFormSignature, true, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if ((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if (allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + + return allMemberNames; + } + } + + return TypeScript.MemberName.create("{}"); + }; + + PullTypeSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var isVisible = _super.prototype.isExternallyVisible.call(this, inIsExternallyVisibleSymbols); + if (isVisible) { + var typars = this.getTypeArguments(); + if (!typars || !typars.length) { + typars = this.getTypeParameters(); + } + + if (typars) { + for (var i = 0; i < typars.length; i++) { + isVisible = PullSymbol.getIsExternallyVisible(typars[i], this, inIsExternallyVisibleSymbols); + if (!isVisible) { + break; + } + } + } + } + + return isVisible; + }; + + PullTypeSymbol.prototype.setType = function (type) { + TypeScript.Debug.assert(false, "tried to set type of type"); + }; + return PullTypeSymbol; + })(PullSymbol); + TypeScript.PullTypeSymbol = PullTypeSymbol; + + var PullPrimitiveTypeSymbol = (function (_super) { + __extends(PullPrimitiveTypeSymbol, _super); + function PullPrimitiveTypeSymbol(name) { + _super.call(this, name, 2 /* Primitive */); + } + PullPrimitiveTypeSymbol.prototype.isResolved = function () { + return true; + }; + + PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { + return false; + }; + + PullPrimitiveTypeSymbol.prototype.isFixed = function () { + return true; + }; + + PullPrimitiveTypeSymbol.prototype.invalidate = function () { + }; + return PullPrimitiveTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; + + var PullStringConstantTypeSymbol = (function (_super) { + __extends(PullStringConstantTypeSymbol, _super); + function PullStringConstantTypeSymbol(name) { + _super.call(this, name); + } + PullStringConstantTypeSymbol.prototype.isStringConstant = function () { + return true; + }; + return PullStringConstantTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullStringConstantTypeSymbol = PullStringConstantTypeSymbol; + + var PullErrorTypeSymbol = (function (_super) { + __extends(PullErrorTypeSymbol, _super); + function PullErrorTypeSymbol(diagnostic, delegateType, _data) { + if (typeof _data === "undefined") { _data = null; } + _super.call(this, "error"); + this.diagnostic = diagnostic; + this.delegateType = delegateType; + this._data = _data; + } + PullErrorTypeSymbol.prototype.isError = function () { + return true; + }; + + PullErrorTypeSymbol.prototype.getDiagnostic = function () { + return this.diagnostic; + }; + + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + return this.delegateType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName) { + return this.delegateType.getDisplayName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.toString = function () { + return this.delegateType.toString(); + }; + + PullErrorTypeSymbol.prototype.isResolved = function () { + return false; + }; + + PullErrorTypeSymbol.prototype.setData = function (data) { + this._data = data; + }; + + PullErrorTypeSymbol.prototype.getData = function () { + return this._data; + }; + return PullErrorTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullErrorTypeSymbol = PullErrorTypeSymbol; + + var PullClassTypeSymbol = (function (_super) { + __extends(PullClassTypeSymbol, _super); + function PullClassTypeSymbol(name) { + _super.call(this, name, 8 /* Class */); + } + return PullClassTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullClassTypeSymbol = PullClassTypeSymbol; + + var PullContainerTypeSymbol = (function (_super) { + __extends(PullContainerTypeSymbol, _super); + function PullContainerTypeSymbol(name, kind) { + if (typeof kind === "undefined") { kind = 4 /* Container */; } + _super.call(this, name, kind); + this.instanceSymbol = null; + this._exportAssignedValueSymbol = null; + this._exportAssignedTypeSymbol = null; + this._exportAssignedContainerSymbol = null; + } + PullContainerTypeSymbol.prototype.isContainer = function () { + return true; + }; + + PullContainerTypeSymbol.prototype.setInstanceSymbol = function (symbol) { + this.instanceSymbol = symbol; + }; + + PullContainerTypeSymbol.prototype.getInstanceSymbol = function () { + return this.instanceSymbol; + }; + + PullContainerTypeSymbol.prototype.invalidate = function () { + if (this.instanceSymbol) { + this.instanceSymbol.invalidate(); + } + + _super.prototype.invalidate.call(this); + }; + + PullContainerTypeSymbol.prototype.setExportAssignedValueSymbol = function (symbol) { + this._exportAssignedValueSymbol = symbol; + }; + PullContainerTypeSymbol.prototype.getExportAssignedValueSymbol = function () { + return this._exportAssignedValueSymbol; + }; + + PullContainerTypeSymbol.prototype.setExportAssignedTypeSymbol = function (type) { + this._exportAssignedTypeSymbol = type; + }; + PullContainerTypeSymbol.prototype.getExportAssignedTypeSymbol = function () { + return this._exportAssignedTypeSymbol; + }; + + PullContainerTypeSymbol.prototype.setExportAssignedContainerSymbol = function (container) { + this._exportAssignedContainerSymbol = container; + }; + PullContainerTypeSymbol.prototype.getExportAssignedContainerSymbol = function () { + return this._exportAssignedContainerSymbol; + }; + + PullContainerTypeSymbol.prototype.resetExportAssignedSymbols = function () { + this._exportAssignedContainerSymbol = null; + this._exportAssignedTypeSymbol = null; + this._exportAssignedValueSymbol = null; + }; + + PullContainerTypeSymbol.usedAsSymbol = function (containerSymbol, symbol) { + if (!containerSymbol || !containerSymbol.isContainer()) { + return false; + } + + if (containerSymbol.getType() == symbol) { + return true; + } + + var containerTypeSymbol = containerSymbol; + var valueExportSymbol = containerTypeSymbol.getExportAssignedValueSymbol(); + var typeExportSymbol = containerTypeSymbol.getExportAssignedTypeSymbol(); + var containerExportSymbol = containerTypeSymbol.getExportAssignedContainerSymbol(); + if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { + return valueExportSymbol == symbol || typeExportSymbol == symbol || containerExportSymbol == symbol || PullContainerTypeSymbol.usedAsSymbol(containerExportSymbol, symbol); + } + + return false; + }; + return PullContainerTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullContainerTypeSymbol = PullContainerTypeSymbol; + + var PullTypeAliasSymbol = (function (_super) { + __extends(PullTypeAliasSymbol, _super); + function PullTypeAliasSymbol(name) { + _super.call(this, name, 256 /* TypeAlias */); + this.typeAliasLink = null; + this.isUsedAsValue = false; + this.typeUsedExternally = false; + this.retrievingExportAssignment = false; + } + PullTypeAliasSymbol.prototype.isAlias = function () { + return true; + }; + PullTypeAliasSymbol.prototype.isContainer = function () { + return true; + }; + + PullTypeAliasSymbol.prototype.setAliasedType = function (type) { + TypeScript.Debug.assert(!type.isError(), "Attempted to alias an error"); + if (this.typeAliasLink) { + this.removeOutgoingLink(this.typeAliasLink); + } + + this.typeAliasLink = this.addOutgoingLink(type, 8 /* Aliases */); + }; + + PullTypeAliasSymbol.prototype.getExportAssignedValueSymbol = function () { + if (!this.typeAliasLink) { + return null; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this.typeAliasLink.end.isContainer()) { + this.retrievingExportAssignment = true; + var sym = (this.typeAliasLink.end).getExportAssignedValueSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedTypeSymbol = function () { + if (!this.typeAliasLink) { + return null; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this.typeAliasLink.end.isContainer()) { + this.retrievingExportAssignment = true; + var sym = (this.typeAliasLink.end).getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedContainerSymbol = function () { + if (!this.typeAliasLink) { + return null; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this.typeAliasLink.end.isContainer()) { + this.retrievingExportAssignment = true; + var sym = (this.typeAliasLink.end).getExportAssignedContainerSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getType = function () { + if (this.typeAliasLink) { + return this.typeAliasLink.end; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.setType = function (type) { + this.setAliasedType(type); + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this.isUsedAsValue = true; + }; + + PullTypeAliasSymbol.prototype.getIsUsedAsValue = function () { + return this.isUsedAsValue; + }; + + PullTypeAliasSymbol.prototype.setIsTypeUsedExternally = function () { + this.typeUsedExternally = true; + }; + + PullTypeAliasSymbol.prototype.getTypeUsedExternally = function () { + return this.typeUsedExternally; + }; + + PullTypeAliasSymbol.prototype.getMembers = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getMembers(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.getCallSignatures = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getCallSignatures(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.getConstructSignatures = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getConstructSignatures(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.getIndexSignatures = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getIndexSignatures(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.findMember = function (name) { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).findMember(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedType = function (name) { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).findNestedType(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getAllMembers = function (searchDeclKind, includePrivate) { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getAllMembers(searchDeclKind, includePrivate); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.invalidate = function () { + this.isUsedAsValue = false; + + _super.prototype.invalidate.call(this); + }; + return PullTypeAliasSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; + + var PullDefinitionSignatureSymbol = (function (_super) { + __extends(PullDefinitionSignatureSymbol, _super); + function PullDefinitionSignatureSymbol() { + _super.apply(this, arguments); + } + PullDefinitionSignatureSymbol.prototype.isDefinition = function () { + return true; + }; + return PullDefinitionSignatureSymbol; + })(PullSignatureSymbol); + TypeScript.PullDefinitionSignatureSymbol = PullDefinitionSignatureSymbol; + + var PullFunctionTypeSymbol = (function (_super) { + __extends(PullFunctionTypeSymbol, _super); + function PullFunctionTypeSymbol() { + _super.call(this, "", 16777216 /* FunctionType */); + this.definitionSignature = null; + } + PullFunctionTypeSymbol.prototype.isFunction = function () { + return true; + }; + + PullFunctionTypeSymbol.prototype.invalidate = function () { + var callSignatures = this.getCallSignatures(); + + if (callSignatures.length) { + for (var i = 0; i < callSignatures.length; i++) { + callSignatures[i].invalidate(); + } + } + + this.definitionSignature = null; + + _super.prototype.invalidate.call(this); + }; + + PullFunctionTypeSymbol.prototype.addSignature = function (signature) { + this.addCallSignature(signature); + + if (signature.isDefinition()) { + this.definitionSignature = signature; + } + }; + + PullFunctionTypeSymbol.prototype.getDefinitionSignature = function () { + return this.definitionSignature; + }; + return PullFunctionTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullFunctionTypeSymbol = PullFunctionTypeSymbol; + + var PullConstructorTypeSymbol = (function (_super) { + __extends(PullConstructorTypeSymbol, _super); + function PullConstructorTypeSymbol() { + _super.call(this, "", 33554432 /* ConstructorType */); + this.definitionSignature = null; + } + PullConstructorTypeSymbol.prototype.isFunction = function () { + return true; + }; + PullConstructorTypeSymbol.prototype.isConstructor = function () { + return true; + }; + + PullConstructorTypeSymbol.prototype.invalidate = function () { + this.definitionSignature = null; + + _super.prototype.invalidate.call(this); + }; + + PullConstructorTypeSymbol.prototype.addSignature = function (signature) { + this.addConstructSignature(signature); + + if (signature.isDefinition()) { + this.definitionSignature = signature; + } + }; + + PullConstructorTypeSymbol.prototype.addTypeParameter = function (typeParameter, doNotChangeContainer) { + this.addMember(typeParameter, 18 /* TypeParameter */, doNotChangeContainer); + + var constructSignatures = this.getConstructSignatures(); + + for (var i = 0; i < constructSignatures.length; i++) { + constructSignatures[i].addTypeParameter(typeParameter); + } + }; + + PullConstructorTypeSymbol.prototype.getDefinitionSignature = function () { + return this.definitionSignature; + }; + return PullConstructorTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullConstructorTypeSymbol = PullConstructorTypeSymbol; + + var PullTypeParameterSymbol = (function (_super) { + __extends(PullTypeParameterSymbol, _super); + function PullTypeParameterSymbol(name, _isFunctionTypeParameter) { + _super.call(this, name, 8192 /* TypeParameter */); + this._isFunctionTypeParameter = _isFunctionTypeParameter; + this.constraintLink = null; + } + PullTypeParameterSymbol.prototype.isTypeParameter = function () { + return true; + }; + PullTypeParameterSymbol.prototype.isFunctionTypeParameter = function () { + return this._isFunctionTypeParameter; + }; + + PullTypeParameterSymbol.prototype.isFixed = function () { + return false; + }; + + PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { + if (this.constraintLink) { + this.removeOutgoingLink(this.constraintLink); + } + + this.constraintLink = this.addOutgoingLink(constraintType, 22 /* TypeConstraint */); + }; + + PullTypeParameterSymbol.prototype.getConstraint = function () { + if (this.constraintLink) { + return this.constraintLink.end; + } + + return null; + }; + + PullTypeParameterSymbol.prototype.isGeneric = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.fullName = function (scopeSymbol) { + var name = this.getDisplayName(scopeSymbol); + var container = this.getContainer(); + if (container) { + var containerName = container.fullName(scopeSymbol); + name = name + " in " + containerName; + } + + return name; + }; + + PullTypeParameterSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getName.call(this, scopeSymbol); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this.constraintLink) { + name += " extends " + this.constraintLink.end.toString(); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getDisplayName.call(this, scopeSymbol, useConstraintInName); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this.constraintLink) { + name += " extends " + this.constraintLink.end.toString(); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var constraint = this.getConstraint(); + if (constraint) { + return PullSymbol.getIsExternallyVisible(constraint, this, inIsExternallyVisibleSymbols); + } + + return true; + }; + return PullTypeParameterSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeParameterSymbol = PullTypeParameterSymbol; + + var PullTypeVariableSymbol = (function (_super) { + __extends(PullTypeVariableSymbol, _super); + function PullTypeVariableSymbol(name, isFunctionTypeParameter) { + _super.call(this, name, isFunctionTypeParameter); + this.tyvarID = TypeScript.globalTyvarID++; + } + PullTypeVariableSymbol.prototype.isTypeParameter = function () { + return true; + }; + PullTypeVariableSymbol.prototype.isTypeVariable = function () { + return true; + }; + return PullTypeVariableSymbol; + })(PullTypeParameterSymbol); + TypeScript.PullTypeVariableSymbol = PullTypeVariableSymbol; + + var PullAccessorSymbol = (function (_super) { + __extends(PullAccessorSymbol, _super); + function PullAccessorSymbol(name) { + _super.call(this, name, 4096 /* Property */); + this.getterSymbolLink = null; + this.setterSymbolLink = null; + } + PullAccessorSymbol.prototype.isAccessor = function () { + return true; + }; + + PullAccessorSymbol.prototype.setSetter = function (setter) { + this.setterSymbolLink = this.addOutgoingLink(setter, 25 /* SetterFunction */); + }; + + PullAccessorSymbol.prototype.getSetter = function () { + var setter = null; + + if (this.setterSymbolLink) { + setter = this.setterSymbolLink.end; + } + + return setter; + }; + + PullAccessorSymbol.prototype.removeSetter = function () { + if (this.setterSymbolLink) { + this.removeOutgoingLink(this.setterSymbolLink); + } + }; + + PullAccessorSymbol.prototype.setGetter = function (getter) { + this.getterSymbolLink = this.addOutgoingLink(getter, 24 /* GetterFunction */); + }; + + PullAccessorSymbol.prototype.getGetter = function () { + var getter = null; + + if (this.getterSymbolLink) { + getter = this.getterSymbolLink.end; + } + + return getter; + }; + + PullAccessorSymbol.prototype.removeGetter = function () { + if (this.getterSymbolLink) { + this.removeOutgoingLink(this.getterSymbolLink); + } + }; + + PullAccessorSymbol.prototype.invalidate = function () { + if (this.getterSymbolLink) { + this.getterSymbolLink.end.invalidate(); + } + + if (this.setterSymbolLink) { + this.setterSymbolLink.end.invalidate(); + } + + _super.prototype.invalidate.call(this); + }; + return PullAccessorSymbol; + })(PullSymbol); + TypeScript.PullAccessorSymbol = PullAccessorSymbol; + + var PullArrayTypeSymbol = (function (_super) { + __extends(PullArrayTypeSymbol, _super); + function PullArrayTypeSymbol() { + _super.call(this, "Array", 128 /* Array */); + this.elementType = null; + } + PullArrayTypeSymbol.prototype.isArray = function () { + return true; + }; + PullArrayTypeSymbol.prototype.getElementType = function () { + return this.elementType; + }; + PullArrayTypeSymbol.prototype.isGeneric = function () { + return true; + }; + + PullArrayTypeSymbol.prototype.setElementType = function (type) { + this.elementType = type; + }; + + PullArrayTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo) { + var elementMemberName = this.elementType ? (this.elementType.isArray() || this.elementType.isNamedTypeSymbol() ? this.elementType.getScopedNameEx(scopeSymbol, false, getPrettyTypeName, getTypeParamMarkerInfo) : this.elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + }; + + PullArrayTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var elementMemberName = this.elementType ? this.elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + }; + return PullArrayTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullArrayTypeSymbol = PullArrayTypeSymbol; + + function specializeToArrayType(typeToReplace, typeToSpecializeTo, resolver, context) { + var arrayInterfaceType = resolver.getCachedArrayType(); + + if (!arrayInterfaceType || (arrayInterfaceType.getKind() & 16 /* Interface */) === 0) { + return null; + } + + if (arrayInterfaceType.isGeneric()) { + var enclosingDecl = arrayInterfaceType.getDeclarations()[0]; + return specializeType(arrayInterfaceType, [typeToSpecializeTo], resolver, enclosingDecl, context); + } + + if (typeToSpecializeTo.getArrayType()) { + return typeToSpecializeTo.getArrayType(); + } + + var newArrayType = new PullArrayTypeSymbol(); + newArrayType.addDeclaration(arrayInterfaceType.getDeclarations()[0]); + + typeToSpecializeTo.setArrayType(newArrayType); + newArrayType.addOutgoingLink(typeToSpecializeTo, 4 /* ArrayOf */); + + var field = null; + var newField = null; + var fieldType = null; + + var method = null; + var methodType = null; + var newMethod = null; + var newMethodType = null; + + var signatures = null; + var newSignature = null; + + var parameters = null; + var newParameter = null; + var parameterType = null; + + var returnType = null; + var newReturnType = null; + + var members = arrayInterfaceType.getMembers(); + + for (var i = 0; i < members.length; i++) { + resolver.resolveDeclaredSymbol(members[i], null, context); + + if (members[i].getKind() === 65536 /* Method */) { + method = members[i]; + + resolver.resolveDeclaredSymbol(method, null, context); + + methodType = method.getType(); + + newMethod = new PullSymbol(method.getName(), 65536 /* Method */); + newMethodType = new PullFunctionTypeSymbol(); + newMethod.setType(newMethodType); + + newMethod.addDeclaration(method.getDeclarations()[0]); + + signatures = methodType.getCallSignatures(); + + for (var j = 0; j < signatures.length; j++) { + newSignature = new PullSignatureSymbol(1048576 /* CallSignature */); + newSignature.addDeclaration(signatures[j].getDeclarations()[0]); + + parameters = signatures[j].getParameters(); + returnType = signatures[j].getReturnType(); + + if (returnType === typeToReplace) { + newSignature.setReturnType(typeToSpecializeTo); + } else { + newSignature.setReturnType(returnType); + } + + for (var k = 0; k < parameters.length; k++) { + newParameter = new PullSymbol(parameters[k].getName(), parameters[k].getKind()); + + parameterType = parameters[k].getType(); + + if (parameterType === null) { + continue; + } + + if (parameterType === typeToReplace) { + newParameter.setType(typeToSpecializeTo); + } else { + newParameter.setType(parameterType); + } + + newSignature.addParameter(newParameter); + } + + newMethodType.addSignature(newSignature); + } + + newArrayType.addMember(newMethod, 5 /* PublicMember */); + } else { + field = members[i]; + + newField = new PullSymbol(field.getName(), field.getKind()); + newField.addDeclaration(field.getDeclarations()[0]); + + fieldType = field.getType(); + + if (fieldType === typeToReplace) { + newField.setType(typeToSpecializeTo); + } else { + newField.setType(fieldType); + } + + newArrayType.addMember(newField, 5 /* PublicMember */); + } + } + newArrayType.addOutgoingLink(arrayInterfaceType, 3 /* ArrayType */); + return newArrayType; + } + TypeScript.specializeToArrayType = specializeToArrayType; + + function typeWrapsTypeParameter(type, typeParameter) { + if (type.isTypeParameter()) { + return type == typeParameter; + } + + var typeArguments = type.getTypeArguments(); + + if (typeArguments) { + for (var i = 0; i < typeArguments.length; i++) { + if (typeWrapsTypeParameter(typeArguments[i], typeParameter)) { + return true; + } + } + } + + return false; + } + TypeScript.typeWrapsTypeParameter = typeWrapsTypeParameter; + + function getRootType(typeToSpecialize) { + var decl = typeToSpecialize.getDeclarations()[0]; + + if (!typeToSpecialize.isGeneric()) { + return typeToSpecialize; + } + + return (typeToSpecialize.getKind() & (8 /* Class */ | 16 /* Interface */)) ? decl.getSymbol().getType() : typeToSpecialize; + } + TypeScript.getRootType = getRootType; + + TypeScript.nSpecializationsCreated = 0; + TypeScript.nSpecializedSignaturesCreated = 0; + + function shouldSpecializeTypeParameterForTypeParameter(specialization, typeToSpecialize) { + if (specialization == typeToSpecialize) { + return false; + } + + if (!(specialization.isTypeParameter() && typeToSpecialize.isTypeParameter())) { + return true; + } + + var parent = specialization.getDeclarations()[0].getParentDecl(); + var targetParent = typeToSpecialize.getDeclarations()[0].getParentDecl(); + + if (parent == targetParent) { + return true; + } + + while (parent) { + if (parent.getFlags() & 16 /* Static */) { + return true; + } + + if (parent == targetParent) { + return false; + } + + parent = parent.getParentDecl(); + } + + return true; + } + TypeScript.shouldSpecializeTypeParameterForTypeParameter = shouldSpecializeTypeParameterForTypeParameter; + + function specializeType(typeToSpecialize, typeArguments, resolver, enclosingDecl, context, ast) { + if (typeToSpecialize.isPrimitive() || !typeToSpecialize.isGeneric()) { + return typeToSpecialize; + } + + var searchForExistingSpecialization = typeArguments != null; + + if (typeArguments === null || (context.specializingToAny && typeArguments.length)) { + typeArguments = []; + } + + if (typeToSpecialize.isTypeParameter()) { + if (context.specializingToAny) { + return resolver.semanticInfoChain.anyTypeSymbol; + } + + var substitution = context.findSpecializationForType(typeToSpecialize); + + if (substitution != typeToSpecialize) { + if (shouldSpecializeTypeParameterForTypeParameter(substitution, typeToSpecialize)) { + return substitution; + } + } + + if (typeArguments && typeArguments.length) { + if (shouldSpecializeTypeParameterForTypeParameter(typeArguments[0], typeToSpecialize)) { + return typeArguments[0]; + } + } + + return typeToSpecialize; + } + + if (typeToSpecialize.isArray()) { + if (typeToSpecialize.currentlyBeingSpecialized()) { + return typeToSpecialize; + } + + var newElementType = null; + + if (!context.specializingToAny) { + var elementType = (typeToSpecialize).getElementType(); + + newElementType = specializeType(elementType, typeArguments, resolver, enclosingDecl, context, ast); + } else { + newElementType = resolver.semanticInfoChain.anyTypeSymbol; + } + + var newArrayType = specializeType(resolver.getCachedArrayType(), [newElementType], resolver, enclosingDecl, context); + + return newArrayType; + } + + var typeParameters = typeToSpecialize.getTypeParameters(); + + if (!context.specializingToAny && searchForExistingSpecialization && (typeParameters.length > typeArguments.length)) { + searchForExistingSpecialization = false; + } + + var newType = null; + + var newTypeDecl = typeToSpecialize.getDeclarations()[0]; + + var rootType = getRootType(typeToSpecialize); + + var isArray = typeToSpecialize === resolver.getCachedArrayType() || typeToSpecialize.isArray(); + + if (searchForExistingSpecialization || context.specializingToAny) { + if (!typeArguments.length || context.specializingToAny) { + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = resolver.semanticInfoChain.anyTypeSymbol; + } + } + + if (isArray) { + newType = typeArguments[0].getArrayType(); + } else if (typeArguments.length) { + newType = rootType.getSpecialization(typeArguments); + } + + if (!newType && !typeParameters.length && context.specializingToAny) { + newType = rootType.getSpecialization([resolver.semanticInfoChain.anyTypeSymbol]); + } + + for (var i = 0; i < typeArguments.length; i++) { + if (!typeArguments[i].isTypeParameter() && (typeArguments[i] == rootType || typeWrapsTypeParameter(typeArguments[i], typeParameters[i]))) { + declAST = resolver.semanticInfoChain.getASTForDecl(newTypeDecl); + if (declAST && typeArguments[i] != resolver.getCachedArrayType()) { + diagnostic = context.postError(enclosingDecl.getScriptName(), declAST.minChar, declAST.getLength(), 225 /* A_generic_type_may_not_reference_itself_with_its_own_type_parameters */, null, enclosingDecl, true); + return resolver.getNewErrorTypeSymbol(diagnostic); + } else { + return resolver.semanticInfoChain.anyTypeSymbol; + } + } + } + } else { + var knownTypeArguments = typeToSpecialize.getTypeArguments(); + var typesToReplace = knownTypeArguments ? knownTypeArguments : typeParameters; + var diagnostic; + var declAST; + + for (var i = 0; i < typesToReplace.length; i++) { + if (!typesToReplace[i].isTypeParameter() && (typeArguments[i] == rootType || typeWrapsTypeParameter(typesToReplace[i], typeParameters[i]))) { + declAST = resolver.semanticInfoChain.getASTForDecl(newTypeDecl); + if (declAST && typeArguments[i] != resolver.getCachedArrayType()) { + diagnostic = context.postError(enclosingDecl.getScriptName(), declAST.minChar, declAST.getLength(), 225 /* A_generic_type_may_not_reference_itself_with_its_own_type_parameters */, null, enclosingDecl, true); + return resolver.getNewErrorTypeSymbol(diagnostic); + } else { + return resolver.semanticInfoChain.anyTypeSymbol; + } + } + + substitution = specializeType(typesToReplace[i], null, resolver, enclosingDecl, context, ast); + + typeArguments[i] = substitution != null ? substitution : typesToReplace[i]; + } + + newType = rootType.getSpecialization(typeArguments); + } + + var rootTypeParameters = rootType.getTypeParameters(); + + if (rootTypeParameters.length && (rootTypeParameters.length == typeArguments.length)) { + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i] != rootTypeParameters[i]) { + break; + } + } + + if (i == rootTypeParameters.length) { + return rootType; + } + } + + if (newType) { + if (!newType.isResolved() && !newType.currentlyBeingSpecialized()) { + typeToSpecialize.invalidateSpecializations(); + } else { + return newType; + } + } + + var prevInSpecialization = context.inSpecialization; + context.inSpecialization = true; + + TypeScript.nSpecializationsCreated++; + + newType = typeToSpecialize.isClass() ? new PullClassTypeSymbol(typeToSpecialize.getName()) : isArray ? new PullArrayTypeSymbol() : typeToSpecialize.isTypeParameter() ? new PullTypeVariableSymbol(typeToSpecialize.getName(), (typeToSpecialize).isFunctionTypeParameter()) : new PullTypeSymbol(typeToSpecialize.getName(), typeToSpecialize.getKind()); + newType.setRootSymbol(rootType); + + newType.setIsBeingSpecialized(); + + newType.setTypeArguments(typeArguments); + + rootType.addSpecialization(newType, typeArguments); + + if (isArray) { + (newType).setElementType(typeArguments[0]); + typeArguments[0].setArrayType(newType); + } + + if (typeToSpecialize.currentlyBeingSpecialized()) { + return newType; + } + + var prevCurrentlyBeingSpecialized = typeToSpecialize.currentlyBeingSpecialized(); + if (typeToSpecialize.getKind() == 33554432 /* ConstructorType */) { + typeToSpecialize.setIsBeingSpecialized(); + } + + var typeReplacementMap = {}; + + for (var i = 0; i < typeParameters.length; i++) { + if (typeParameters[i] != typeArguments[i]) { + typeReplacementMap[typeParameters[i].getSymbolID().toString()] = typeArguments[i]; + } + newType.addMember(typeParameters[i], 18 /* TypeParameter */, true); + } + + var extendedTypesToSpecialize = typeToSpecialize.getExtendedTypes(); + var typeDecl; + var typeAST; + var unitPath; + var decls = typeToSpecialize.getDeclarations(); + + if (extendedTypesToSpecialize.length) { + for (var i = 0; i < decls.length; i++) { + typeDecl = decls[i]; + typeAST = resolver.semanticInfoChain.getASTForDecl(typeDecl); + + if (typeAST.extendsList) { + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(typeDecl.getScriptName()); + context.pushTypeSpecializationCache(typeReplacementMap); + var extendTypeSymbol = resolver.resolveTypeReference(new TypeScript.TypeReference(typeAST.extendsList.members[0], 0), typeDecl, context).symbol; + resolver.setUnitPath(unitPath); + context.popTypeSpecializationCache(); + + newType.addExtendedType(extendTypeSymbol); + } + } + } + + var implementedTypesToSpecialize = typeToSpecialize.getImplementedTypes(); + + if (implementedTypesToSpecialize.length) { + for (var i = 0; i < decls.length; i++) { + typeDecl = decls[i]; + typeAST = resolver.semanticInfoChain.getASTForDecl(typeDecl); + + if (typeAST.implementsList) { + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(typeDecl.getScriptName()); + context.pushTypeSpecializationCache(typeReplacementMap); + var implementedTypeSymbol = resolver.resolveTypeReference(new TypeScript.TypeReference(typeAST.implementsList.members[0], 0), typeDecl, context).symbol; + resolver.setUnitPath(unitPath); + context.popTypeSpecializationCache(); + + newType.addImplementedType(implementedTypeSymbol); + } + } + } + + var callSignatures = typeToSpecialize.getCallSignatures(false); + var constructSignatures = typeToSpecialize.getConstructSignatures(false); + var indexSignatures = typeToSpecialize.getIndexSignatures(false); + var members = typeToSpecialize.getMembers(); + + var newSignature; + var signature; + + var decl = null; + var declAST = null; + var parameters; + var newParameters; + var returnType = null; + var prevSpecializationSignature = null; + + for (var i = 0; i < callSignatures.length; i++) { + signature = callSignatures[i]; + + if (!signature.currentlyBeingSpecialized()) { + context.pushTypeSpecializationCache(typeReplacementMap); + + decl = signature.getDeclarations()[0]; + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decl.getScriptName()); + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.mimicSignature(signature, resolver); + declAST = resolver.semanticInfoChain.getASTForDecl(decl); + + TypeScript.Debug.assert(declAST != null, "Call signature for type '" + typeToSpecialize.toString() + "' could not be specialized because of a stale declaration"); + + prevSpecializationSignature = decl.getSpecializingSignatureSymbol(); + decl.setSpecializingSignatureSymbol(newSignature); + resolver.resolveAST(declAST, false, newTypeDecl, context); + decl.setSpecializingSignatureSymbol(prevSpecializationSignature); + + parameters = signature.getParameters(); + newParameters = newSignature.getParameters(); + + for (var p = 0; p < parameters.length; p++) { + newParameters[p].setType(parameters[p].getType()); + } + newSignature.setResolved(); + + resolver.setUnitPath(unitPath); + + returnType = newSignature.getReturnType(); + + if (!returnType) { + newSignature.setReturnType(signature.getReturnType()); + } + + signature.setIsBeingSpecialized(); + newSignature.setRootSymbol(signature); + newSignature = specializeSignature(newSignature, true, typeReplacementMap, null, resolver, newTypeDecl, context); + signature.setIsSpecialized(); + + context.popTypeSpecializationCache(); + + if (!newSignature) { + context.inSpecialization = prevInSpecialization; + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + TypeScript.Debug.assert(false, "returning from call"); + return resolver.semanticInfoChain.anyTypeSymbol; + } + } else { + newSignature = signature; + } + + newType.addCallSignature(newSignature); + + if (newSignature.hasGenericParameter()) { + newType.setHasGenericSignature(); + } + } + + for (var i = 0; i < constructSignatures.length; i++) { + signature = constructSignatures[i]; + + if (!signature.currentlyBeingSpecialized()) { + context.pushTypeSpecializationCache(typeReplacementMap); + + decl = signature.getDeclarations()[0]; + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decl.getScriptName()); + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.mimicSignature(signature, resolver); + declAST = resolver.semanticInfoChain.getASTForDecl(decl); + + TypeScript.Debug.assert(declAST != null, "Construct signature for type '" + typeToSpecialize.toString() + "' could not be specialized because of a stale declaration"); + + prevSpecializationSignature = decl.getSpecializingSignatureSymbol(); + decl.setSpecializingSignatureSymbol(newSignature); + resolver.resolveAST(declAST, false, newTypeDecl, context); + decl.setSpecializingSignatureSymbol(prevSpecializationSignature); + + parameters = signature.getParameters(); + newParameters = newSignature.getParameters(); + + for (var p = 0; p < parameters.length; p++) { + newParameters[p].setType(parameters[p].getType()); + } + newSignature.setResolved(); + + resolver.setUnitPath(unitPath); + + returnType = newSignature.getReturnType(); + + if (!returnType) { + newSignature.setReturnType(signature.getReturnType()); + } + + signature.setIsBeingSpecialized(); + newSignature.setRootSymbol(signature); + newSignature = specializeSignature(newSignature, true, typeReplacementMap, null, resolver, newTypeDecl, context); + signature.setIsSpecialized(); + + context.popTypeSpecializationCache(); + + if (!newSignature) { + context.inSpecialization = prevInSpecialization; + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + TypeScript.Debug.assert(false, "returning from construct"); + return resolver.semanticInfoChain.anyTypeSymbol; + } + } else { + newSignature = signature; + } + + newType.addConstructSignature(newSignature); + + if (newSignature.hasGenericParameter()) { + newType.setHasGenericSignature(); + } + } + + for (var i = 0; i < indexSignatures.length; i++) { + signature = indexSignatures[i]; + + if (!signature.currentlyBeingSpecialized()) { + context.pushTypeSpecializationCache(typeReplacementMap); + + decl = signature.getDeclarations()[0]; + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decl.getScriptName()); + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.mimicSignature(signature, resolver); + declAST = resolver.semanticInfoChain.getASTForDecl(decl); + + TypeScript.Debug.assert(declAST != null, "Index signature for type '" + typeToSpecialize.toString() + "' could not be specialized because of a stale declaration"); + + prevSpecializationSignature = decl.getSpecializingSignatureSymbol(); + decl.setSpecializingSignatureSymbol(newSignature); + resolver.resolveAST(declAST, false, newTypeDecl, context); + decl.setSpecializingSignatureSymbol(prevSpecializationSignature); + + parameters = signature.getParameters(); + newParameters = newSignature.getParameters(); + + for (var p = 0; p < parameters.length; p++) { + newParameters[p].setType(parameters[p].getType()); + } + newSignature.setResolved(); + + resolver.setUnitPath(unitPath); + + returnType = newSignature.getReturnType(); + + if (!returnType) { + newSignature.setReturnType(signature.getReturnType()); + } + + signature.setIsBeingSpecialized(); + newSignature.setRootSymbol(signature); + newSignature = specializeSignature(newSignature, true, typeReplacementMap, null, resolver, newTypeDecl, context); + signature.setIsSpecialized(); + + context.popTypeSpecializationCache(); + + if (!newSignature) { + context.inSpecialization = prevInSpecialization; + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + TypeScript.Debug.assert(false, "returning from index"); + return resolver.semanticInfoChain.anyTypeSymbol; + } + } else { + newSignature = signature; + } + + newType.addIndexSignature(newSignature); + + if (newSignature.hasGenericParameter()) { + newType.setHasGenericSignature(); + } + } + + var field = null; + var newField = null; + + var fieldType = null; + var newFieldType = null; + var replacementType = null; + + var fieldSignatureSymbol = null; + + for (var i = 0; i < members.length; i++) { + field = members[i]; + field.setIsBeingSpecialized(); + + decls = field.getDeclarations(); + + newField = new PullSymbol(field.getName(), field.getKind()); + + newField.setRootSymbol(field); + + if (field.getIsOptional()) { + newField.setIsOptional(); + } + + if (!field.isResolved()) { + resolver.resolveDeclaredSymbol(field, newTypeDecl, context); + } + + fieldType = field.getType(); + + if (!fieldType) { + fieldType = newType; + } + + replacementType = typeReplacementMap[fieldType.getSymbolID().toString()]; + + if (replacementType) { + newField.setType(replacementType); + } else { + if (fieldType.isGeneric() && !fieldType.isFixed()) { + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decls[0].getScriptName()); + + context.pushTypeSpecializationCache(typeReplacementMap); + + newFieldType = specializeType(fieldType, !fieldType.getIsSpecialized() ? typeArguments : null, resolver, newTypeDecl, context, ast); + + resolver.setUnitPath(unitPath); + + context.popTypeSpecializationCache(); + + newField.setType(newFieldType); + } else { + newField.setType(fieldType); + } + } + field.setIsSpecialized(); + newType.addMember(newField, (field.hasFlag(2 /* Private */)) ? 6 /* PrivateMember */ : 5 /* PublicMember */); + } + + if (typeToSpecialize.isClass()) { + var constructorMethod = (typeToSpecialize).getConstructorMethod(); + + if (!constructorMethod.isResolved()) { + var prevIsSpecializingConstructorMethod = context.isSpecializingConstructorMethod; + context.isSpecializingConstructorMethod = true; + resolver.resolveDeclaredSymbol(constructorMethod, enclosingDecl, context); + context.isSpecializingConstructorMethod = prevIsSpecializingConstructorMethod; + } + + var newConstructorMethod = new PullSymbol(constructorMethod.getName(), 32768 /* ConstructorMethod */); + var newConstructorType = specializeType(constructorMethod.getType(), typeArguments, resolver, newTypeDecl, context, ast); + + newConstructorMethod.setType(newConstructorType); + + var constructorDecls = constructorMethod.getDeclarations(); + + newConstructorMethod.setRootSymbol(constructorMethod); + + (newType).setConstructorMethod(newConstructorMethod); + } + + newType.setIsSpecialized(); + + newType.setResolved(); + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + context.inSpecialization = prevInSpecialization; + return newType; + } + TypeScript.specializeType = specializeType; + + function specializeSignature(signature, skipLocalTypeParameters, typeReplacementMap, typeArguments, resolver, enclosingDecl, context, ast) { + if (signature.currentlyBeingSpecialized()) { + return signature; + } + + if (!signature.isResolved() && !signature.isResolving()) { + resolver.resolveDeclaredSymbol(signature, enclosingDecl, context); + } + + var newSignature = signature.getSpecialization(typeArguments); + + if (newSignature) { + return newSignature; + } + + signature.setIsBeingSpecialized(); + + var prevInSpecialization = context.inSpecialization; + context.inSpecialization = true; + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.setRootSymbol(signature); + + if (signature.hasVariableParamList()) { + newSignature.setHasVariableParamList(); + } + + if (signature.hasGenericParameter()) { + newSignature.setHasGenericParameter(); + } + + signature.addSpecialization(newSignature, typeArguments); + + var parameters = signature.getParameters(); + var typeParameters = signature.getTypeParameters(); + var returnType = signature.getReturnType(); + + for (var i = 0; i < typeParameters.length; i++) { + newSignature.addTypeParameter(typeParameters[i]); + } + + if (signature.hasGenericParameter()) { + newSignature.setHasGenericParameter(); + } + + var newParameter; + var newParameterType; + var newParameterElementType; + var parameterType; + var replacementParameterType; + var localTypeParameters = new TypeScript.BlockIntrinsics(); + var localSkipMap = null; + + if (skipLocalTypeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + localTypeParameters[typeParameters[i].getName()] = true; + if (!localSkipMap) { + localSkipMap = {}; + } + localSkipMap[typeParameters[i].getSymbolID().toString()] = typeParameters[i]; + } + } + + context.pushTypeSpecializationCache(typeReplacementMap); + + if (skipLocalTypeParameters && localSkipMap) { + context.pushTypeSpecializationCache(localSkipMap); + } + var newReturnType = (!localTypeParameters[returnType.getName()]) ? specializeType(returnType, null, resolver, enclosingDecl, context, ast) : returnType; + if (skipLocalTypeParameters && localSkipMap) { + context.popTypeSpecializationCache(); + } + context.popTypeSpecializationCache(); + + newSignature.setReturnType(newReturnType); + + for (var k = 0; k < parameters.length; k++) { + newParameter = new PullSymbol(parameters[k].getName(), parameters[k].getKind()); + newParameter.setRootSymbol(parameters[k]); + + parameterType = parameters[k].getType(); + + context.pushTypeSpecializationCache(typeReplacementMap); + if (skipLocalTypeParameters && localSkipMap) { + context.pushTypeSpecializationCache(localSkipMap); + } + newParameterType = !localTypeParameters[parameterType.getName()] ? specializeType(parameterType, null, resolver, enclosingDecl, context, ast) : parameterType; + if (skipLocalTypeParameters && localSkipMap) { + context.popTypeSpecializationCache(); + } + context.popTypeSpecializationCache(); + + if (parameters[k].getIsOptional()) { + newParameter.setIsOptional(); + } + + if (parameters[k].getIsVarArg()) { + newParameter.setIsVarArg(); + newSignature.setHasVariableParamList(); + } + + if (resolver.isTypeArgumentOrWrapper(newParameterType)) { + newSignature.setHasGenericParameter(); + } + + newParameter.setType(newParameterType); + newSignature.addParameter(newParameter, newParameter.getIsOptional()); + } + + signature.setIsSpecialized(); + + context.inSpecialization = prevInSpecialization; + + return newSignature; + } + TypeScript.specializeSignature = specializeSignature; + + function getIDForTypeSubstitutions(types) { + var substitution = ""; + + for (var i = 0; i < types.length; i++) { + substitution += types[i].getSymbolID().toString() + "#"; + } + + return substitution; + } + TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullSymbolBindingContext = (function () { + function PullSymbolBindingContext(semanticInfoChain, scriptName) { + this.semanticInfoChain = semanticInfoChain; + this.scriptName = scriptName; + this.parentChain = []; + this.declPath = []; + this.reBindingAfterChange = false; + this.startingDeclForRebind = TypeScript.pullDeclID; + this.semanticInfo = this.semanticInfoChain.getUnit(this.scriptName); + } + PullSymbolBindingContext.prototype.getParent = function (n) { + if (typeof n === "undefined") { n = 0; } + return this.parentChain ? this.parentChain[this.parentChain.length - 1 - n] : null; + }; + PullSymbolBindingContext.prototype.getDeclPath = function () { + return this.declPath; + }; + + PullSymbolBindingContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + this.declPath[this.declPath.length] = parentDecl.getName(); + } + }; + + PullSymbolBindingContext.prototype.popParent = function () { + if (this.parentChain.length) { + this.parentChain.length--; + this.declPath.length--; + } + }; + return PullSymbolBindingContext; + })(); + TypeScript.PullSymbolBindingContext = PullSymbolBindingContext; + + TypeScript.time_in_findSymbol = 0; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CandidateInferenceInfo = (function () { + function CandidateInferenceInfo() { + this.typeParameter = null; + this.isFixed = false; + this.inferenceCandidates = []; + } + CandidateInferenceInfo.prototype.addCandidate = function (candidate) { + if (!this.isFixed) { + this.inferenceCandidates[this.inferenceCandidates.length] = candidate; + } + }; + return CandidateInferenceInfo; + })(); + TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; + + var ArgumentInferenceContext = (function () { + function ArgumentInferenceContext() { + this.inferenceCache = {}; + this.candidateCache = {}; + } + ArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + var comboID = objectType.getSymbolID().toString() + "#" + parameterType.getSymbolID().toString(); + + if (this.inferenceCache[comboID]) { + return true; + } else { + this.inferenceCache[comboID] = true; + return false; + } + }; + + ArgumentInferenceContext.prototype.resetRelationshipCache = function () { + this.inferenceCache = {}; + }; + + ArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + var info = this.candidateCache[param.getSymbolID().toString()]; + + if (!info) { + info = new CandidateInferenceInfo(); + info.typeParameter = param; + this.candidateCache[param.getSymbolID().toString()] = info; + } + }; + + ArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + return this.candidateCache[param.getSymbolID().toString()]; + }; + + ArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate, fix) { + var info = this.getInferenceInfo(param); + + if (info) { + if (candidate) { + info.addCandidate(candidate); + } + + if (!info.isFixed) { + info.isFixed = fix; + } + } + }; + + ArgumentInferenceContext.prototype.getInferenceCandidates = function () { + var inferenceCandidates = []; + var info; + var val; + + for (var infoKey in this.candidateCache) { + info = this.candidateCache[infoKey]; + + for (var i = 0; i < info.inferenceCandidates.length; i++) { + val = {}; + val[info.typeParameter.getSymbolID().toString()] = info.inferenceCandidates[i]; + inferenceCandidates[inferenceCandidates.length] = val; + } + } + + return inferenceCandidates; + }; + + ArgumentInferenceContext.prototype.inferArgumentTypes = function (resolver, context) { + var info = null; + + var collection; + + var bestCommonType; + + var results = []; + + var unfit = false; + + for (var infoKey in this.candidateCache) { + info = this.candidateCache[infoKey]; + + if (!info.inferenceCandidates.length) { + results[results.length] = { param: info.typeParameter, type: resolver.semanticInfoChain.anyTypeSymbol }; + continue; + } + + collection = { + getLength: function () { + return info.inferenceCandidates.length; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return info.inferenceCandidates[index].getType(); + } + }; + + bestCommonType = resolver.widenType(resolver.findBestCommonType(info.inferenceCandidates[0], null, collection, context, new TypeScript.TypeComparisonInfo())); + + if (!bestCommonType) { + unfit = true; + } else { + for (var i = 0; i < results.length; i++) { + if (results[i].type == info.typeParameter) { + results[i].type = bestCommonType; + } + } + } + + results[results.length] = { param: info.typeParameter, type: bestCommonType }; + } + + return { results: results, unfit: unfit }; + }; + return ArgumentInferenceContext; + })(); + TypeScript.ArgumentInferenceContext = ArgumentInferenceContext; + + var PullContextualTypeContext = (function () { + function PullContextualTypeContext(contextualType, provisional, substitutions) { + this.contextualType = contextualType; + this.provisional = provisional; + this.substitutions = substitutions; + this.provisionallyTypedSymbols = []; + this.provisionalDiagnostic = []; + } + PullContextualTypeContext.prototype.recordProvisionallyTypedSymbol = function (symbol) { + this.provisionallyTypedSymbols[this.provisionallyTypedSymbols.length] = symbol; + }; + + PullContextualTypeContext.prototype.invalidateProvisionallyTypedSymbols = function () { + for (var i = 0; i < this.provisionallyTypedSymbols.length; i++) { + this.provisionallyTypedSymbols[i].invalidate(); + } + }; + + PullContextualTypeContext.prototype.postDiagnostic = function (error) { + this.provisionalDiagnostic[this.provisionalDiagnostic.length] = error; + }; + + PullContextualTypeContext.prototype.hadProvisionalErrors = function () { + return this.provisionalDiagnostic.length > 0; + }; + return PullContextualTypeContext; + })(); + TypeScript.PullContextualTypeContext = PullContextualTypeContext; + + var PullTypeResolutionContext = (function () { + function PullTypeResolutionContext() { + this.contextStack = []; + this.typeSpecializationStack = []; + this.genericASTResolutionStack = []; + this.resolvingTypeReference = false; + this.resolvingNamespaceMemberAccess = false; + this.resolveAggressively = false; + this.canUseTypeSymbol = false; + this.specializingToAny = false; + this.specializingToObject = false; + this.isResolvingClassExtendedType = false; + this.isSpecializingSignatureAtCallSite = false; + this.isSpecializingConstructorMethod = false; + this.isComparingSpecializedSignatures = false; + this.inSpecialization = false; + this.suppressErrors = false; + this.inBaseTypeResolution = false; + } + PullTypeResolutionContext.prototype.pushContextualType = function (type, provisional, substitutions) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, substitutions)); + }; + + PullTypeResolutionContext.prototype.popContextualType = function () { + var tc = this.contextStack.pop(); + + tc.invalidateProvisionallyTypedSymbols(); + + return tc; + }; + + PullTypeResolutionContext.prototype.findSubstitution = function (type) { + var substitution = null; + + if (this.contextStack.length) { + for (var i = this.contextStack.length - 1; i >= 0; i--) { + if (this.contextStack[i].substitutions) { + substitution = this.contextStack[i].substitutions[type.getSymbolID().toString()]; + + if (substitution) { + break; + } + } + } + } + + return substitution; + }; + + PullTypeResolutionContext.prototype.getContextualType = function () { + var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; + + if (context) { + var type = context.contextualType; + + if (!type) { + return null; + } + + if (type.isTypeParameter() && (type).getConstraint()) { + type = (type).getConstraint(); + } + + var substitution = this.findSubstitution(type); + + return substitution ? substitution : type; + } + + return null; + }; + + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + + PullTypeResolutionContext.prototype.isInBaseTypeResolution = function () { + return this.inBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.startBaseTypeResolution = function () { + var wasInBaseTypeResoltion = this.inBaseTypeResolution; + this.inBaseTypeResolution = true; + return wasInBaseTypeResoltion; + }; + + PullTypeResolutionContext.prototype.doneBaseTypeResolution = function (wasInBaseTypeResolution) { + this.inBaseTypeResolution = wasInBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { + var substitution = this.findSubstitution(type); + + symbol.setType(substitution ? substitution : type); + + if (this.contextStack.length && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); + } + }; + + PullTypeResolutionContext.prototype.pushTypeSpecializationCache = function (cache) { + this.typeSpecializationStack[this.typeSpecializationStack.length] = cache; + }; + + PullTypeResolutionContext.prototype.popTypeSpecializationCache = function () { + if (this.typeSpecializationStack.length) { + this.typeSpecializationStack.length--; + } + }; + + PullTypeResolutionContext.prototype.findSpecializationForType = function (type) { + var specialization = null; + + for (var i = this.typeSpecializationStack.length - 1; i >= 0; i--) { + specialization = (this.typeSpecializationStack[i])[type.getSymbolID().toString()]; + + if (specialization) { + return specialization; + } + } + + return type; + }; + + PullTypeResolutionContext.prototype.postError = function (fileName, offset, length, diagnosticCode, arguments, enclosingDecl, addToDecl) { + if (typeof arguments === "undefined") { arguments = null; } + if (typeof enclosingDecl === "undefined") { enclosingDecl = null; } + if (typeof addToDecl === "undefined") { addToDecl = false; } + var diagnostic = new TypeScript.SemanticDiagnostic(fileName, offset, length, diagnosticCode, arguments); + this.postDiagnostic(diagnostic, enclosingDecl, addToDecl); + + return diagnostic; + }; + + PullTypeResolutionContext.prototype.postDiagnostic = function (diagnostic, enclosingDecl, addToDecl) { + if (this.inProvisionalResolution()) { + (this.contextStack[this.contextStack.length - 1]).postDiagnostic(diagnostic); + } else if (!this.suppressErrors && enclosingDecl && addToDecl) { + enclosingDecl.addDiagnostic(diagnostic); + } + }; + + PullTypeResolutionContext.prototype.startResolvingTypeArguments = function (ast) { + this.genericASTResolutionStack[this.genericASTResolutionStack.length] = ast; + }; + + PullTypeResolutionContext.prototype.isResolvingTypeArguments = function (ast) { + for (var i = 0; i < this.genericASTResolutionStack.length; i++) { + if (this.genericASTResolutionStack[i].getID() === ast.getID()) { + return true; + } + } + + return false; + }; + + PullTypeResolutionContext.prototype.doneResolvingTypeArguments = function () { + this.genericASTResolutionStack.length--; + }; + return PullTypeResolutionContext; + })(); + TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SymbolAndDiagnostics = (function () { + function SymbolAndDiagnostics(symbol, symbolAlias, diagnostics) { + this.symbol = symbol; + this.symbolAlias = symbolAlias; + this.diagnostics = diagnostics; + } + SymbolAndDiagnostics.create = function (symbol, diagnostics) { + return new SymbolAndDiagnostics(symbol, null, diagnostics); + }; + + SymbolAndDiagnostics.empty = function () { + return SymbolAndDiagnostics._empty; + }; + + SymbolAndDiagnostics.fromSymbol = function (symbol) { + return new SymbolAndDiagnostics(symbol, null, null); + }; + + SymbolAndDiagnostics.fromAlias = function (symbol, alias) { + return new SymbolAndDiagnostics(symbol, alias, null); + }; + + SymbolAndDiagnostics.prototype.addDiagnostic = function (diagnostic) { + TypeScript.Debug.assert(this !== SymbolAndDiagnostics._empty); + + if (this.diagnostics === null) { + this.diagnostics = []; + } + + this.diagnostics.push(diagnostic); + }; + + SymbolAndDiagnostics.prototype.withoutDiagnostics = function () { + if (!this.diagnostics) { + return this; + } + + return SymbolAndDiagnostics.fromSymbol(this.symbol); + }; + SymbolAndDiagnostics._empty = new SymbolAndDiagnostics(null, null, null); + return SymbolAndDiagnostics; + })(); + TypeScript.SymbolAndDiagnostics = SymbolAndDiagnostics; + + var PullResolutionDataCache = (function () { + function PullResolutionDataCache() { + this.cacheSize = 16; + this.rdCache = []; + this.nextUp = 0; + for (var i = 0; i < this.cacheSize; i++) { + this.rdCache[i] = { + actuals: [], + exactCandidates: [], + conversionCandidates: [], + id: i + }; + } + } + PullResolutionDataCache.prototype.getResolutionData = function () { + var rd = null; + + if (this.nextUp < this.cacheSize) { + rd = this.rdCache[this.nextUp]; + } + + if (rd === null) { + this.cacheSize++; + rd = { + actuals: [], + exactCandidates: [], + conversionCandidates: [], + id: this.cacheSize + }; + this.rdCache[this.cacheSize] = rd; + } + + this.nextUp++; + + return rd; + }; + + PullResolutionDataCache.prototype.returnResolutionData = function (rd) { + rd.actuals.length = 0; + rd.exactCandidates.length = 0; + rd.conversionCandidates.length = 0; + + this.nextUp = rd.id; + }; + return PullResolutionDataCache; + })(); + TypeScript.PullResolutionDataCache = PullResolutionDataCache; + + var PullAdditionalCallResolutionData = (function () { + function PullAdditionalCallResolutionData() { + this.targetSymbol = null; + this.targetTypeSymbol = null; + this.resolvedSignatures = null; + this.candidateSignature = null; + this.actualParametersContextTypeSymbols = null; + } + return PullAdditionalCallResolutionData; + })(); + TypeScript.PullAdditionalCallResolutionData = PullAdditionalCallResolutionData; + + var PullAdditionalObjectLiteralResolutionData = (function () { + function PullAdditionalObjectLiteralResolutionData() { + this.membersContextTypeSymbols = null; + } + return PullAdditionalObjectLiteralResolutionData; + })(); + TypeScript.PullAdditionalObjectLiteralResolutionData = PullAdditionalObjectLiteralResolutionData; + + var PullTypeResolver = (function () { + function PullTypeResolver(compilationSettings, semanticInfoChain, unitPath) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this.unitPath = unitPath; + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this.cachedFunctionArgumentsSymbol = null; + this.assignableCache = {}; + this.subtypeCache = {}; + this.identicalCache = {}; + this.resolutionDataCache = new PullResolutionDataCache(); + this.currentUnit = null; + this.cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 1024 /* Variable */); + this.cachedFunctionArgumentsSymbol.setType(this.cachedIArgumentsInterfaceType() ? this.cachedIArgumentsInterfaceType() : this.semanticInfoChain.anyTypeSymbol); + this.cachedFunctionArgumentsSymbol.setResolved(); + + var functionArgumentsDecl = new TypeScript.PullDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, new TypeScript.TextSpan(0, 0), unitPath); + functionArgumentsDecl.setSymbol(this.cachedFunctionArgumentsSymbol); + this.cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); + + this.currentUnit = this.semanticInfoChain.getUnit(unitPath); + } + PullTypeResolver.prototype.cleanCachedGlobals = function () { + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this.cachedFunctionArgumentsSymbol = null; + + this.identicalCache = {}; + this.subtypeCache = {}; + this.assignableCache = {}; + }; + + PullTypeResolver.prototype.cachedArrayInterfaceType = function () { + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */); + } + + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedArrayInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedArrayInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedArrayInterfaceType; + }; + + PullTypeResolver.prototype.getCachedArrayType = function () { + return this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.cachedNumberInterfaceType = function () { + if (!this._cachedNumberInterfaceType) { + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */); + } + + if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedNumberInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedNumberInterfaceType; + }; + + PullTypeResolver.prototype.cachedStringInterfaceType = function () { + if (!this._cachedStringInterfaceType) { + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */); + } + + if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedStringInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedStringInterfaceType; + }; + + PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { + if (!this._cachedBooleanInterfaceType) { + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */); + } + + if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedBooleanInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedBooleanInterfaceType; + }; + + PullTypeResolver.prototype.cachedObjectInterfaceType = function () { + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */); + } + + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedObjectInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedObjectInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { + if (!this._cachedFunctionInterfaceType) { + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */); + } + + if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedFunctionInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedFunctionInterfaceType; + }; + + PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { + if (!this._cachedIArgumentsInterfaceType) { + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */); + } + + if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedIArgumentsInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedIArgumentsInterfaceType; + }; + + PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { + if (!this._cachedRegExpInterfaceType) { + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */); + } + + if (!this._cachedRegExpInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedRegExpInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedRegExpInterfaceType; + }; + + PullTypeResolver.prototype.getUnitPath = function () { + return this.unitPath; + }; + + PullTypeResolver.prototype.setUnitPath = function (unitPath) { + this.unitPath = unitPath; + + this.currentUnit = this.semanticInfoChain.getUnit(unitPath); + }; + + PullTypeResolver.prototype.getDeclForAST = function (ast) { + return this.semanticInfoChain.getDeclForAST(ast, this.unitPath); + }; + + PullTypeResolver.prototype.getSymbolAndDiagnosticsForAST = function (ast) { + return this.semanticInfoChain.getSymbolAndDiagnosticsForAST(ast, this.unitPath); + }; + + PullTypeResolver.prototype.setSymbolAndDiagnosticsForAST = function (ast, symbolAndDiagnostics, context) { + if (context && (context.inProvisionalResolution() || context.inSpecialization)) { + return; + } + + this.semanticInfoChain.setSymbolAndDiagnosticsForAST(ast, symbolAndDiagnostics, this.unitPath); + }; + + PullTypeResolver.prototype.getASTForSymbol = function (symbol) { + return this.semanticInfoChain.getASTForSymbol(symbol, this.unitPath); + }; + + PullTypeResolver.prototype.getASTForDecl = function (decl) { + return this.semanticInfoChain.getASTForDecl(decl); + }; + + PullTypeResolver.prototype.getNewErrorTypeSymbol = function (diagnostic, data) { + return new TypeScript.PullErrorTypeSymbol(diagnostic, this.semanticInfoChain.anyTypeSymbol, data); + }; + + PullTypeResolver.prototype.getEnclosingDecl = function (decl) { + var declPath = TypeScript.getPathToDecl(decl); + + if (!declPath.length) { + return null; + } else if (declPath.length > 1 && declPath[declPath.length - 1] === decl) { + return declPath[declPath.length - 2]; + } else { + return declPath[declPath.length - 1]; + } + }; + + PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { + if (!(symbol.getKind() & (65536 /* Method */ | 4096 /* Property */))) { + var containerType = !parent.isContainer() ? parent.getAssociatedContainerType() : parent; + + if (containerType && containerType.isContainer() && !TypeScript.PullHelpers.symbolIsEnum(parent)) { + if (symbol.hasFlag(1 /* Exported */)) { + return symbol; + } + + return null; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.getMemberSymbol = function (symbolName, declSearchKind, parent, searchContainedMembers) { + if (typeof searchContainedMembers === "undefined") { searchContainedMembers = false; } + var member = null; + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + member = parent.findMember(symbolName); + } else { + member = parent.findNestedType(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var containerType = parent.getAssociatedContainerType(); + + if (containerType) { + if (containerType.isClass()) { + return null; + } + + parent = containerType; + } + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + member = parent.findMember(symbolName); + } else { + member = parent.findNestedType(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var typeDeclarations = parent.getDeclarations(); + var childDecls = null; + + for (var j = 0; j < typeDeclarations.length; j++) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); + } + } + }; + + PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var symbol = null; + + var decl = null; + var childDecls; + var declSymbol = null; + var declMembers; + var pathDeclKind; + var valDecl = null; + var kind; + var instanceSymbol = null; + var instanceType = null; + var childSymbol = null; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.getKind(); + + if (decl.getFlags() & 2097152 /* DeclaredInAWithBlock */) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (pathDeclKind & (4 /* Container */ | 32 /* DynamicModule */)) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return childDecls[0].getSymbol(); + } + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + valDecl = childDecls[0]; + + if (valDecl) { + return valDecl.getSymbol(); + } + } + + instanceSymbol = (decl.getSymbol()).getInstanceSymbol(); + + if (instanceSymbol) { + instanceType = instanceSymbol.getType(); + + childSymbol = this.getMemberSymbol(symbolName, declSearchKind, instanceType); + + if (childSymbol && (childSymbol.getKind() & declSearchKind)) { + return childSymbol; + } + } + + childDecls = decl.searchChildDecls(symbolName, 256 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + + if (sym.isAlias()) { + return sym; + } + } + + valDecl = decl.getValueDecl(); + + if (valDecl) { + decl = valDecl; + } + } + + declSymbol = decl.getSymbol().getType(); + + var childSymbol = this.getMemberSymbol(symbolName, declSearchKind, declSymbol); + + if (childSymbol) { + return childSymbol; + } + } else if ((declSearchKind & (TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer)) || !(pathDeclKind & 8 /* Class */)) { + var candidateSymbol = null; + + if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === (decl).getFunctionExpressionName()) { + candidateSymbol = decl.getSymbol(); + } + + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + if (decl.getKind() & TypeScript.PullElementKind.SomeFunction) { + decl.ensureSymbolIsBound(); + } + return childDecls[0].getSymbol(); + } + + if (candidateSymbol) { + return candidateSymbol; + } + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + childDecls = decl.searchChildDecls(symbolName, 256 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + + if (sym.isAlias()) { + return sym; + } + } + } + } + } + + symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + + return symbol; + }; + + PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { + var result = []; + var decl = null; + var childDecls; + var pathDeclKind; + var parameters; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.getKind(); + var declSymbol = decl.getSymbol(); + var declKind = decl.getKind(); + + if (declKind !== 8 /* Class */ && declKind !== 16 /* Interface */) { + this.addFilteredDecls(decl.getChildDecls(), declSearchKind, result); + } + + switch (declKind) { + case 4 /* Container */: + case 32 /* DynamicModule */: + if (declSymbol) { + var otherDecls = declSymbol.getDeclarations(); + for (var j = 0, m = otherDecls.length; j < m; j++) { + var otherDecl = otherDecls[j]; + if (otherDecl === decl) { + continue; + } + + var otherDeclChildren = otherDecl.getChildDecls(); + for (var k = 0, s = otherDeclChildren.length; k < s; k++) { + var otherDeclChild = otherDeclChildren[k]; + if ((otherDeclChild.getFlags() & 1 /* Exported */) && (otherDeclChild.getKind() & declSearchKind)) { + result.push(otherDeclChild); + } + } + } + } + + break; + + case 8 /* Class */: + case 16 /* Interface */: + if (declSymbol && declSymbol.isGeneric()) { + parameters = declSymbol.getTypeParameters(); + for (var k = 0; k < parameters.length; k++) { + result.push(parameters[k].getDeclarations()[0]); + } + } + + break; + + case 131072 /* FunctionExpression */: + var functionExpressionName = (decl).getFunctionExpressionName(); + if (declSymbol && functionExpressionName) { + result.push(declSymbol.getDeclarations()[0]); + } + + case 16384 /* Function */: + case 32768 /* ConstructorMethod */: + case 65536 /* Method */: + if (declSymbol) { + var functionType = declSymbol.getType(); + if (functionType.getHasGenericSignature()) { + var signatures = (pathDeclKind === 32768 /* ConstructorMethod */) ? functionType.getConstructSignatures() : functionType.getCallSignatures(); + if (signatures && signatures.length) { + for (var j = 0; j < signatures.length; j++) { + var signature = signatures[j]; + if (signature.isGeneric()) { + parameters = signature.getTypeParameters(); + for (var k = 0; k < parameters.length; k++) { + result.push(parameters[k].getDeclarations()[0]); + } + } + } + } + } + } + + break; + } + } + + var units = this.semanticInfoChain.units; + for (var i = 0, n = units.length; i < n; i++) { + var unit = units[i]; + if (unit === this.currentUnit && declPath.length != 0) { + continue; + } + var topLevelDecls = unit.getTopLevelDecls(); + if (topLevelDecls.length) { + for (var j = 0, m = topLevelDecls.length; j < m; j++) { + var topLevelDecl = topLevelDecls[j]; + if (topLevelDecl.getKind() === 1 /* Script */ || topLevelDecl.getKind() === 0 /* Global */) { + this.addFilteredDecls(topLevelDecl.getChildDecls(), declSearchKind, result); + } + } + } + } + + return result; + }; + + PullTypeResolver.prototype.addFilteredDecls = function (decls, declSearchKind, result) { + if (decls.length) { + for (var i = 0, n = decls.length; i < n; i++) { + var decl = decls[i]; + if (decl.getKind() & declSearchKind) { + result.push(decl); + } + } + } + }; + + PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl, context) { + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + + if (enclosingDecl && !declPath.length) { + declPath = [enclosingDecl]; + } + + var declSearchKind = TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer | TypeScript.PullElementKind.SomeValue; + + return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); + }; + + PullTypeResolver.prototype.getVisibleContextSymbols = function (enclosingDecl, context) { + var contextualTypeSymbol = context.getContextualType(); + if (!contextualTypeSymbol || this.isAnyOrEquivalent(contextualTypeSymbol)) { + return null; + } + + var declSearchKind = TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer | TypeScript.PullElementKind.SomeValue; + var members = contextualTypeSymbol.getAllMembers(declSearchKind, false); + + for (var i = 0; i < members.length; i++) { + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { + var prevCanUseTypeSymbol = context.canUseTypeSymbol; + context.canUseTypeSymbol = true; + var lhs = this.resolveAST(expression, false, enclosingDecl, context).symbol; + context.canUseTypeSymbol = prevCanUseTypeSymbol; + var lhsType = lhs.getType(); + + if (!lhsType) { + return null; + } + + if (this.isAnyOrEquivalent(lhsType)) { + return null; + } + + if (!lhsType.isResolved()) { + this.resolveDeclaredSymbol(lhsType, enclosingDecl, context); + } + + var includePrivate = false; + var containerSymbol = lhsType; + if (containerSymbol.getKind() === 33554432 /* ConstructorType */) { + containerSymbol = containerSymbol.getConstructSignatures()[0].getReturnType(); + } + + if (containerSymbol && containerSymbol.isClass()) { + var declPath = TypeScript.getPathToDecl(enclosingDecl); + if (declPath && declPath.length) { + var declarations = containerSymbol.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + var declaration = declarations[i]; + if (declPath.indexOf(declaration) >= 0) { + includePrivate = true; + break; + } + } + } + } + + var declSearchKind = TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer | TypeScript.PullElementKind.SomeValue; + + var members = []; + + if (lhsType.isContainer()) { + if ((lhsType).getExportAssignedContainerSymbol()) { + lhsType = (lhsType).getExportAssignedContainerSymbol(); + } + } + + if (lhsType.isTypeParameter()) { + var constraint = (lhsType).getConstraint(); + + if (constraint) { + lhsType = constraint; + members = lhsType.getAllMembers(declSearchKind, false); + } + } else { + if (lhs.getKind() == 67108864 /* EnumMember */) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } + + if (lhsType === this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { + lhsType = this.cachedNumberInterfaceType(); + } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { + lhsType = this.cachedStringInterfaceType(); + } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { + lhsType = this.cachedBooleanInterfaceType(); + } + + if (!lhsType.isResolved()) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, enclosingDecl, context); + + if (potentiallySpecializedType != lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + members = lhsType.getAllMembers(declSearchKind, includePrivate); + + if (lhsType.isContainer()) { + var associatedInstance = (lhsType).getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.getType(); + if (!instanceType.isResolved()) { + this.resolveDeclaredSymbol(instanceType, enclosingDecl, context); + } + var instanceMembers = instanceType.getAllMembers(declSearchKind, includePrivate); + members = members.concat(instanceMembers); + } + } else if (lhsType.isConstructor()) { + var prototypeStr = "prototype"; + var prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); + var parentDecl = lhsType.getDeclarations()[0]; + var prototypeDecl = new TypeScript.PullDecl(prototypeStr, prototypeStr, parentDecl.getKind(), parentDecl.getFlags(), parentDecl.getSpan(), parentDecl.getScriptName()); + this.currentUnit.addSynthesizedDecl(prototypeDecl); + prototypeDecl.setParentDecl(parentDecl); + prototypeSymbol.addDeclaration(prototypeDecl); + + members.push(prototypeSymbol); + } else { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.getType(); + if (!containerType.isResolved()) { + this.resolveDeclaredSymbol(containerType, enclosingDecl, context); + } + var containerMembers = containerType.getAllMembers(declSearchKind, includePrivate); + members = members.concat(containerMembers); + } + } + } + + if (lhsType.getCallSignatures().length && this.cachedFunctionInterfaceType()) { + members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, false)); + } + + for (var i = 0; i < members.length; i++) { + if (!members[i].isResolved()) { + this.resolveDeclaredSymbol(members[i], enclosingDecl, context); + } + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.isAnyOrEquivalent = function (type) { + return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); + }; + + PullTypeResolver.prototype.isNumberOrEquivalent = function (type) { + return (type === this.semanticInfoChain.numberTypeSymbol) || (this.cachedNumberInterfaceType() && type === this.cachedNumberInterfaceType()); + }; + + PullTypeResolver.prototype.isTypeArgumentOrWrapper = function (type) { + if (!type) { + return false; + } + + if (!type.isGeneric()) { + return false; + } + + if (type.isTypeParameter()) { + return true; + } + + if (type.isArray()) { + return this.isTypeArgumentOrWrapper((type).getElementType()); + } + + var typeArguments = type.getTypeArguments(); + + if (typeArguments) { + for (var i = 0; i < typeArguments.length; i++) { + if (this.isTypeArgumentOrWrapper(typeArguments[i])) { + return true; + } + } + } else { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.isArrayOrEquivalent = function (type) { + return (type.isArray() && (type).getElementType()) || type == this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.findTypeSymbolForDynamicModule = function (idText, currentFileName, search) { + var originalIdText = idText; + var symbol = search(idText); + + if (symbol === null) { + if (!symbol) { + idText = TypeScript.swapQuotes(originalIdText); + symbol = search(idText); + } + + if (!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".ts"; + symbol = search(idText); + } + + if (!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; + symbol = search(idText); + } + + if (!symbol && !TypeScript.isRelative(originalIdText)) { + idText = originalIdText; + + var strippedIdText = TypeScript.stripQuotes(idText); + + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + + while (symbol === null && path != "") { + idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); + symbol = search(idText); + + if (symbol === null) { + idText = TypeScript.changePathToDTS(idText); + symbol = search(idText); + } + + if (symbol === null) { + if (path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbol = function (symbol, enclosingDecl, context) { + var savedResolvingTypeReference = context.resolvingTypeReference; + context.resolvingTypeReference = false; + + var result = this.resolveDeclaredSymbolWorker(symbol, enclosingDecl, context); + context.resolvingTypeReference = savedResolvingTypeReference; + + return result; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbolWorker = function (symbol, enclosingDecl, context) { + if (!symbol || symbol.isResolved()) { + return symbol; + } + + if (symbol.isResolving()) { + if (!symbol.currentlyBeingSpecialized()) { + if (!symbol.isType()) { + symbol.setType(this.semanticInfoChain.anyTypeSymbol); + } + + return symbol; + } + } + + var thisUnit = this.unitPath; + + var decls = symbol.getDeclarations(); + + var ast = null; + + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + + ast = this.semanticInfoChain.getASTForDecl(decl); + + if (!ast || ast.nodeType === 80 /* Member */) { + this.setUnitPath(thisUnit); + return symbol; + } + + this.setUnitPath(decl.getScriptName()); + this.resolveAST(ast, false, enclosingDecl, context); + } + + var typeArgs = symbol.isType() ? (symbol).getTypeArguments() : null; + + if (typeArgs && typeArgs.length) { + var typeParameters = (symbol).getTypeParameters(); + var typeCache = {}; + + for (var i = 0; i < typeParameters.length; i++) { + typeCache[typeParameters[i].getSymbolID().toString()] = typeArgs[i]; + } + + context.pushTypeSpecializationCache(typeCache); + var rootType = TypeScript.getRootType(symbol.getType()); + + var specializedSymbol = TypeScript.specializeType(rootType, typeArgs, this, enclosingDecl, context, ast); + + context.popTypeSpecializationCache(); + + symbol = specializedSymbol; + } + + this.setUnitPath(thisUnit); + + return symbol; + }; + + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { + var containerDecl = this.getDeclForAST(ast); + var containerSymbol = containerDecl.getSymbol(); + + if (containerSymbol.isResolved()) { + return containerSymbol; + } + + containerSymbol.setResolved(); + + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + if (containerDecl.getKind() != 64 /* Enum */) { + var instanceSymbol = containerSymbol.getInstanceSymbol(); + + if (instanceSymbol) { + this.resolveDeclaredSymbol(instanceSymbol, containerDecl.getParentDecl(), context); + } + + var members = ast.members.members; + + for (var i = 0; i < members.length; i++) { + if (members[i].nodeType == 87 /* ExportAssignment */) { + this.resolveExportAssignmentStatement(members[i], containerDecl, context); + break; + } + } + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (typeRef) { + if (typeRef.nodeType != 11 /* TypeRef */) { + return false; + } + + if (typeRef.term.nodeType == 20 /* Name */) { + return true; + } else if (typeRef.term.nodeType == 32 /* MemberAccessExpression */) { + var binex = typeRef.term; + + if (binex.operand2.nodeType == 20 /* Name */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.resolveReferenceTypeDeclaration = function (typeDeclAST, context) { + var typeDecl = this.getDeclForAST(typeDeclAST); + var enclosingDecl = this.getEnclosingDecl(typeDecl); + var typeDeclSymbol = typeDecl.getSymbol(); + var typeDeclIsClass = typeDeclAST.nodeType === 13 /* ClassDeclaration */; + var hasVisited = this.getSymbolAndDiagnosticsForAST(typeDeclAST) != null; + var extendedTypes = []; + var implementedTypes = []; + + if ((typeDeclSymbol.isResolved() && hasVisited) || (typeDeclSymbol.isResolving() && !context.isInBaseTypeResolution())) { + return typeDeclSymbol; + } + + var wasResolving = typeDeclSymbol.isResolving(); + typeDeclSymbol.startResolving(); + + if (!typeDeclSymbol.isResolved()) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], typeDecl, context); + } + } + + var typeRefDecls = typeDeclSymbol.getDeclarations(); + + for (var i = 0; i < typeRefDecls.length; i++) { + var childDecls = typeRefDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + var wasInBaseTypeResolution = context.startBaseTypeResolution(); + + if (!typeDeclIsClass && !hasVisited) { + typeDeclSymbol.resetKnownBaseTypeCount(); + } + + if (typeDeclAST.extendsList) { + var savedIsResolvingClassExtendedType = context.isResolvingClassExtendedType; + if (typeDeclIsClass) { + context.isResolvingClassExtendedType = true; + } + + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < typeDeclAST.extendsList.members.length; i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var parentType = this.resolveTypeReference(new TypeScript.TypeReference(typeDeclAST.extendsList.members[i], 0), typeDecl, context).symbol; + + if (typeDeclSymbol.isValidBaseKind(parentType, true)) { + var resolvedParentType = parentType; + extendedTypes[extendedTypes.length] = parentType; + if (parentType.isGeneric() && parentType.isResolved() && !parentType.getIsSpecialized()) { + parentType = this.specializeTypeToAny(parentType, enclosingDecl, context); + typeDecl.addDiagnostic(new TypeScript.Diagnostic(typeDecl.getScriptName(), typeDeclAST.minChar, typeDeclAST.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */)); + } + if (!typeDeclSymbol.hasBase(parentType)) { + this.setSymbolAndDiagnosticsForAST(typeDeclAST.extendsList.members[i], SymbolAndDiagnostics.fromSymbol(resolvedParentType), context); + typeDeclSymbol.addExtendedType(parentType); + + var specializations = typeDeclSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + specializations[j].addExtendedType(parentType); + } + } + } + } + + context.isResolvingClassExtendedType = savedIsResolvingClassExtendedType; + } + + if (!typeDeclSymbol.isResolved() && !wasResolving) { + var baseTypeSymbols = typeDeclSymbol.getExtendedTypes(); + for (var i = 0; i < baseTypeSymbols.length; i++) { + var baseType = baseTypeSymbols[i]; + + for (var j = 0; j < extendedTypes.length; j++) { + if (baseType == extendedTypes[j]) { + break; + } + } + + if (j == extendedTypes.length) { + typeDeclSymbol.removeExtendedType(baseType); + } + } + } + + if (typeDeclAST.implementsList && typeDeclIsClass) { + var extendsCount = typeDeclAST.extendsList ? typeDeclAST.extendsList.members.length : 0; + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < typeDeclAST.implementsList.members.length); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var implementedType = this.resolveTypeReference(new TypeScript.TypeReference(typeDeclAST.implementsList.members[i - extendsCount], 0), typeDecl, context).symbol; + + if (typeDeclSymbol.isValidBaseKind(implementedType, false)) { + var resolvedImplementedType = implementedType; + implementedTypes[implementedTypes.length] = implementedType; + if (implementedType.isGeneric() && implementedType.isResolved() && !implementedType.getIsSpecialized()) { + implementedType = this.specializeTypeToAny(implementedType, enclosingDecl, context); + typeDecl.addDiagnostic(new TypeScript.Diagnostic(typeDecl.getScriptName(), typeDeclAST.minChar, typeDeclAST.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */)); + this.setSymbolAndDiagnosticsForAST(typeDeclAST.implementsList.members[i - extendsCount], SymbolAndDiagnostics.fromSymbol(implementedType), context); + typeDeclSymbol.addImplementedType(implementedType); + } else if (!typeDeclSymbol.hasBase(implementedType)) { + this.setSymbolAndDiagnosticsForAST(typeDeclAST.implementsList.members[i - extendsCount], SymbolAndDiagnostics.fromSymbol(resolvedImplementedType), context); + typeDeclSymbol.addImplementedType(implementedType); + } + } + } + } + + if (!typeDeclSymbol.isResolved() && !wasResolving) { + var baseTypeSymbols = typeDeclSymbol.getImplementedTypes(); + for (var i = 0; i < baseTypeSymbols.length; i++) { + var baseType = baseTypeSymbols[i]; + + for (var j = 0; j < implementedTypes.length; j++) { + if (baseType == implementedTypes[j]) { + break; + } + } + + if (j == implementedTypes.length) { + typeDeclSymbol.removeImplementedType(baseType); + } + } + } + + context.doneBaseTypeResolution(wasInBaseTypeResolution); + if (wasInBaseTypeResolution && (typeDeclAST.implementsList || typeDeclAST.extendsList)) { + return typeDeclSymbol; + } + + if (!typeDeclSymbol.isResolved()) { + var typeDeclMembers = typeDeclSymbol.getMembers(); + for (var i = 0; i < typeDeclMembers.length; i++) { + this.resolveDeclaredSymbol(typeDeclMembers[i], typeDecl, context); + } + + if (!typeDeclIsClass) { + var callSignatures = typeDeclSymbol.getCallSignatures(); + for (var i = 0; i < callSignatures.length; i++) { + this.resolveDeclaredSymbol(callSignatures[i], typeDecl, context); + } + + var constructSignatures = typeDeclSymbol.getConstructSignatures(); + for (var i = 0; i < constructSignatures.length; i++) { + this.resolveDeclaredSymbol(constructSignatures[i], typeDecl, context); + } + + var indexSignatures = typeDeclSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignatures.length; i++) { + this.resolveDeclaredSymbol(indexSignatures[i], typeDecl, context); + } + } + } + + this.setSymbolAndDiagnosticsForAST(typeDeclAST.name, SymbolAndDiagnostics.fromSymbol(typeDeclSymbol), context); + this.setSymbolAndDiagnosticsForAST(typeDeclAST, SymbolAndDiagnostics.fromSymbol(typeDeclSymbol), context); + + typeDeclSymbol.setResolved(); + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { + var classDecl = this.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + if (classDeclSymbol.isResolved()) { + return classDeclSymbol; + } + + this.resolveReferenceTypeDeclaration(classDeclAST, context); + + var constructorMethod = classDeclSymbol.getConstructorMethod(); + var extendedTypes = classDeclSymbol.getExtendedTypes(); + var parentType = extendedTypes.length ? extendedTypes[0] : null; + + if (constructorMethod) { + var constructorTypeSymbol = constructorMethod.getType(); + + var constructSignatures = constructorTypeSymbol.getConstructSignatures(); + + if (!constructSignatures.length) { + var constructorSignature; + + if (parentType) { + var parentClass = parentType; + var parentConstructor = parentClass.getConstructorMethod(); + var parentConstructorType = parentConstructor.getType(); + var parentConstructSignatures = parentConstructorType.getConstructSignatures(); + + var parentConstructSignature; + var parentParameters; + for (var i = 0; i < parentConstructSignatures.length; i++) { + parentConstructSignature = parentConstructSignatures[i]; + parentParameters = parentConstructSignature.getParameters(); + + constructorSignature = parentConstructSignature.isDefinition() ? new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + constructorSignature.setReturnType(classDeclSymbol); + + for (var j = 0; j < parentParameters.length; j++) { + constructorSignature.addParameter(parentParameters[j], parentParameters[j].getIsOptional()); + } + + var typeParameters = constructorTypeSymbol.getTypeParameters(); + + for (var j = 0; j < typeParameters.length; j++) { + constructorSignature.addTypeParameter(typeParameters[j]); + } + + constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorSignature.addDeclaration(classDecl); + } + } else { + constructorSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + constructorSignature.setReturnType(classDeclSymbol); + constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorSignature.addDeclaration(classDecl); + + var typeParameters = constructorTypeSymbol.getTypeParameters(); + + for (var i = 0; i < typeParameters.length; i++) { + constructorSignature.addTypeParameter(typeParameters[i]); + } + } + } + + if (!classDeclSymbol.isResolved()) { + return classDeclSymbol; + } + + var constructorMembers = constructorTypeSymbol.getMembers(); + + this.resolveDeclaredSymbol(constructorMethod, classDecl, context); + + for (var i = 0; i < constructorMembers.length; i++) { + this.resolveDeclaredSymbol(constructorMembers[i], classDecl, context); + } + + if (parentType) { + var parentConstructorSymbol = (parentType).getConstructorMethod(); + var parentConstructorTypeSymbol = parentConstructorSymbol.getType(); + + if (!constructorTypeSymbol.hasBase(parentConstructorTypeSymbol)) { + constructorTypeSymbol.addExtendedType(parentConstructorTypeSymbol); + } + } + } + + return classDeclSymbol; + }; + + PullTypeResolver.prototype.resolveInterfaceDeclaration = function (interfaceDeclAST, context) { + var interfaceDecl = this.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveReferenceTypeDeclaration(interfaceDeclAST, context); + return interfaceDeclSymbol; + }; + + PullTypeResolver.prototype.resolveImportDeclaration = function (importStatementAST, context) { + var _this = this; + var importDecl = this.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + var aliasName = importStatementAST.id.text; + var aliasedType = null; + + if (importDeclSymbol.isResolved()) { + return importDeclSymbol; + } + + importDeclSymbol.startResolving(); + + if (importStatementAST.alias.nodeType === 11 /* TypeRef */) { + aliasedType = this.resolveTypeReference(importStatementAST.alias, enclosingDecl, context).symbol; + } else if (importStatementAST.alias.nodeType === 20 /* Name */) { + var text = (importStatementAST.alias).actualText; + + if (!TypeScript.isQuoted(text)) { + aliasedType = this.resolveTypeReference(new TypeScript.TypeReference(importStatementAST.alias, 0), enclosingDecl, context).symbol; + } else { + var modPath = (importStatementAST.alias).actualText; + var declPath = TypeScript.getPathToDecl(enclosingDecl); + + importStatementAST.isDynamicImport = true; + + aliasedType = this.findTypeSymbolForDynamicModule(modPath, importDecl.getScriptName(), function (s) { + return _this.getSymbolFromDeclPath(s, declPath, TypeScript.PullElementKind.SomeContainer); + }); + + if (!aliasedType) { + importDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.currentUnit.getPath(), importStatementAST.minChar, importStatementAST.getLength(), 140 /* Unable_to_resolve_external_module__0_ */, [text])); + aliasedType = this.semanticInfoChain.anyTypeSymbol; + } + } + } + + if (aliasedType) { + if (!aliasedType.isContainer()) { + importDecl.addDiagnostic(new TypeScript.Diagnostic(this.currentUnit.getPath(), importStatementAST.minChar, importStatementAST.getLength(), 141 /* Module_cannot_be_aliased_to_a_non_module_type */)); + aliasedType = this.semanticInfoChain.anyTypeSymbol; + } else if ((aliasedType).getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + + importDeclSymbol.setAliasedType(aliasedType); + importDeclSymbol.setResolved(); + + this.semanticInfoChain.setSymbolAndDiagnosticsForAST(importStatementAST.alias, SymbolAndDiagnostics.fromSymbol(aliasedType), this.unitPath); + } + + return importDeclSymbol; + }; + + PullTypeResolver.prototype.resolveExportAssignmentStatement = function (exportAssignmentAST, enclosingDecl, context) { + var id = exportAssignmentAST.id.text; + var valueSymbol = null; + var typeSymbol = null; + var containerSymbol = null; + + var parentSymbol = enclosingDecl.getSymbol(); + + if (!parentSymbol.isType() && (parentSymbol).isContainer()) { + enclosingDecl.addDiagnostic(new TypeScript.Diagnostic(enclosingDecl.getScriptName(), exportAssignmentAST.minChar, exportAssignmentAST.getLength(), 230 /* Export_assignments_may_only_be_used_in_External_modules */)); + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var declPath = enclosingDecl !== null ? [enclosingDecl] : []; + + containerSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeContainer); + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.getKind() & TypeScript.PullElementKind.AcceptableAlias) != 0; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.getKind() == 256 /* TypeAlias */) { + if (!containerSymbol.isResolved()) { + this.resolveDeclaredSymbol(containerSymbol, enclosingDecl, context); + } + var aliasedType = (containerSymbol).getType(); + + if (aliasedType.getKind() != 32 /* DynamicModule */) { + acceptableAlias = true; + } else { + var aliasedAssignedValue = (containerSymbol).getExportAssignedValueSymbol(); + var aliasedAssignedType = (containerSymbol).getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = (containerSymbol).getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + if (aliasedAssignedValue) { + valueSymbol = aliasedAssignedValue; + } + if (aliasedAssignedType) { + typeSymbol = aliasedAssignedType; + } + if (aliasedAssignedContainer) { + containerSymbol = aliasedAssignedContainer; + } + acceptableAlias = true; + } + } + } + + if (!acceptableAlias) { + enclosingDecl.addDiagnostic(new TypeScript.Diagnostic(enclosingDecl.getScriptName(), exportAssignmentAST.minChar, exportAssignmentAST.getLength(), 231 /* Export_assignments_may_only_be_made_with_acceptable_kinds */)); + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + } + + if (!valueSymbol) { + valueSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeValue); + } + if (!typeSymbol) { + typeSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeType); + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + return SymbolAndDiagnostics.create(this.semanticInfoChain.voidTypeSymbol, [context.postError(enclosingDecl.getScriptName(), exportAssignmentAST.minChar, exportAssignmentAST.getLength(), 164 /* Could_not_find_symbol__0_ */, [id])]); + } + + if (valueSymbol) { + if (!valueSymbol.isResolved()) { + this.resolveDeclaredSymbol(valueSymbol, enclosingDecl, context); + } + (parentSymbol).setExportAssignedValueSymbol(valueSymbol); + } + if (typeSymbol) { + if (!typeSymbol.isResolved()) { + this.resolveDeclaredSymbol(typeSymbol, enclosingDecl, context); + } + + (parentSymbol).setExportAssignedTypeSymbol(typeSymbol); + } + if (containerSymbol) { + if (!containerSymbol.isResolved()) { + this.resolveDeclaredSymbol(containerSymbol, enclosingDecl, context); + } + + (parentSymbol).setExportAssignedContainerSymbol(containerSymbol); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignature = function (funcDeclAST, enclosingDecl, context) { + var funcDeclSymbol = null; + + var functionDecl = this.getDeclForAST(funcDeclAST); + + if (!functionDecl || !functionDecl.hasSymbol()) { + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + if (enclosingDecl) { + declCollectionContext.pushParent(enclosingDecl); + } + + TypeScript.getAstWalkerFactory().walk(funcDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + functionDecl = this.getDeclForAST(funcDeclAST); + this.currentUnit.addSynthesizedDecl(functionDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + binder.setUnit(this.unitPath); + if (functionDecl.getKind() === 33554432 /* ConstructorType */) { + binder.bindConstructorTypeDeclarationToPullSymbol(functionDecl); + } else { + binder.bindFunctionTypeDeclarationToPullSymbol(functionDecl); + } + } + + funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.getKind() === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, enclosingDecl, context).symbol; + + signature.setReturnType(returnTypeSymbol); + + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + + if (funcDeclSymbol) { + funcDeclSymbol.getType().setHasGenericSignature(); + } + } + } else { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveFunctionTypeSignatureParameter(funcDeclAST.arguments.members[i], signature, enclosingDecl, context); + } + } + + if (funcDeclSymbol && signature.hasGenericParameter()) { + funcDeclSymbol.getType().setHasGenericSignature(); + } + + if (signature.hasGenericParameter()) { + if (funcDeclSymbol) { + funcDeclSymbol.getType().setHasGenericSignature(); + } + } + + funcDeclSymbol.setResolved(); + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignatureParameter = function (argDeclAST, signature, enclosingDecl, context) { + var paramDecl = this.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeExpr) { + var typeRef = this.resolveTypeReference(argDeclAST.typeExpr, enclosingDecl, context).symbol; + + if (paramSymbol.getIsVarArg() && !(typeRef.isArray() || typeRef == this.cachedArrayInterfaceType())) { + var diagnostic = context.postError(this.unitPath, argDeclAST.minChar, argDeclAST.getLength(), 228 /* Rest_parameters_must_be_array_types */, null, enclosingDecl); + typeRef = this.getNewErrorTypeSymbol(diagnostic); + } + + context.setTypeInContext(paramSymbol, typeRef); + + if (this.isTypeArgumentOrWrapper(typeRef)) { + signature.setHasGenericParameter(); + } + } else { + if (paramSymbol.getIsVarArg() && paramSymbol.getType()) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, TypeScript.specializeToArrayType(this.cachedArrayInterfaceType(), paramSymbol.getType(), this, context)); + } else { + context.setTypeInContext(paramSymbol, paramSymbol.getType()); + } + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveFunctionExpressionParameter = function (argDeclAST, contextParam, enclosingDecl, context) { + var paramDecl = this.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeExpr) { + var typeRef = this.resolveTypeReference(argDeclAST.typeExpr, enclosingDecl, context).symbol; + + if (paramSymbol.getIsVarArg() && !(typeRef.isArray() || typeRef == this.cachedArrayInterfaceType())) { + var diagnostic = context.postError(this.unitPath, argDeclAST.minChar, argDeclAST.getLength(), 228 /* Rest_parameters_must_be_array_types */, null, enclosingDecl); + typeRef = this.getNewErrorTypeSymbol(diagnostic); + } + + context.setTypeInContext(paramSymbol, typeRef); + } else { + if (paramSymbol.getIsVarArg() && paramSymbol.getType()) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, TypeScript.specializeToArrayType(this.cachedArrayInterfaceType(), paramSymbol.getType(), this, context)); + } else { + context.setTypeInContext(paramSymbol, paramSymbol.getType()); + } + } else if (contextParam) { + context.setTypeInContext(paramSymbol, contextParam.getType()); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveInterfaceTypeReference = function (interfaceDeclAST, enclosingDecl, context) { + var interfaceSymbol = null; + + var interfaceDecl = this.getDeclForAST(interfaceDeclAST); + + if (!interfaceDecl) { + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + if (enclosingDecl) { + declCollectionContext.pushParent(enclosingDecl); + } + + TypeScript.getAstWalkerFactory().walk(interfaceDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var interfaceDecl = this.getDeclForAST(interfaceDeclAST); + this.currentUnit.addSynthesizedDecl(interfaceDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + + binder.setUnit(this.unitPath); + binder.bindObjectTypeDeclarationToPullSymbol(interfaceDecl); + } + + interfaceSymbol = interfaceDecl.getSymbol(); + + if (interfaceDeclAST.members) { + var memberDecl = null; + var memberSymbol = null; + var memberType = null; + var typeMembers = interfaceDeclAST.members; + + for (var i = 0; i < typeMembers.members.length; i++) { + memberDecl = this.getDeclForAST(typeMembers.members[i]); + memberSymbol = (memberDecl.getKind() & TypeScript.PullElementKind.SomeSignature) ? memberDecl.getSignatureSymbol() : memberDecl.getSymbol(); + + this.resolveDeclaredSymbol(memberSymbol, enclosingDecl, context); + + memberType = memberSymbol.getType(); + + if ((memberType && memberType.isGeneric()) || (memberSymbol.isSignature() && (memberSymbol).isGeneric())) { + interfaceSymbol.setHasGenericMember(); + } + } + } + + interfaceSymbol.setResolved(); + + return interfaceSymbol; + }; + + PullTypeResolver.prototype.resolveTypeReference = function (typeRef, enclosingDecl, context) { + if (typeRef === null) { + return null; + } + + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(typeRef); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeTypeReferenceSymbol(typeRef, enclosingDecl, context); + + if (!symbolAndDiagnostics.symbol.isGeneric()) { + this.setSymbolAndDiagnosticsForAST(typeRef, symbolAndDiagnostics, context); + } + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (typeRef, enclosingDecl, context) { + var typeDeclSymbol = null; + var diagnostic = null; + var symbolAndDiagnostic = null; + + if (typeRef.term.nodeType === 20 /* Name */) { + var prevResolvingTypeReference = context.resolvingTypeReference; + context.resolvingTypeReference = true; + symbolAndDiagnostic = this.resolveTypeNameExpression(typeRef.term, enclosingDecl, context); + typeDeclSymbol = symbolAndDiagnostic.symbol; + + context.resolvingTypeReference = prevResolvingTypeReference; + } else if (typeRef.term.nodeType === 12 /* FunctionDeclaration */) { + typeDeclSymbol = this.resolveFunctionTypeSignature(typeRef.term, enclosingDecl, context); + } else if (typeRef.term.nodeType === 14 /* InterfaceDeclaration */) { + typeDeclSymbol = this.resolveInterfaceTypeReference(typeRef.term, enclosingDecl, context); + } else if (typeRef.term.nodeType === 10 /* GenericType */) { + symbolAndDiagnostic = this.resolveGenericTypeReference(typeRef.term, enclosingDecl, context); + typeDeclSymbol = symbolAndDiagnostic.symbol; + } else if (typeRef.term.nodeType === 32 /* MemberAccessExpression */) { + var dottedName = typeRef.term; + + prevResolvingTypeReference = context.resolvingTypeReference; + symbolAndDiagnostic = this.resolveDottedTypeNameExpression(dottedName, enclosingDecl, context); + typeDeclSymbol = symbolAndDiagnostic.symbol; + context.resolvingTypeReference = prevResolvingTypeReference; + } else if (typeRef.term.nodeType === 5 /* StringLiteral */) { + var stringConstantAST = typeRef.term; + typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.actualText); + var decl = new TypeScript.PullDecl(stringConstantAST.actualText, stringConstantAST.actualText, typeDeclSymbol.getKind(), null, new TypeScript.TextSpan(stringConstantAST.minChar, stringConstantAST.getLength()), enclosingDecl.getScriptName()); + this.currentUnit.addSynthesizedDecl(decl); + typeDeclSymbol.addDeclaration(decl); + } + + if (!typeDeclSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, typeRef.term.minChar, typeRef.term.getLength(), 146 /* Unable_to_resolve_type */)]); + } + + if (typeDeclSymbol.isError()) { + return SymbolAndDiagnostics.fromSymbol(typeDeclSymbol); + } + + if (typeRef.arrayCount) { + var arraySymbol = typeDeclSymbol.getArrayType(); + + if (!arraySymbol) { + if (!this.cachedArrayInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedArrayInterfaceType(), enclosingDecl, context); + } + + if (typeDeclSymbol.isNamedTypeSymbol() && typeDeclSymbol.isGeneric() && !typeDeclSymbol.isTypeParameter() && typeDeclSymbol.isResolved() && !typeDeclSymbol.getIsSpecialized() && typeDeclSymbol.getTypeParameters().length && (typeDeclSymbol.getTypeArguments() == null && !this.isArrayOrEquivalent(typeDeclSymbol)) && this.isTypeRefWithoutTypeArgs(typeRef)) { + context.postError(this.unitPath, typeRef.minChar, typeRef.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + typeDeclSymbol = this.specializeTypeToAny(typeDeclSymbol, enclosingDecl, context); + } + + arraySymbol = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, typeDeclSymbol, this, context); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (typeRef.arrayCount > 1) { + for (var arity = typeRef.arrayCount - 1; arity > 0; arity--) { + var existingArraySymbol = arraySymbol.getArrayType(); + + if (!existingArraySymbol) { + arraySymbol = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, arraySymbol, this, context); + } else { + arraySymbol = existingArraySymbol; + } + } + } + + typeDeclSymbol = arraySymbol; + } + + return SymbolAndDiagnostics.fromSymbol(typeDeclSymbol); + }; + + PullTypeResolver.prototype.resolveVariableDeclaration = function (varDecl, context, enclosingDecl) { + var decl = this.getDeclForAST(varDecl); + + if (enclosingDecl && decl.getKind() == 2048 /* Parameter */) { + enclosingDecl.ensureSymbolIsBound(); + } + + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (declSymbol.isResolved()) { + var declType = declSymbol.getType(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + var valSymbol = valDecl.getSymbol(); + + if (valSymbol && !valSymbol.isResolved()) { + valSymbol.setType(declType); + valSymbol.setResolved(); + } + } + + return declType; + } + + if (declSymbol.isResolving()) { + if (!context.inSpecialization) { + declSymbol.setType(this.semanticInfoChain.anyTypeSymbol); + declSymbol.setResolved(); + return declSymbol; + } + } + + declSymbol.startResolving(); + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + + var diagnostic = null; + + if (varDecl.typeExpr) { + var typeExprSymbol = this.resolveTypeReference(varDecl.typeExpr, wrapperDecl, context).symbol; + + if (!typeExprSymbol) { + diagnostic = context.postError(this.unitPath, varDecl.minChar, varDecl.getLength(), 147 /* Unable_to_resolve_type_of__0_ */, [varDecl.id.actualText], decl); + declSymbol.setType(this.getNewErrorTypeSymbol(diagnostic)); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else if (typeExprSymbol.isError()) { + context.setTypeInContext(declSymbol, typeExprSymbol); + } else { + if (typeExprSymbol.isNamedTypeSymbol() && typeExprSymbol.isGeneric() && !typeExprSymbol.isTypeParameter() && typeExprSymbol.isResolved() && !typeExprSymbol.getIsSpecialized() && typeExprSymbol.getTypeParameters().length && (typeExprSymbol.getTypeArguments() == null && !this.isArrayOrEquivalent(typeExprSymbol)) && this.isTypeRefWithoutTypeArgs(varDecl.typeExpr)) { + context.postError(this.unitPath, varDecl.typeExpr.minChar, varDecl.typeExpr.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + typeExprSymbol = this.specializeTypeToAny(typeExprSymbol, enclosingDecl, context); + } + + if (typeExprSymbol.isContainer()) { + var exportedTypeSymbol = (typeExprSymbol).getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceSymbol = (typeExprSymbol.getType()).getInstanceSymbol(); + + if (!instanceSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceSymbol)) { + typeExprSymbol = this.getNewErrorTypeSymbol(diagnostic); + } else { + typeExprSymbol = instanceSymbol.getType(); + } + } + } else if (declSymbol.getIsVarArg() && !(typeExprSymbol.isArray() || typeExprSymbol == this.cachedArrayInterfaceType())) { + var diagnostic = context.postError(this.unitPath, varDecl.minChar, varDecl.getLength(), 228 /* Rest_parameters_must_be_array_types */, null, enclosingDecl); + typeExprSymbol = this.getNewErrorTypeSymbol(diagnostic); + } + + context.setTypeInContext(declSymbol, typeExprSymbol); + + if (declParameterSymbol) { + declParameterSymbol.setType(typeExprSymbol); + } + + if ((varDecl.nodeType === 19 /* Parameter */) && enclosingDecl && ((typeExprSymbol.isGeneric() && !typeExprSymbol.isArray()) || this.isTypeArgumentOrWrapper(typeExprSymbol))) { + var signature = enclosingDecl.getSpecializingSignatureSymbol(); + + if (signature) { + signature.setHasGenericParameter(); + } + } + } + } else if (varDecl.init) { + var initExprSymbolAndDiagnostics = this.resolveAST(varDecl.init, false, wrapperDecl, context); + var initExprSymbol = initExprSymbolAndDiagnostics && initExprSymbolAndDiagnostics.symbol; + + if (!initExprSymbol) { + diagnostic = context.postError(this.unitPath, varDecl.minChar, varDecl.getLength(), 147 /* Unable_to_resolve_type_of__0_ */, [varDecl.id.actualText], decl); + + context.setTypeInContext(declSymbol, this.getNewErrorTypeSymbol(diagnostic)); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + context.setTypeInContext(declSymbol, this.widenType(initExprSymbol.getType())); + initExprSymbol.addOutgoingLink(declSymbol, 2 /* ProvidesInferredType */); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, initExprSymbol.getType()); + initExprSymbol.addOutgoingLink(declParameterSymbol, 2 /* ProvidesInferredType */); + } + } + } else if (declSymbol.getKind() === 4 /* Container */) { + instanceSymbol = (declSymbol).getInstanceSymbol(); + var instanceType = instanceSymbol.getType(); + + if (instanceType) { + context.setTypeInContext(declSymbol, instanceType); + } else { + context.setTypeInContext(declSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + var defaultType = this.semanticInfoChain.anyTypeSymbol; + + if (declSymbol.getIsVarArg()) { + defaultType = TypeScript.specializeToArrayType(this.cachedArrayInterfaceType(), defaultType, this, context); + } + + context.setTypeInContext(declSymbol, defaultType); + + if (declParameterSymbol) { + declParameterSymbol.setType(defaultType); + } + } + + declSymbol.setResolved(); + + if (declParameterSymbol) { + declParameterSymbol.setResolved(); + } + + return declSymbol; + }; + + PullTypeResolver.prototype.resolveTypeParameterDeclaration = function (typeParameterAST, context) { + var typeParameterDecl = this.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + if (typeParameterSymbol.isResolved() || typeParameterSymbol.isResolving()) { + return typeParameterSymbol; + } + + typeParameterSymbol.startResolving(); + + if (typeParameterAST.constraint) { + var enclosingDecl = this.getEnclosingDecl(typeParameterDecl); + var constraintTypeSymbol = this.resolveTypeReference(typeParameterAST.constraint, enclosingDecl, context).symbol; + + if (constraintTypeSymbol.isNamedTypeSymbol() && constraintTypeSymbol.isGeneric() && !constraintTypeSymbol.isTypeParameter() && constraintTypeSymbol.getTypeParameters().length && (constraintTypeSymbol.getTypeArguments() == null && !this.isArrayOrEquivalent(constraintTypeSymbol)) && constraintTypeSymbol.isResolved() && this.isTypeRefWithoutTypeArgs(typeParameterAST.constraint)) { + context.postError(this.unitPath, typeParameterAST.constraint.minChar, typeParameterAST.constraint.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + constraintTypeSymbol = this.specializeTypeToAny(constraintTypeSymbol, enclosingDecl, context); + } + + if (constraintTypeSymbol) { + typeParameterSymbol.setConstraint(constraintTypeSymbol); + } + } + + typeParameterSymbol.setResolved(); + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionBodyReturnTypes = function (funcDeclAST, signature, useContextualType, enclosingDecl, context) { + var _this = this; + var returnStatements = []; + + var enclosingDeclStack = [enclosingDecl]; + + var preFindReturnExpressionTypes = function (ast, parent, walker) { + var go = true; + + switch (ast.nodeType) { + case 12 /* FunctionDeclaration */: + go = false; + break; + + case 93 /* ReturnStatement */: + var returnStatement = ast; + returnStatements[returnStatements.length] = { returnStatement: returnStatement, enclosingDecl: enclosingDeclStack[enclosingDeclStack.length - 1] }; + go = false; + break; + + case 101 /* CatchClause */: + case 99 /* WithStatement */: + enclosingDeclStack[enclosingDeclStack.length] = _this.getDeclForAST(ast); + break; + + default: + break; + } + + walker.options.goChildren = go; + + return ast; + }; + + var postFindReturnExpressionEnclosingDecls = function (ast, parent, walker) { + switch (ast.nodeType) { + case 101 /* CatchClause */: + case 99 /* WithStatement */: + enclosingDeclStack.length--; + break; + default: + break; + } + + walker.options.goChildren = true; + + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(funcDeclAST.block, preFindReturnExpressionTypes, postFindReturnExpressionEnclosingDecls); + + if (!returnStatements.length) { + signature.setReturnType(this.semanticInfoChain.voidTypeSymbol); + } else { + var returnExpressionSymbols = []; + var returnType; + + for (var i = 0; i < returnStatements.length; i++) { + if (returnStatements[i].returnStatement.returnExpression) { + returnType = this.resolveAST(returnStatements[i].returnStatement.returnExpression, useContextualType, returnStatements[i].enclosingDecl, context).symbol.getType(); + + if (returnType.isError()) { + signature.setReturnType(returnType); + return; + } + + returnExpressionSymbols[returnExpressionSymbols.length] = returnType; + } + } + + if (!returnExpressionSymbols.length) { + signature.setReturnType(this.semanticInfoChain.voidTypeSymbol); + } else { + var collection = { + getLength: function () { + return returnExpressionSymbols.length; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return returnExpressionSymbols[index].getType(); + } + }; + + returnType = this.findBestCommonType(returnExpressionSymbols[0], null, collection, context, new TypeScript.TypeComparisonInfo()); + + if (useContextualType && returnType == this.semanticInfoChain.anyTypeSymbol) { + var contextualType = context.getContextualType(); + + if (contextualType) { + returnType = contextualType; + } + } + + signature.setReturnType(returnType ? this.widenType(returnType) : this.semanticInfoChain.anyTypeSymbol); + + if (this.isTypeArgumentOrWrapper(returnType)) { + var functionDecl = this.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + + if (functionSymbol) { + functionSymbol.getType().setHasGenericSignature(); + } + } + + for (var i = 0; i < returnExpressionSymbols.length; i++) { + returnExpressionSymbols[i].addOutgoingLink(signature, 2 /* ProvidesInferredType */); + } + } + } + }; + + PullTypeResolver.prototype.resolveFunctionDeclaration = function (funcDeclAST, context) { + var funcDecl = this.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSpecializingSignatureSymbol(); + + var hadError = false; + + var isConstructor = funcDeclAST.isConstructor || TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 1024 /* ConstructMember */); + + if (signature) { + if (signature.isResolved()) { + return funcSymbol; + } + + if (isConstructor && !signature.isResolving()) { + var classAST = funcDeclAST.classDecl; + + if (classAST) { + var classDecl = this.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved() && !classSymbol.isResolving()) { + this.resolveDeclaredSymbol(classSymbol, this.getEnclosingDecl(classDecl), context); + } + } + } + + var diagnostic; + + if (signature.isResolving()) { + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, funcDecl, context).symbol; + if (!returnTypeSymbol) { + diagnostic = context.postError(this.unitPath, funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), 197 /* Cannot_resolve_return_type_reference */, null, funcDecl); + signature.setReturnType(this.getNewErrorTypeSymbol(diagnostic)); + hadError = true; + } else { + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + if (funcSymbol) { + funcSymbol.getType().setHasGenericSignature(); + } + } + signature.setReturnType(returnTypeSymbol); + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 198 /* Constructors_cannot_have_a_return_type_of__void_ */, null, funcDecl, true); + } + } + } else { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } + + signature.setResolved(); + return funcSymbol; + } + + signature.startResolving(); + + if (funcDeclAST.typeArguments) { + for (var i = 0; i < funcDeclAST.typeArguments.members.length; i++) { + this.resolveTypeParameterDeclaration(funcDeclAST.typeArguments.members[i], context); + } + } + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveVariableDeclaration(funcDeclAST.arguments.members[i], context, funcDecl); + } + } + + if (signature.isGeneric()) { + if (funcSymbol) { + funcSymbol.getType().setHasGenericSignature(); + } + } + + if (funcDeclAST.returnTypeAnnotation) { + var prevReturnTypeSymbol = signature.getReturnType(); + + returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, funcDecl, context).symbol; + + if (!returnTypeSymbol) { + diagnostic = context.postError(this.unitPath, funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), 197 /* Cannot_resolve_return_type_reference */, null, funcDecl); + signature.setReturnType(this.getNewErrorTypeSymbol(diagnostic)); + + hadError = true; + } else if (!(this.isTypeArgumentOrWrapper(returnTypeSymbol) && prevReturnTypeSymbol && !this.isTypeArgumentOrWrapper(prevReturnTypeSymbol))) { + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + + if (funcSymbol) { + funcSymbol.getType().setHasGenericSignature(); + } + } + + signature.setReturnType(returnTypeSymbol); + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 198 /* Constructors_cannot_have_a_return_type_of__void_ */, null, funcDecl, true); + } + } + } else if (!funcDeclAST.isConstructor) { + if (funcDeclAST.isSignature()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, false, funcDecl, context); + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveGetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var getterSymbol = accessorSymbol.getGetter(); + var getterTypeSymbol = getterSymbol.getType(); + + var signature = getterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + var diagnostic; + + if (signature) { + if (signature.isResolved()) { + return accessorSymbol; + } + + if (signature.isResolving()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + signature.setResolved(); + + return accessorSymbol; + } + + signature.startResolving(); + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveVariableDeclaration(funcDeclAST.arguments.members[i], context, funcDecl); + } + } + + if (signature.hasGenericParameter()) { + if (getterSymbol) { + getterTypeSymbol.setHasGenericSignature(); + } + } + + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, funcDecl, context).symbol; + + if (!returnTypeSymbol) { + diagnostic = context.postError(this.unitPath, funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), 197 /* Cannot_resolve_return_type_reference */, null, funcDecl); + signature.setReturnType(this.getNewErrorTypeSymbol(diagnostic)); + + hadError = true; + } else { + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + + if (getterSymbol) { + getterTypeSymbol.setHasGenericSignature(); + } + } + + signature.setReturnType(returnTypeSymbol); + } + } else { + if (funcDeclAST.isSignature()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, false, funcDecl, context); + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + var accessorType = signature.getReturnType(); + + var setter = accessorSymbol.getSetter(); + + if (setter) { + var setterType = setter.getType(); + var setterSig = setterType.getCallSignatures()[0]; + + if (setterSig.isResolved()) { + var setterParameters = setterSig.getParameters(); + + if (setterParameters.length) { + var setterParameter = setterParameters[0]; + var setterParameterType = setterParameter.getType(); + + if (!this.typesAreIdentical(accessorType, setterParameterType)) { + diagnostic = context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 165 /* _get__and__set__accessor_must_have_the_same_type */, null, this.getEnclosingDecl(funcDecl)); + accessorSymbol.setType(this.getNewErrorTypeSymbol(diagnostic)); + } + } + } else { + accessorSymbol.setType(accessorType); + } + } else { + accessorSymbol.setType(accessorType); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var setterSymbol = accessorSymbol.getSetter(); + var setterTypeSymbol = setterSymbol.getType(); + + var signature = setterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + + if (signature) { + if (signature.isResolved()) { + return accessorSymbol; + } + + if (signature.isResolving()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + signature.setResolved(); + + return accessorSymbol; + } + + signature.startResolving(); + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveVariableDeclaration(funcDeclAST.arguments.members[i], context, funcDecl); + } + } + + if (signature.hasGenericParameter()) { + if (setterSymbol) { + setterTypeSymbol.setHasGenericSignature(); + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + var parameters = signature.getParameters(); + + var getter = accessorSymbol.getGetter(); + + var accessorType = parameters.length ? parameters[0].getType() : getter ? getter.getType() : this.semanticInfoChain.undefinedTypeSymbol; + + if (getter) { + var getterType = getter.getType(); + var getterSig = getterType.getCallSignatures()[0]; + + if (accessorType == this.semanticInfoChain.undefinedTypeSymbol) { + accessorType = getterType; + } + + if (getterSig.isResolved()) { + var getterReturnType = getterSig.getReturnType(); + + if (!this.typesAreIdentical(accessorType, getterReturnType)) { + if (this.isAnyOrEquivalent(accessorType)) { + accessorSymbol.setType(getterReturnType); + if (!accessorType.isError()) { + parameters[0].setType(getterReturnType); + } + } else { + var diagnostic = context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 165 /* _get__and__set__accessor_must_have_the_same_type */, null, this.getEnclosingDecl(funcDecl)); + accessorSymbol.setType(this.getNewErrorTypeSymbol(diagnostic)); + } + } + } else { + accessorSymbol.setType(accessorType); + } + } else { + accessorSymbol.setType(accessorType); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.resolveAST = function (ast, inContextuallyTypedAssignment, enclosingDecl, context) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + switch (ast.nodeType) { + case 101 /* CatchClause */: + case 99 /* WithStatement */: + case 2 /* Script */: + return SymbolAndDiagnostics.fromSymbol(null); + + case 15 /* ModuleDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveModuleDeclaration(ast, context)); + + case 14 /* InterfaceDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveInterfaceDeclaration(ast, context)); + + case 13 /* ClassDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveClassDeclaration(ast, context)); + + case 17 /* VariableDeclarator */: + case 19 /* Parameter */: + return SymbolAndDiagnostics.fromSymbol(this.resolveVariableDeclaration(ast, context, enclosingDecl)); + + case 9 /* TypeParameter */: + return SymbolAndDiagnostics.fromSymbol(this.resolveTypeParameterDeclaration(ast, context)); + + case 16 /* ImportDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveImportDeclaration(ast, context)); + + case 22 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 10 /* GenericType */: + return this.resolveGenericTypeReference(ast, enclosingDecl, context); + + case 20 /* Name */: + if (context.resolvingTypeReference) { + return this.resolveTypeNameExpression(ast, enclosingDecl, context); + } else { + return this.resolveNameExpression(ast, enclosingDecl, context); + } + + case 32 /* MemberAccessExpression */: + if (context.resolvingTypeReference) { + return this.resolveDottedTypeNameExpression(ast, enclosingDecl, context); + } else { + return this.resolveDottedNameExpression(ast, enclosingDecl, context); + } + + case 10 /* GenericType */: + return this.resolveGenericTypeReference(ast, enclosingDecl, context); + + case 12 /* FunctionDeclaration */: { + var funcDecl = ast; + + if (funcDecl.isGetAccessor()) { + return SymbolAndDiagnostics.fromSymbol(this.resolveGetAccessorDeclaration(funcDecl, context)); + } else if (funcDecl.isSetAccessor()) { + return SymbolAndDiagnostics.fromSymbol(this.resolveSetAccessorDeclaration(funcDecl, context)); + } else if (inContextuallyTypedAssignment || (funcDecl.getFunctionFlags() & 8192 /* IsFunctionExpression */) || (funcDecl.getFunctionFlags() & 2048 /* IsFatArrowFunction */) || (funcDecl.getFunctionFlags() & 16384 /* IsFunctionProperty */)) { + return SymbolAndDiagnostics.fromSymbol(this.resolveFunctionExpression(funcDecl, inContextuallyTypedAssignment, enclosingDecl, context)); + } else { + return SymbolAndDiagnostics.fromSymbol(this.resolveFunctionDeclaration(funcDecl, context)); + } + } + + case 21 /* ArrayLiteralExpression */: + return this.resolveArrayLiteralExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 29 /* ThisExpression */: + return this.resolveThisExpression(ast, enclosingDecl, context); + + case 30 /* SuperExpression */: + return this.resolveSuperExpression(ast, enclosingDecl, context); + + case 36 /* InvocationExpression */: + return this.resolveCallExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 37 /* ObjectCreationExpression */: + return this.resolveNewExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 78 /* CastExpression */: + return this.resolveTypeAssertionExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 11 /* TypeRef */: + return this.resolveTypeReference(ast, enclosingDecl, context); + + case 87 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, enclosingDecl, context); + + case 7 /* NumericLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + case 5 /* StringLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + case 8 /* NullLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.nullTypeSymbol); + case 3 /* TrueLiteral */: + case 4 /* FalseLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + case 24 /* VoidExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + + case 38 /* AssignmentExpression */: + return this.resolveAssignmentStatement(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 73 /* LogicalNotExpression */: + case 57 /* NotEqualsWithTypeConversionExpression */: + case 56 /* EqualsWithTypeConversionExpression */: + case 58 /* EqualsExpression */: + case 59 /* NotEqualsExpression */: + case 60 /* LessThanExpression */: + case 61 /* LessThanOrEqualExpression */: + case 63 /* GreaterThanOrEqualExpression */: + case 62 /* GreaterThanExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + + case 64 /* AddExpression */: + case 39 /* AddAssignmentExpression */: + return this.resolveArithmeticExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 40 /* SubtractAssignmentExpression */: + case 42 /* MultiplyAssignmentExpression */: + case 41 /* DivideAssignmentExpression */: + case 43 /* ModuloAssignmentExpression */: + case 46 /* OrAssignmentExpression */: + case 44 /* AndAssignmentExpression */: + + case 72 /* BitwiseNotExpression */: + case 65 /* SubtractExpression */: + case 66 /* MultiplyExpression */: + case 67 /* DivideExpression */: + case 68 /* ModuloExpression */: + case 53 /* BitwiseOrExpression */: + case 55 /* BitwiseAndExpression */: + case 26 /* PlusExpression */: + case 27 /* NegateExpression */: + case 76 /* PostIncrementExpression */: + case 74 /* PreIncrementExpression */: + case 77 /* PostDecrementExpression */: + case 75 /* PreDecrementExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + + case 69 /* LeftShiftExpression */: + case 70 /* SignedRightShiftExpression */: + case 71 /* UnsignedRightShiftExpression */: + case 47 /* LeftShiftAssignmentExpression */: + case 48 /* SignedRightShiftAssignmentExpression */: + case 49 /* UnsignedRightShiftAssignmentExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + + case 35 /* ElementAccessExpression */: + return this.resolveIndexExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 51 /* LogicalOrExpression */: + return this.resolveLogicalOrExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 52 /* LogicalAndExpression */: + return this.resolveLogicalAndExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 34 /* TypeOfExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + + case 95 /* ThrowStatement */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + + case 28 /* DeleteExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + + case 50 /* ConditionalExpression */: + return this.resolveConditionalExpression(ast, enclosingDecl, context); + + case 6 /* RegularExpressionLiteral */: + return this.resolveRegularExpressionLiteral(); + + case 79 /* ParenthesizedExpression */: + return this.resolveParenthesizedExpression(ast, enclosingDecl, context); + + case 88 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 33 /* InstanceOfExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveRegularExpressionLiteral = function () { + if (this.cachedRegExpInterfaceType()) { + return SymbolAndDiagnostics.fromSymbol(this.cachedRegExpInterfaceType()); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + }; + + PullTypeResolver.prototype.isNameOrMemberAccessExpression = function (ast) { + var checkAST = ast; + + while (checkAST) { + if (checkAST.nodeType === 88 /* ExpressionStatement */) { + checkAST = (checkAST).expression; + } else if (checkAST.nodeType === 79 /* ParenthesizedExpression */) { + checkAST = (checkAST).expression; + } else if (checkAST.nodeType === 20 /* Name */) { + return true; + } else if (checkAST.nodeType === 32 /* MemberAccessExpression */) { + return true; + } else { + return false; + } + } + }; + + PullTypeResolver.prototype.resolveNameSymbol = function (nameSymbol, context) { + if (nameSymbol && !context.canUseTypeSymbol && nameSymbol != this.semanticInfoChain.undefinedTypeSymbol && nameSymbol != this.semanticInfoChain.nullTypeSymbol && (nameSymbol.isPrimitive() || !(nameSymbol.getKind() & TypeScript.PullElementKind.SomeValue))) { + nameSymbol = null; + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.resolveNameExpression = function (nameAST, enclosingDecl, context) { + var nameSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(nameAST); + var foundCached = nameSymbolAndDiagnostics != null; + + if (!foundCached) { + nameSymbolAndDiagnostics = this.computeNameExpression(nameAST, enclosingDecl, context); + } + + var nameSymbol = nameSymbolAndDiagnostics.symbol; + if (!nameSymbol.isResolved()) { + this.resolveDeclaredSymbol(nameSymbol, enclosingDecl, context); + } + + if (!foundCached && !this.isAnyOrEquivalent(nameSymbol.getType())) { + this.setSymbolAndDiagnosticsForAST(nameAST, nameSymbolAndDiagnostics, context); + } + + return nameSymbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, enclosingDecl, context) { + if (nameAST.isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var id = nameAST.text; + + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + + if (enclosingDecl && !declPath.length) { + declPath = [enclosingDecl]; + } + + var aliasSymbol = null; + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeValue); + + if (!nameSymbol && id === "arguments" && enclosingDecl && (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction)) { + nameSymbol = this.cachedFunctionArgumentsSymbol; + + if (this.cachedIArgumentsInterfaceType() && !this.cachedIArgumentsInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), enclosingDecl, context); + } + } + + if (!nameSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, id), [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 164 /* Could_not_find_symbol__0_ */, [nameAST.actualText])]); + } + + if (nameSymbol.isType() && nameSymbol.isAlias()) { + aliasSymbol = nameSymbol; + + (aliasSymbol).setIsUsedAsValue(); + + if (!nameSymbol.isResolved()) { + this.resolveDeclaredSymbol(nameSymbol, enclosingDecl, context); + } + + var exportAssignmentSymbol = (nameSymbol).getExportAssignedValueSymbol(); + + if (exportAssignmentSymbol) { + nameSymbol = exportAssignmentSymbol; + } else { + aliasSymbol = null; + } + } + + return SymbolAndDiagnostics.fromAlias(nameSymbol, aliasSymbol); + }; + + PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(dottedNameAST); + var foundCached = symbolAndDiagnostics != null; + + if (!foundCached) { + symbolAndDiagnostics = this.computeDottedNameExpressionSymbol(dottedNameAST, enclosingDecl, context); + } + + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + if (symbol && !symbol.isResolved()) { + this.resolveDeclaredSymbol(symbol, enclosingDecl, context); + } + + if (!foundCached && !this.isAnyOrEquivalent(symbol.getType())) { + this.setSymbolAndDiagnosticsForAST(dottedNameAST, symbolAndDiagnostics, context); + this.setSymbolAndDiagnosticsForAST(dottedNameAST.operand2, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.isPrototypeMember = function (dottedNameAST, enclosingDecl, context) { + var rhsName = (dottedNameAST.operand2).text; + if (rhsName === "prototype") { + var prevCanUseTypeSymbol = context.canUseTypeSymbol; + context.canUseTypeSymbol = true; + var lhsType = this.resolveAST(dottedNameAST.operand1, false, enclosingDecl, context).symbol.getType(); + context.canUseTypeSymbol = prevCanUseTypeSymbol; + + if (lhsType) { + if (lhsType.isClass() || lhsType.isConstructor()) { + return true; + } else { + var classInstanceType = lhsType.getAssociatedContainerType(); + + if (classInstanceType && classInstanceType.isClass()) { + return true; + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.computeDottedNameExpressionSymbol = function (dottedNameAST, enclosingDecl, context) { + if ((dottedNameAST.operand2).isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var rhsName = (dottedNameAST.operand2).text; + var prevCanUseTypeSymbol = context.canUseTypeSymbol; + context.canUseTypeSymbol = true; + var lhs = this.resolveAST(dottedNameAST.operand1, false, enclosingDecl, context).symbol; + context.canUseTypeSymbol = prevCanUseTypeSymbol; + var lhsType = lhs.getType(); + + if (lhs.isAlias()) { + (lhs).setIsUsedAsValue(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return SymbolAndDiagnostics.fromSymbol(lhsType); + } + + if (!lhsType) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 162 /* Could_not_find_enclosing_symbol_for_dotted_name__0_ */, [(dottedNameAST.operand2).actualText])]); + } + + if ((lhsType === this.semanticInfoChain.numberTypeSymbol || (lhs.getKind() == 67108864 /* EnumMember */)) && this.cachedNumberInterfaceType()) { + lhsType = this.cachedNumberInterfaceType(); + } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { + lhsType = this.cachedStringInterfaceType(); + } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { + lhsType = this.cachedBooleanInterfaceType(); + } + + if (!lhsType.isResolved()) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, enclosingDecl, context); + + if (potentiallySpecializedType != lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + if (lhsType.isContainer() && !lhsType.isAlias()) { + var instanceSymbol = (lhsType).getInstanceSymbol(); + + if (instanceSymbol) { + lhsType = instanceSymbol.getType(); + } + } + + if (this.isPrototypeMember(dottedNameAST, enclosingDecl, context)) { + if (lhsType.isClass()) { + return SymbolAndDiagnostics.fromSymbol(lhsType); + } else { + var classInstanceType = lhsType.getAssociatedContainerType(); + + if (classInstanceType && classInstanceType.isClass()) { + return SymbolAndDiagnostics.fromSymbol(classInstanceType); + } + } + } + + if (lhsType.isTypeParameter()) { + lhsType = this.substituteUpperBoundForType(lhsType); + } + + var nameSymbol = null; + if (!(lhs.isType() && (lhs).isClass() && this.isNameOrMemberAccessExpression(dottedNameAST.operand1)) && !nameSymbol) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, lhsType); + nameSymbol = this.resolveNameSymbol(nameSymbol, context); + } + + if (!nameSymbol) { + if (lhsType.isClass()) { + var staticType = (lhsType).getConstructorMethod().getType(); + + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, staticType); + + if (!nameSymbol) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, lhsType); + } + } else if ((lhsType.getCallSignatures().length || lhsType.getConstructSignatures().length) && this.cachedFunctionInterfaceType()) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, this.cachedFunctionInterfaceType()); + } else if (lhsType.isContainer()) { + var containerType = (lhsType.isAlias() ? (lhsType).getType() : lhsType); + var associatedInstance = containerType.getInstanceSymbol(); + + if (associatedInstance) { + var instanceType = associatedInstance.getType(); + + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, instanceType); + } + } else { + var associatedType = lhsType.getAssociatedContainerType(); + + if (associatedType && !associatedType.isClass()) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, associatedType); + } + } + + nameSymbol = this.resolveNameSymbol(nameSymbol, context); + + if (!nameSymbol && !lhsType.isPrimitive() && this.cachedObjectInterfaceType()) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, this.cachedObjectInterfaceType()); + } + + if (!nameSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, rhsName), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 163 /* The_property__0__does_not_exist_on_value_of_type__1__ */, [(dottedNameAST.operand2).actualText, lhsType.getDisplayName()])]); + } + } + + return SymbolAndDiagnostics.fromSymbol(nameSymbol); + }; + + PullTypeResolver.prototype.resolveTypeNameExpression = function (nameAST, enclosingDecl, context) { + var typeNameSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(nameAST); + + if (!typeNameSymbolAndDiagnostics || !typeNameSymbolAndDiagnostics.symbol.isType()) { + typeNameSymbolAndDiagnostics = this.computeTypeNameExpression(nameAST, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(nameAST, typeNameSymbolAndDiagnostics, context); + } + + var typeNameSymbol = typeNameSymbolAndDiagnostics && typeNameSymbolAndDiagnostics.symbol; + if (!typeNameSymbol.isResolved()) { + var savedResolvingNamespaceMemberAccess = context.resolvingNamespaceMemberAccess; + context.resolvingNamespaceMemberAccess = false; + this.resolveDeclaredSymbol(typeNameSymbol, enclosingDecl, context); + context.resolvingNamespaceMemberAccess = savedResolvingNamespaceMemberAccess; + } + + if (typeNameSymbol && !(typeNameSymbol.isTypeParameter() && (typeNameSymbol).isFunctionTypeParameter() && context.isSpecializingSignatureAtCallSite && !context.isSpecializingConstructorMethod)) { + var substitution = context.findSpecializationForType(typeNameSymbol); + + if (typeNameSymbol.isTypeParameter() && (substitution != typeNameSymbol)) { + if (TypeScript.shouldSpecializeTypeParameterForTypeParameter(substitution, typeNameSymbol)) { + typeNameSymbol = substitution; + } + } + + if (typeNameSymbol != typeNameSymbolAndDiagnostics.symbol) { + return SymbolAndDiagnostics.fromSymbol(typeNameSymbol); + } + } + + return typeNameSymbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeTypeNameExpression = function (nameAST, enclosingDecl, context) { + if (nameAST.isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var id = nameAST.text; + + if (id === "any") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } else if (id === "string") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + } else if (id === "number") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (id === "bool") { + if (this.compilationSettings.disallowBool && !this.currentUnit.getProperties().unitContainsBool) { + this.currentUnit.getProperties().unitContainsBool = true; + return SymbolAndDiagnostics.create(this.semanticInfoChain.booleanTypeSymbol, [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 167 /* Use_of_deprecated__bool__type__Use__boolean__instead */)]); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } + } else if (id === "boolean") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } else if (id === "void") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + } else { + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + + if (enclosingDecl && !declPath.length) { + declPath = [enclosingDecl]; + } + + var kindToCheckFirst = context.resolvingNamespaceMemberAccess ? TypeScript.PullElementKind.SomeContainer : TypeScript.PullElementKind.SomeType; + var kindToCheckSecond = context.resolvingNamespaceMemberAccess ? TypeScript.PullElementKind.SomeType : TypeScript.PullElementKind.SomeContainer; + + var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); + + if (!typeNameSymbol) { + typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckSecond); + } + + if (!typeNameSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, id), [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 164 /* Could_not_find_symbol__0_ */, [nameAST.actualText])]); + } + + if (typeNameSymbol.isAlias()) { + if (!typeNameSymbol.isResolved()) { + var savedResolvingNamespaceMemberAccess = context.resolvingNamespaceMemberAccess; + context.resolvingNamespaceMemberAccess = false; + this.resolveDeclaredSymbol(typeNameSymbol, enclosingDecl, context); + context.resolvingNamespaceMemberAccess = savedResolvingNamespaceMemberAccess; + } + + var aliasedType = (typeNameSymbol).getType(); + + if (aliasedType && !aliasedType.isResolved()) { + this.resolveDeclaredSymbol(aliasedType, enclosingDecl, context); + } + + var exportAssignmentSymbol = (typeNameSymbol).getExportAssignedTypeSymbol(); + + if (exportAssignmentSymbol) { + typeNameSymbol = exportAssignmentSymbol; + } + } + + if (typeNameSymbol.isTypeParameter()) { + if (enclosingDecl && (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction) && (enclosingDecl.getFlags() & 16 /* Static */)) { + var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); + + if (parentDecl.getKind() == 8 /* Class */) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 226 /* Static_methods_cannot_reference_class_type_parameters */)]); + } + } + } + } + + return SymbolAndDiagnostics.fromSymbol(typeNameSymbol); + }; + + PullTypeResolver.prototype.addDiagnostic = function (diagnostics, diagnostic) { + if (!diagnostics) { + diagnostics = []; + } + + diagnostics.push(diagnostic); + return diagnostics; + }; + + PullTypeResolver.prototype.resolveGenericTypeReference = function (genericTypeAST, enclosingDecl, context) { + var savedResolvingTypeReference = context.resolvingTypeReference; + context.resolvingTypeReference = true; + var genericTypeSymbol = this.resolveAST(genericTypeAST.name, false, enclosingDecl, context).symbol.getType(); + context.resolvingTypeReference = savedResolvingTypeReference; + + if (genericTypeSymbol.isError()) { + return SymbolAndDiagnostics.fromSymbol(genericTypeSymbol); + } + + if (!genericTypeSymbol.isResolving() && !genericTypeSymbol.isResolved()) { + this.resolveDeclaredSymbol(genericTypeSymbol, enclosingDecl, context); + } + + var typeArgs = []; + + if (!context.isResolvingTypeArguments(genericTypeAST)) { + context.startResolvingTypeArguments(genericTypeAST); + + if (genericTypeAST.typeArguments && genericTypeAST.typeArguments.members.length) { + for (var i = 0; i < genericTypeAST.typeArguments.members.length; i++) { + var typeArg = this.resolveTypeReference(genericTypeAST.typeArguments.members[i], enclosingDecl, context).symbol; + + if (typeArg.isNamedTypeSymbol() && typeArg.isGeneric() && !typeArg.isTypeParameter() && typeArg.isResolved() && !typeArg.getIsSpecialized() && typeArg.getTypeParameters().length && (typeArg.getTypeArguments() == null && !this.isArrayOrEquivalent(typeArg)) && this.isTypeRefWithoutTypeArgs(genericTypeAST.typeArguments.members[i])) { + context.postError(this.unitPath, genericTypeAST.typeArguments.members[i].minChar, genericTypeAST.typeArguments.members[i].getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + typeArg = this.specializeTypeToAny(typeArg, enclosingDecl, context); + } + + typeArgs[i] = context.findSpecializationForType(typeArg); + } + } + + context.doneResolvingTypeArguments(); + } + + var typeParameters = genericTypeSymbol.getTypeParameters(); + + if (typeArgs.length && typeArgs.length != typeParameters.length) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, genericTypeAST.minChar, genericTypeAST.getLength(), 159 /* Generic_type__0__requires_1_type_argument_s_ */, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])]); + } + + var specializedSymbol = TypeScript.specializeType(genericTypeSymbol, typeArgs, this, enclosingDecl, context, genericTypeAST); + + var typeConstraint = null; + var upperBound = null; + var diagnostics = null; + + for (var iArg = 0; (iArg < typeArgs.length) && (iArg < typeParameters.length); iArg++) { + typeArg = typeArgs[iArg]; + typeConstraint = typeParameters[iArg].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { + if (typeParameters[j] == typeConstraint) { + typeConstraint = typeArgs[j]; + } + } + } + + if (typeArg.isTypeParameter()) { + upperBound = (typeArg).getConstraint(); + + if (upperBound) { + typeArg = upperBound; + } + } + + if (typeArg.isResolving()) { + return SymbolAndDiagnostics.fromSymbol(specializedSymbol); + } + if (!this.sourceIsAssignableToTarget(typeArg, typeConstraint, context)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, genericTypeAST.minChar, genericTypeAST.getLength(), 155 /* Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_ */, [typeArg.toString(true), typeConstraint.toString(true), typeParameters[iArg].toString(true)])); + } + } + } + + return SymbolAndDiagnostics.create(specializedSymbol, diagnostics); + }; + + PullTypeResolver.prototype.resolveDottedTypeNameExpression = function (dottedNameAST, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(dottedNameAST); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeDottedTypeNameExpression(dottedNameAST, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(dottedNameAST, symbolAndDiagnostics, context); + } + + var symbol = symbolAndDiagnostics.symbol; + if (!symbol.isResolved()) { + this.resolveDeclaredSymbol(symbol, enclosingDecl, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeDottedTypeNameExpression = function (dottedNameAST, enclosingDecl, context) { + if ((dottedNameAST.operand2).isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var rhsName = (dottedNameAST.operand2).text; + + var savedResolvingTypeReference = context.resolvingTypeReference; + var savedResolvingNamespaceMemberAccess = context.resolvingNamespaceMemberAccess; + context.resolvingNamespaceMemberAccess = true; + context.resolvingTypeReference = true; + var lhs = this.resolveAST(dottedNameAST.operand1, false, enclosingDecl, context).symbol; + context.resolvingTypeReference = savedResolvingTypeReference; + context.resolvingNamespaceMemberAccess = savedResolvingNamespaceMemberAccess; + + var lhsType = lhs.getType(); + + if (context.isResolvingClassExtendedType) { + if (lhs.isAlias()) { + (lhs).setIsUsedAsValue(); + } + } + + if (this.isAnyOrEquivalent(lhsType)) { + return SymbolAndDiagnostics.fromSymbol(lhsType); + } + + if (!lhsType) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 162 /* Could_not_find_enclosing_symbol_for_dotted_name__0_ */, [(dottedNameAST.operand2).actualText])]); + } + + var childTypeSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeType, lhsType); + + if (!childTypeSymbol && lhsType.isContainer()) { + var exportedContainer = (lhsType).getExportAssignedContainerSymbol(); + + if (exportedContainer) { + childTypeSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeType, exportedContainer); + } + } + + if (!childTypeSymbol && enclosingDecl) { + var parentDecl = enclosingDecl; + + while (parentDecl) { + if (parentDecl.getKind() & TypeScript.PullElementKind.SomeContainer) { + break; + } + + parentDecl = parentDecl.getParentDecl(); + } + + if (parentDecl) { + var enclosingSymbolType = parentDecl.getSymbol().getType(); + + if (enclosingSymbolType === lhsType) { + childTypeSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeType, lhsType); + } + } + } + + if (!childTypeSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, rhsName), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 163 /* The_property__0__does_not_exist_on_value_of_type__1__ */, [(dottedNameAST.operand2).actualText, lhsType.getName()])]); + } + + return SymbolAndDiagnostics.fromSymbol(childTypeSymbol); + }; + + PullTypeResolver.prototype.resolveFunctionExpression = function (funcDeclAST, inContextuallyTypedAssignment, enclosingDecl, context) { + var funcDeclSymbol = null; + var functionDecl = this.getDeclForAST(funcDeclAST); + + if (functionDecl && functionDecl.hasSymbol()) { + funcDeclSymbol = functionDecl.getSymbol(); + if (funcDeclSymbol.isResolved()) { + return funcDeclSymbol; + } + } + + var shouldContextuallyType = inContextuallyTypedAssignment; + + var assigningFunctionTypeSymbol = null; + var assigningFunctionSignature = null; + + if (funcDeclAST.returnTypeAnnotation) { + shouldContextuallyType = false; + } + + if (shouldContextuallyType && funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + if ((funcDeclAST.arguments.members[i]).typeExpr) { + shouldContextuallyType = false; + break; + } + } + } + + if (shouldContextuallyType) { + assigningFunctionTypeSymbol = context.getContextualType(); + + if (assigningFunctionTypeSymbol) { + this.resolveDeclaredSymbol(assigningFunctionTypeSymbol, enclosingDecl, context); + + if (assigningFunctionTypeSymbol) { + assigningFunctionSignature = assigningFunctionTypeSymbol.getCallSignatures()[0]; + } + } + } + + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + if (enclosingDecl) { + declCollectionContext.pushParent(enclosingDecl); + } + + TypeScript.getAstWalkerFactory().walk(funcDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var functionDecl = this.getDeclForAST(funcDeclAST); + this.currentUnit.addSynthesizedDecl(functionDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + binder.setUnit(this.unitPath); + binder.bindFunctionExpressionToPullSymbol(functionDecl); + + funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.getType().getCallSignatures()[0]; + + if (funcDeclAST.arguments) { + var contextParams = []; + var contextParam = null; + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.getParameters(); + } + + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + if ((i < contextParams.length) && !contextParams[i].getIsVarArg()) { + contextParam = contextParams[i]; + } else if (contextParams.length && contextParams[contextParams.length - 1].getIsVarArg()) { + contextParam = (contextParams[contextParams.length - 1].getType()).getElementType(); + } + + this.resolveFunctionExpressionParameter(funcDeclAST.arguments.members[i], contextParam, functionDecl, context); + } + } + + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, functionDecl, context).symbol; + + signature.setReturnType(returnTypeSymbol); + } else { + if (assigningFunctionSignature) { + var returnType = assigningFunctionSignature.getReturnType(); + + if (returnType) { + context.pushContextualType(returnType, context.inProvisionalResolution(), null); + + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, true, functionDecl, context); + context.popContextualType(); + } else { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, false, functionDecl, context); + } + } + + if (assigningFunctionTypeSymbol) { + funcDeclSymbol.addOutgoingLink(assigningFunctionTypeSymbol, 1 /* ContextuallyTypedAs */); + } + + funcDeclSymbol.setResolved(); + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveThisExpression = function (ast, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(ast); + + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeThisExpressionSymbol(ast, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(ast, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeThisExpressionSymbol = function (ast, enclosingDecl, context) { + if (enclosingDecl) { + var enclosingDeclKind = enclosingDecl.getKind(); + var diagnostics; + + if (enclosingDeclKind === 4 /* Container */) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.currentUnit.getPath(), ast.minChar, ast.getLength(), 176 /* _this__cannot_be_referenced_within_module_bodies */)]); + } else if (!(enclosingDeclKind & (TypeScript.PullElementKind.SomeFunction | 1 /* Script */ | TypeScript.PullElementKind.SomeBlock))) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.currentUnit.getPath(), ast.minChar, ast.getLength(), 177 /* _this__must_only_be_used_inside_a_function_or_script_context */)]); + } else { + var declPath = TypeScript.getPathToDecl(enclosingDecl); + + if (declPath.length) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.getKind(); + var declFlags = decl.getFlags(); + + if (declFlags & 16 /* Static */) { + break; + } else if (declKind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(declFlags, 8192 /* FatArrow */)) { + break; + } else if (declKind === 16384 /* Function */) { + break; + } else if (declKind === 8 /* Class */) { + var classSymbol = decl.getSymbol(); + return SymbolAndDiagnostics.fromSymbol(classSymbol); + } + } + } + } + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveSuperExpression = function (ast, enclosingDecl, context) { + if (!enclosingDecl) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + var classSymbol = null; + + if (declPath.length) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declFlags = decl.getFlags(); + + if (decl.getKind() === 131072 /* FunctionExpression */ && !(declFlags & 8192 /* FatArrow */)) { + break; + } else if (declFlags & 16 /* Static */) { + break; + } else if (decl.getKind() === 8 /* Class */) { + classSymbol = decl.getSymbol(); + + break; + } + } + } + + if (classSymbol) { + if (!classSymbol.isResolved()) { + this.resolveDeclaredSymbol(classSymbol, enclosingDecl, context); + } + + var parents = classSymbol.getExtendedTypes(); + + if (parents.length) { + return SymbolAndDiagnostics.fromSymbol(parents[0]); + } + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(expressionAST); + + if (!symbolAndDiagnostics || additionalResults) { + symbolAndDiagnostics = this.computeObjectLiteralExpression(expressionAST, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults); + this.setSymbolAndDiagnosticsForAST(expressionAST, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeObjectLiteralExpression = function (expressionAST, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var objectLitAST = expressionAST; + var span = TypeScript.TextSpan.fromBounds(objectLitAST.minChar, objectLitAST.limChar); + + var objectLitDecl = new TypeScript.PullDecl("", "", 512 /* ObjectLiteral */, 0 /* None */, span, this.unitPath); + this.currentUnit.addSynthesizedDecl(objectLitDecl); + + if (enclosingDecl) { + objectLitDecl.setParentDecl(enclosingDecl); + } + + this.currentUnit.setDeclForAST(objectLitAST, objectLitDecl); + this.currentUnit.setASTForDecl(objectLitDecl, objectLitAST); + + var typeSymbol = new TypeScript.PullTypeSymbol("", 16 /* Interface */); + typeSymbol.addDeclaration(objectLitDecl); + objectLitDecl.setSymbol(typeSymbol); + + var memberDecls = objectLitAST.operand; + + var contextualType = null; + + if (inContextuallyTypedAssignment) { + contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, enclosingDecl, context); + } + + if (memberDecls) { + var binex; + var memberSymbol; + var assigningSymbol = null; + var acceptedContextualType = false; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols = []; + } + + for (var i = 0, len = memberDecls.members.length; i < len; i++) { + binex = memberDecls.members[i]; + + var id = binex.operand1; + var text; + var actualText; + + if (id.nodeType === 20 /* Name */) { + actualText = (id).actualText; + text = (id).text; + } else if (id.nodeType === 5 /* StringLiteral */) { + actualText = (id).actualText; + text = (id).text; + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + span = TypeScript.TextSpan.fromBounds(binex.minChar, binex.limChar); + + var decl = new TypeScript.PullDecl(text, actualText, 4096 /* Property */, 4 /* Public */, span, this.unitPath); + this.currentUnit.addSynthesizedDecl(decl); + + objectLitDecl.addChildDecl(decl); + decl.setParentDecl(objectLitDecl); + + this.semanticInfoChain.getUnit(this.unitPath).setDeclForAST(binex, decl); + this.semanticInfoChain.getUnit(this.unitPath).setASTForDecl(decl, binex); + + memberSymbol = new TypeScript.PullSymbol(text, 4096 /* Property */); + + memberSymbol.addDeclaration(decl); + decl.setSymbol(memberSymbol); + + if (contextualType) { + assigningSymbol = this.getMemberSymbol(text, TypeScript.PullElementKind.SomeValue, contextualType); + + if (assigningSymbol) { + this.resolveDeclaredSymbol(assigningSymbol, enclosingDecl, context); + + context.pushContextualType(assigningSymbol.getType(), context.inProvisionalResolution(), null); + + acceptedContextualType = true; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols[i] = assigningSymbol.getType(); + } + } + } + + if (binex.operand2.nodeType === 12 /* FunctionDeclaration */) { + var funcDeclAST = binex.operand2; + + if (funcDeclAST.isAccessor()) { + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + declCollectionContext.pushParent(objectLitDecl); + + TypeScript.getAstWalkerFactory().walk(funcDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var functionDecl = this.getDeclForAST(funcDeclAST); + this.currentUnit.addSynthesizedDecl(functionDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + binder.setUnit(this.unitPath); + + if (funcDeclAST.isGetAccessor()) { + binder.bindGetAccessorDeclarationToPullSymbol(functionDecl); + } else { + binder.bindSetAccessorDeclarationToPullSymbol(functionDecl); + } + } + } + + var memberExprType = this.resolveAST(binex.operand2, assigningSymbol != null, enclosingDecl, context).symbol; + + if (acceptedContextualType) { + context.popContextualType(); + acceptedContextualType = false; + } + + context.setTypeInContext(memberSymbol, memberExprType.getType()); + + memberSymbol.setResolved(); + + this.setSymbolAndDiagnosticsForAST(binex.operand1, SymbolAndDiagnostics.fromSymbol(memberSymbol), context); + + typeSymbol.addMember(memberSymbol, 5 /* PublicMember */); + } + } + + typeSymbol.setResolved(); + return SymbolAndDiagnostics.fromSymbol(typeSymbol); + }; + + PullTypeResolver.prototype.resolveArrayLiteralExpression = function (arrayLit, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(arrayLit); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeArrayLiteralExpressionSymbol(arrayLit, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(arrayLit, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeArrayLiteralExpressionSymbol = function (arrayLit, inContextuallyTypedAssignment, enclosingDecl, context) { + var elements = arrayLit.operand; + var elementType = this.semanticInfoChain.anyTypeSymbol; + var elementTypes = []; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var contextualElementType = null; + comparisonInfo.onlyCaptureFirstError = true; + + if (inContextuallyTypedAssignment) { + var contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, enclosingDecl, context); + + if (contextualType && contextualType.isArray()) { + contextualElementType = contextualType.getElementType(); + } + } + + if (elements) { + if (inContextuallyTypedAssignment) { + context.pushContextualType(contextualElementType, context.inProvisionalResolution(), null); + } + + for (var i = 0; i < elements.members.length; i++) { + elementTypes[elementTypes.length] = this.resolveAST(elements.members[i], inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + } + + if (inContextuallyTypedAssignment) { + context.popContextualType(); + } + } + + if (contextualElementType && !contextualElementType.isTypeParameter()) { + elementType = contextualElementType; + + for (var i = 0; i < elementTypes.length; i++) { + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var currentElementType = elementTypes[i]; + var currentElementAST = elements.members[i]; + if (!this.sourceIsAssignableToTarget(currentElementType, contextualElementType, context, comparisonInfo)) { + var message; + if (comparisonInfo.message) { + message = context.postError(this.getUnitPath(), currentElementAST.minChar, currentElementAST.getLength(), 81 /* Cannot_convert__0__to__1__NL__2 */, [currentElementType.toString(), contextualElementType.toString(), comparisonInfo.message]); + } else { + message = context.postError(this.getUnitPath(), currentElementAST.minChar, currentElementAST.getLength(), 80 /* Cannot_convert__0__to__1_ */, [currentElementType.toString(), contextualElementType.toString()]); + } + + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [message]); + } + } + } else { + if (elementTypes.length) { + elementType = elementTypes[0]; + } else if (contextualElementType) { + elementType = contextualElementType; + } + + var collection = { + getLength: function () { + return elements.members.length; + }, + setTypeAtIndex: function (index, type) { + elementTypes[index] = type; + }, + getTypeAtIndex: function (index) { + return elementTypes[index]; + } + }; + + elementType = this.findBestCommonType(elementType, null, collection, context, comparisonInfo); + + if (elementType === this.semanticInfoChain.undefinedTypeSymbol || elementType === this.semanticInfoChain.nullTypeSymbol) { + elementType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!elementType) { + elementType = this.semanticInfoChain.anyTypeSymbol; + } else if (contextualType && !contextualType.isTypeParameter()) { + if (this.sourceIsAssignableToTarget(elementType, contextualType, context)) { + elementType = contextualType; + } + } + } + + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + if (!this.cachedArrayInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedArrayInterfaceType(), enclosingDecl, context); + } + + arraySymbol = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, elementType, this, context); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + } + + return SymbolAndDiagnostics.fromSymbol(arraySymbol); + }; + + PullTypeResolver.prototype.resolveIndexExpression = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(callEx); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeIndexExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(callEx, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeIndexExpressionSymbol = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context) { + var targetSymbol = this.resolveAST(callEx.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol; + + var targetTypeSymbol = targetSymbol.getType(); + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return SymbolAndDiagnostics.fromSymbol(targetTypeSymbol); + } + + var elementType = targetTypeSymbol.getElementType(); + + var indexType = this.resolveAST(callEx.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + var isNumberIndex = indexType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(indexType); + + if (elementType && isNumberIndex) { + return SymbolAndDiagnostics.fromSymbol(elementType); + } + + if (callEx.operand2.nodeType === 5 /* StringLiteral */ || callEx.operand2.nodeType === 7 /* NumericLiteral */) { + var memberName = callEx.operand2.nodeType === 5 /* StringLiteral */ ? TypeScript.stripQuotes((callEx.operand2).actualText) : TypeScript.quoteStr((callEx.operand2).value.toString()); + + var member = this.getMemberSymbol(memberName, TypeScript.PullElementKind.SomeValue, targetTypeSymbol); + + if (member) { + return SymbolAndDiagnostics.fromSymbol(member.getType()); + } + } + + var signatures = targetTypeSymbol.getIndexSignatures(); + + var stringSignature = null; + var numberSignature = null; + var signature = null; + var paramSymbols; + var paramType; + + for (var i = 0; i < signatures.length; i++) { + if (stringSignature && numberSignature) { + break; + } + + signature = signatures[i]; + + paramSymbols = signature.getParameters(); + + if (paramSymbols.length) { + paramType = paramSymbols[0].getType(); + + if (paramType === this.semanticInfoChain.stringTypeSymbol) { + stringSignature = signatures[i]; + continue; + } else if (paramType === this.semanticInfoChain.numberTypeSymbol || paramType.getKind() === 64 /* Enum */) { + numberSignature = signatures[i]; + continue; + } + } + } + + if (numberSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol)) { + var returnType = numberSignature.getReturnType(); + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { + var returnType = stringSignature.getReturnType(); + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + var returnType = this.semanticInfoChain.anyTypeSymbol; + return SymbolAndDiagnostics.fromSymbol(returnType); + } else { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.getUnitPath(), callEx.minChar, callEx.getLength(), 77 /* Value_of_type__0__is_not_indexable_by_type__1_ */, [targetTypeSymbol.toString(false), indexType.toString(false)])]); + } + }; + + PullTypeResolver.prototype.resolveBitwiseOperator = function (expressionAST, inContextuallyTypedAssignment, enclosingDecl, context) { + var binex = expressionAST; + + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + if (this.sourceIsSubtypeOfTarget(leftType, this.semanticInfoChain.numberTypeSymbol, context) && this.sourceIsSubtypeOfTarget(rightType, this.semanticInfoChain.numberTypeSymbol, context)) { + return this.semanticInfoChain.numberTypeSymbol; + } else if ((leftType === this.semanticInfoChain.booleanTypeSymbol) && (rightType === this.semanticInfoChain.booleanTypeSymbol)) { + return this.semanticInfoChain.booleanTypeSymbol; + } else if (this.isAnyOrEquivalent(leftType)) { + if ((this.isAnyOrEquivalent(rightType) || (rightType === this.semanticInfoChain.numberTypeSymbol) || (rightType === this.semanticInfoChain.booleanTypeSymbol))) { + return this.semanticInfoChain.anyTypeSymbol; + } + } else if (this.isAnyOrEquivalent(rightType)) { + if ((leftType === this.semanticInfoChain.numberTypeSymbol) || (leftType === this.semanticInfoChain.booleanTypeSymbol)) { + return this.semanticInfoChain.anyTypeSymbol; + } + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveArithmeticExpression = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + if (this.isNullOrUndefinedType(leftType)) { + leftType = rightType; + } + if (this.isNullOrUndefinedType(rightType)) { + rightType = leftType; + } + + leftType = this.widenType(leftType); + rightType = this.widenType(rightType); + + if (binex.nodeType === 64 /* AddExpression */ || binex.nodeType === 39 /* AddAssignmentExpression */) { + if (leftType === this.semanticInfoChain.stringTypeSymbol || rightType === this.semanticInfoChain.stringTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + } else if (leftType === this.semanticInfoChain.numberTypeSymbol && rightType === this.semanticInfoChain.numberTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (this.sourceIsSubtypeOfTarget(leftType, this.semanticInfoChain.numberTypeSymbol, context) && this.sourceIsSubtypeOfTarget(rightType, this.semanticInfoChain.numberTypeSymbol, context)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else { + if (leftType === this.semanticInfoChain.numberTypeSymbol && rightType === this.semanticInfoChain.numberTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (this.sourceIsSubtypeOfTarget(leftType, this.semanticInfoChain.numberTypeSymbol, context) && this.sourceIsSubtypeOfTarget(rightType, this.semanticInfoChain.numberTypeSymbol, context)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (this.isAnyOrEquivalent(leftType) || this.isAnyOrEquivalent(rightType)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } + }; + + PullTypeResolver.prototype.resolveLogicalOrExpression = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(binex); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeLogicalOrExpressionSymbol(binex, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(binex, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeLogicalOrExpressionSymbol = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + if (this.isAnyOrEquivalent(leftType) || this.isAnyOrEquivalent(rightType)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } else if (leftType === this.semanticInfoChain.booleanTypeSymbol) { + if (rightType === this.semanticInfoChain.booleanTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else if (leftType === this.semanticInfoChain.numberTypeSymbol) { + if (rightType === this.semanticInfoChain.numberTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else if (leftType === this.semanticInfoChain.stringTypeSymbol) { + if (rightType === this.semanticInfoChain.stringTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else if (this.sourceIsSubtypeOfTarget(leftType, rightType, context)) { + return SymbolAndDiagnostics.fromSymbol(rightType); + } else if (this.sourceIsSubtypeOfTarget(rightType, leftType, context)) { + return SymbolAndDiagnostics.fromSymbol(leftType); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveLogicalAndExpression = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + return SymbolAndDiagnostics.fromSymbol(this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType()); + }; + + PullTypeResolver.prototype.resolveConditionalExpression = function (trinex, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(trinex); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeConditionalExpressionSymbol(trinex, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(trinex, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeConditionalExpressionSymbol = function (trinex, enclosingDecl, context) { + var leftType = this.resolveAST(trinex.operand2, false, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(trinex.operand3, false, enclosingDecl, context).symbol.getType(); + + var symbol = null; + if (this.typesAreIdentical(leftType, rightType)) { + symbol = leftType; + } else if (this.sourceIsSubtypeOfTarget(leftType, rightType, context) || this.sourceIsSubtypeOfTarget(rightType, leftType, context)) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return rightType; + } + }; + + var bestCommonType = this.findBestCommonType(leftType, null, collection, context); + + if (bestCommonType) { + symbol = bestCommonType; + } + } + + if (!symbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.getUnitPath(), trinex.minChar, trinex.getLength(), 160 /* Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_ */, [leftType.toString(false), rightType.toString(false)])]); + } + + return SymbolAndDiagnostics.fromSymbol(symbol); + }; + + PullTypeResolver.prototype.resolveParenthesizedExpression = function (ast, enclosingDecl, context) { + return this.resolveAST(ast.expression, false, enclosingDecl, context).withoutDiagnostics(); + }; + + PullTypeResolver.prototype.resolveExpressionStatement = function (ast, inContextuallyTypedAssignment, enclosingDecl, context) { + return this.resolveAST(ast.expression, inContextuallyTypedAssignment, enclosingDecl, context).withoutDiagnostics(); + }; + + PullTypeResolver.prototype.resolveCallExpression = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + if (additionalResults) { + return this.computeCallExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults); + } + + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(callEx); + if (!symbolAndDiagnostics || !symbolAndDiagnostics.symbol.isResolved()) { + symbolAndDiagnostics = this.computeCallExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, null); + this.setSymbolAndDiagnosticsForAST(callEx, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeCallExpressionSymbol = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var targetSymbol = this.resolveAST(callEx.target, inContextuallyTypedAssignment, enclosingDecl, context).symbol; + var targetAST = this.getLastIdentifierInTarget(callEx); + + var targetTypeSymbol = targetSymbol.getType(); + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + if (callEx.typeArguments) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 223 /* Untyped_function_calls_may_not_accept_type_arguments */)]); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var diagnostics = []; + var isSuperCall = false; + + if (callEx.target.nodeType === 30 /* SuperExpression */) { + isSuperCall = true; + + if (targetTypeSymbol.isClass()) { + targetSymbol = (targetTypeSymbol).getConstructorMethod(); + targetTypeSymbol = targetSymbol.getType(); + } else { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 158 /* Calls_to__super__are_only_valid_inside_a_class */)); + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), diagnostics); + } + } + + var signatures = isSuperCall ? (targetTypeSymbol).getConstructSignatures() : (targetTypeSymbol).getCallSignatures(); + + if (!signatures.length && (targetTypeSymbol.getKind() == 33554432 /* ConstructorType */)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 227 /* Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___ */, [targetTypeSymbol.toString()])); + } + + var typeArgs = null; + var typeReplacementMap = null; + var couldNotFindGenericOverload = false; + var couldNotAssignToConstraint; + + if (callEx.typeArguments) { + typeArgs = []; + + if (callEx.typeArguments && callEx.typeArguments.members.length) { + for (var i = 0; i < callEx.typeArguments.members.length; i++) { + var typeArg = this.resolveTypeReference(callEx.typeArguments.members[i], enclosingDecl, context).symbol; + typeArgs[i] = context.findSpecializationForType(typeArg); + } + } + } else if (isSuperCall && targetTypeSymbol.isGeneric()) { + typeArgs = targetTypeSymbol.getTypeArguments(); + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var prevSpecializingToAny = context.specializingToAny; + var prevSpecializing = context.isSpecializingSignatureAtCallSite; + var beforeResolutionSignatures = signatures; + var triedToInferTypeArgs; + + for (var i = 0; i < signatures.length; i++) { + typeParameters = signatures[i].getTypeParameters(); + couldNotAssignToConstraint = false; + triedToInferTypeArgs = false; + + if (signatures[i].isGeneric() && typeParameters.length && !signatures[i].isFixed()) { + if (typeArgs) { + inferredTypeArgs = typeArgs; + } else if (callEx.arguments) { + inferredTypeArgs = this.inferArgumentTypesForSignature(signatures[i], callEx.arguments, new TypeScript.TypeComparisonInfo(), enclosingDecl, context); + triedToInferTypeArgs = true; + } + + if (inferredTypeArgs) { + typeReplacementMap = {}; + + if (inferredTypeArgs.length) { + if (inferredTypeArgs.length != typeParameters.length) { + continue; + } + + for (var j = 0; j < typeParameters.length; j++) { + typeReplacementMap[typeParameters[j].getSymbolID().toString()] = inferredTypeArgs[j]; + } + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { + if (typeParameters[k] == typeConstraint) { + typeConstraint = inferredTypeArgs[k]; + } + } + } + if (typeConstraint.isTypeParameter()) { + context.pushTypeSpecializationCache(typeReplacementMap); + typeConstraint = TypeScript.specializeType(typeConstraint, null, this, enclosingDecl, context); + context.popTypeSpecializationCache(); + } + context.isComparingSpecializedSignatures = true; + if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, context)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 155 /* Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_ */, [inferredTypeArgs[j].toString(true), typeConstraint.toString(true), typeParameters[j].toString(true)])); + couldNotAssignToConstraint = true; + } + context.isComparingSpecializedSignatures = false; + + if (couldNotAssignToConstraint) { + break; + } + } + } + } else { + if (triedToInferTypeArgs) { + if (signatures[i].parametersAreFixed()) { + if (signatures[i].hasGenericParameter()) { + context.specializingToAny = true; + } else { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } else { + continue; + } + } + + context.specializingToAny = true; + } + + if (couldNotAssignToConstraint) { + continue; + } + + context.isSpecializingSignatureAtCallSite = true; + specializedSignature = TypeScript.specializeSignature(signatures[i], false, typeReplacementMap, inferredTypeArgs, this, enclosingDecl, context); + + context.isSpecializingSignatureAtCallSite = prevSpecializing; + context.specializingToAny = prevSpecializingToAny; + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } + } else { + if (!(callEx.typeArguments && callEx.typeArguments.members.length)) { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } + } + + if (signatures.length && !resolvedSignatures.length) { + couldNotFindGenericOverload = true; + } + + signatures = resolvedSignatures; + } + + var errorCondition = null; + + if (!signatures.length) { + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures && beforeResolutionSignatures.length ? beforeResolutionSignatures[0] : null; + + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + } + + if (!couldNotFindGenericOverload) { + if (this.cachedFunctionInterfaceType() && this.sourceIsSubtypeOfTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), context)) { + return SymbolAndDiagnostics.create(this.semanticInfoChain.anyTypeSymbol, diagnostics); + } + + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, callEx.minChar, callEx.getLength(), 157 /* Unable_to_invoke_type_with_no_call_signatures */)); + errorCondition = this.getNewErrorTypeSymbol(null); + } else { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, callEx.minChar, callEx.getLength(), 156 /* Could_not_select_overload_for__call__expression */)); + errorCondition = this.getNewErrorTypeSymbol(null); + } + + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + var signature = this.resolveOverloads(callEx, signatures, enclosingDecl, callEx.typeArguments != null, context, diagnostics); + var useBeforeResolutionSignatures = signature == null; + + if (!signature) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 156 /* Could_not_select_overload_for__call__expression */)); + + errorCondition = this.getNewErrorTypeSymbol(null); + + if (!signatures.length) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + signature = signatures[0]; + + if (callEx.arguments) { + for (var k = 0, n = callEx.arguments.members.length; k < n; k++) { + var arg = callEx.arguments.members[k]; + var argSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(arg); + var argSymbol = argSymbolAndDiagnostics && argSymbolAndDiagnostics.symbol; + + if (argSymbol) { + var argType = argSymbol.getType(); + if (arg.nodeType === 12 /* FunctionDeclaration */) { + if (!this.canApplyContextualTypeToFunction(argType, arg, true)) { + continue; + } + } + + argSymbol.invalidate(); + } + } + } + } + + if (!signature.isGeneric() && callEx.typeArguments) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 224 /* Non_generic_functions_may_not_accept_type_arguments */)); + } + + var returnType = signature.getReturnType(); + + var actualParametersContextTypeSymbols = []; + if (callEx.arguments) { + var len = callEx.arguments.members.length; + var params = signature.getParameters(); + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVariableParamList())) { + if (typeReplacementMap) { + context.pushTypeSpecializationCache(typeReplacementMap); + } + this.resolveDeclaredSymbol(params[i], signatureDecl, context); + if (typeReplacementMap) { + context.popTypeSpecializationCache(); + } + contextualType = params[i].getType(); + } else if (signature.hasVariableParamList()) { + contextualType = params[params.length - 1].getType(); + if (contextualType.isArray()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.arguments.members[i], contextualType != null, enclosingDecl, context); + + if (contextualType) { + context.popContextualType(); + contextualType = null; + } + } + } + + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + if (useBeforeResolutionSignatures && beforeResolutionSignatures) { + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures[0]; + } else { + additionalResults.resolvedSignatures = signatures; + additionalResults.candidateSignature = signature; + } + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + } + + if (errorCondition) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + }; + + PullTypeResolver.prototype.resolveNewExpression = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + if (additionalResults) { + return this.computeNewExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults); + } + + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(callEx); + if (!symbolAndDiagnostics || !symbolAndDiagnostics.symbol.isResolved()) { + symbolAndDiagnostics = this.computeNewExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, null); + this.setSymbolAndDiagnosticsForAST(callEx, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeNewExpressionSymbol = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var returnType = null; + + var targetSymbol = this.resolveAST(callEx.target, inContextuallyTypedAssignment, enclosingDecl, context).symbol; + var targetTypeSymbol = targetSymbol.isType() ? targetSymbol : targetSymbol.getType(); + + var targetAST = this.getLastIdentifierInTarget(callEx); + + if (targetTypeSymbol.isClass()) { + targetTypeSymbol = (targetTypeSymbol).getConstructorMethod().getType(); + } + + var constructSignatures = targetTypeSymbol.getConstructSignatures(); + + var typeArgs = null; + var typeReplacementMap = null; + var usedCallSignaturesInstead = false; + var couldNotAssignToConstraint; + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return SymbolAndDiagnostics.fromSymbol(targetTypeSymbol); + } + + if (!constructSignatures.length) { + constructSignatures = targetTypeSymbol.getCallSignatures(); + usedCallSignaturesInstead = true; + } + + var diagnostics = []; + if (constructSignatures.length) { + if (callEx.typeArguments) { + typeArgs = []; + + if (callEx.typeArguments && callEx.typeArguments.members.length) { + for (var i = 0; i < callEx.typeArguments.members.length; i++) { + var typeArg = this.resolveTypeReference(callEx.typeArguments.members[i], enclosingDecl, context).symbol; + typeArgs[i] = context.findSpecializationForType(typeArg); + } + } + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var prevSpecializingToAny = context.specializingToAny; + var prevIsSpecializing = context.isSpecializingSignatureAtCallSite = true; + var triedToInferTypeArgs; + + for (var i = 0; i < constructSignatures.length; i++) { + couldNotAssignToConstraint = false; + + if (constructSignatures[i].isGeneric() && !constructSignatures[i].isFixed()) { + if (typeArgs) { + inferredTypeArgs = typeArgs; + } else if (callEx.arguments) { + inferredTypeArgs = this.inferArgumentTypesForSignature(constructSignatures[i], callEx.arguments, new TypeScript.TypeComparisonInfo(), enclosingDecl, context); + triedToInferTypeArgs = true; + } + + if (inferredTypeArgs) { + typeParameters = constructSignatures[i].getTypeParameters(); + + typeReplacementMap = {}; + + if (inferredTypeArgs.length) { + if (inferredTypeArgs.length < typeParameters.length) { + continue; + } + + for (var j = 0; j < typeParameters.length; j++) { + typeReplacementMap[typeParameters[j].getSymbolID().toString()] = inferredTypeArgs[j]; + } + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { + if (typeParameters[k] == typeConstraint) { + typeConstraint = inferredTypeArgs[k]; + } + } + } + if (typeConstraint.isTypeParameter()) { + context.pushTypeSpecializationCache(typeReplacementMap); + typeConstraint = TypeScript.specializeType(typeConstraint, null, this, enclosingDecl, context); + context.popTypeSpecializationCache(); + } + + context.isComparingSpecializedSignatures = true; + if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, context)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 155 /* Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_ */, [inferredTypeArgs[j].toString(true), typeConstraint.toString(true), typeParameters[j].toString(true)])); + couldNotAssignToConstraint = true; + } + context.isComparingSpecializedSignatures = false; + + if (couldNotAssignToConstraint) { + break; + } + } + } + } else { + if (triedToInferTypeArgs) { + if (constructSignatures[i].parametersAreFixed()) { + if (constructSignatures[i].hasGenericParameter()) { + context.specializingToAny = true; + } else { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } else { + continue; + } + } + + context.specializingToAny = true; + } + + if (couldNotAssignToConstraint) { + continue; + } + + context.isSpecializingSignatureAtCallSite = true; + specializedSignature = TypeScript.specializeSignature(constructSignatures[i], false, typeReplacementMap, inferredTypeArgs, this, enclosingDecl, context); + + context.specializingToAny = prevSpecializingToAny; + context.isSpecializingSignatureAtCallSite = prevIsSpecializing; + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } + } else { + if (!(callEx.typeArguments && callEx.typeArguments.members.length)) { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } + } + + constructSignatures = resolvedSignatures; + } + + var signature = this.resolveOverloads(callEx, constructSignatures, enclosingDecl, callEx.typeArguments != null, context, diagnostics); + + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = []; + } + + if (!constructSignatures.length && diagnostics) { + var result = this.getNewErrorTypeSymbol(null); + return SymbolAndDiagnostics.create(result, diagnostics); + } + + var errorCondition = null; + + if (!signature) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 154 /* Could_not_select_overload_for__new__expression */)); + + errorCondition = this.getNewErrorTypeSymbol(null); + + if (!constructSignatures.length) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + signature = constructSignatures[0]; + + if (callEx.arguments) { + for (var k = 0, n = callEx.arguments.members.length; k < n; k++) { + var arg = callEx.arguments.members[k]; + var argSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(arg); + var argSymbol = argSymbolAndDiagnostics && argSymbolAndDiagnostics.symbol; + + if (argSymbol) { + var argType = argSymbol.getType(); + if (arg.nodeType === 12 /* FunctionDeclaration */) { + if (!this.canApplyContextualTypeToFunction(argType, arg, true)) { + continue; + } + } + + argSymbol.invalidate(); + } + } + } + } + + returnType = signature.getReturnType(); + + if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { + if (typeArgs && typeArgs.length) { + returnType = TypeScript.specializeType(returnType, typeArgs, this, enclosingDecl, context, callEx); + } else { + returnType = this.specializeTypeToAny(returnType, enclosingDecl, context); + } + } + + if (usedCallSignaturesInstead) { + if (returnType != this.semanticInfoChain.voidTypeSymbol) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 153 /* Call_signatures_used_in_a__new__expression_must_have_a__void__return_type */)); + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), diagnostics); + } else { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (!returnType) { + returnType = signature.getReturnType(); + + if (!returnType) { + returnType = targetTypeSymbol; + } + } + + var actualParametersContextTypeSymbols = []; + if (callEx.arguments) { + var len = callEx.arguments.members.length; + var params = signature.getParameters(); + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVariableParamList())) { + if (typeReplacementMap) { + context.pushTypeSpecializationCache(typeReplacementMap); + } + this.resolveDeclaredSymbol(params[i], signatureDecl, context); + if (typeReplacementMap) { + context.popTypeSpecializationCache(); + } + contextualType = params[i].getType(); + } else if (signature.hasVariableParamList()) { + contextualType = params[params.length - 1].getType(); + if (contextualType.isArray()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.arguments.members[i], contextualType != null, enclosingDecl, context); + + if (contextualType) { + context.popContextualType(); + contextualType = null; + } + } + } + + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + } + + if (errorCondition) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + } else if (targetTypeSymbol.isClass()) { + return SymbolAndDiagnostics.fromSymbol(returnType); + } + + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 152 /* Invalid__new__expression */)); + + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), diagnostics); + }; + + PullTypeResolver.prototype.resolveTypeAssertionExpression = function (assertionExpression, inContextuallyTypedAssignment, enclosingDecl, context) { + return this.resolveTypeReference(assertionExpression.castTerm, enclosingDecl, context); + }; + + PullTypeResolver.prototype.resolveAssignmentStatement = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(binex); + + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeAssignmentStatementSymbol(binex, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(binex, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeAssignmentStatementSymbol = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + context.pushContextualType(leftType, context.inProvisionalResolution(), null); + this.resolveAST(binex.operand2, true, enclosingDecl, context); + context.popContextualType(); + + return SymbolAndDiagnostics.fromSymbol(leftType); + }; + + PullTypeResolver.prototype.resolveBoundDecls = function (decl, context) { + if (!decl) { + return; + } + + switch (decl.getKind()) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.resolveBoundDecls(childDecls[i], context); + } + break; + case 32 /* DynamicModule */: + case 4 /* Container */: + case 64 /* Enum */: + var moduleDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveModuleDeclaration(moduleDecl, context); + break; + case 16 /* Interface */: + var interfaceDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveInterfaceDeclaration(interfaceDecl, context); + break; + case 8 /* Class */: + var classDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveClassDeclaration(classDecl, context); + break; + case 65536 /* Method */: + case 16384 /* Function */: + var funcDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveFunctionDeclaration(funcDecl, context); + break; + case 262144 /* GetAccessor */: + funcDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveGetAccessorDeclaration(funcDecl, context); + break; + case 524288 /* SetAccessor */: + funcDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveSetAccessorDeclaration(funcDecl, context); + break; + case 4096 /* Property */: + case 1024 /* Variable */: + case 2048 /* Parameter */: + var varDecl = this.semanticInfoChain.getASTForDecl(decl); + + if (varDecl) { + this.resolveVariableDeclaration(varDecl, context); + } + break; + } + }; + + PullTypeResolver.prototype.mergeOrdered = function (a, b, context, comparisonInfo) { + if (this.isAnyOrEquivalent(a) || this.isAnyOrEquivalent(b)) { + return this.semanticInfoChain.anyTypeSymbol; + } else if (a === b) { + return a; + } else if ((b === this.semanticInfoChain.nullTypeSymbol) && a != this.semanticInfoChain.nullTypeSymbol) { + return a; + } else if ((a === this.semanticInfoChain.nullTypeSymbol) && (b != this.semanticInfoChain.nullTypeSymbol)) { + return b; + } else if ((a === this.semanticInfoChain.voidTypeSymbol) && (b === this.semanticInfoChain.voidTypeSymbol || b === this.semanticInfoChain.undefinedTypeSymbol || b === this.semanticInfoChain.nullTypeSymbol)) { + return a; + } else if ((a === this.semanticInfoChain.voidTypeSymbol) && (b === this.semanticInfoChain.anyTypeSymbol)) { + return b; + } else if ((b === this.semanticInfoChain.undefinedTypeSymbol) && a != this.semanticInfoChain.voidTypeSymbol) { + return a; + } else if ((a === this.semanticInfoChain.undefinedTypeSymbol) && (b != this.semanticInfoChain.undefinedTypeSymbol)) { + return b; + } else if (a.isTypeParameter() && !b.isTypeParameter()) { + return b; + } else if (!a.isTypeParameter() && b.isTypeParameter()) { + return a; + } else if (a.isArray() && b.isArray()) { + if (a.getElementType() === b.getElementType()) { + return a; + } else { + var mergedET = this.mergeOrdered(a.getElementType(), b.getElementType(), context, comparisonInfo); + if (mergedET) { + var mergedArrayType = mergedET.getArrayType(); + + if (!mergedArrayType) { + mergedArrayType = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, mergedET, this, context); + } + + return mergedArrayType; + } + } + } else if (this.sourceIsSubtypeOfTarget(a, b, context, comparisonInfo)) { + return b; + } else if (this.sourceIsSubtypeOfTarget(b, a, context, comparisonInfo)) { + return a; + } + + return null; + }; + + PullTypeResolver.prototype.widenType = function (type) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol || type.isError()) { + return this.semanticInfoChain.anyTypeSymbol; + } + + return type; + }; + + PullTypeResolver.prototype.isNullOrUndefinedType = function (type) { + return type === this.semanticInfoChain.nullTypeSymbol || type === this.semanticInfoChain.undefinedTypeSymbol; + }; + + PullTypeResolver.prototype.canApplyContextualType = function (type) { + if (!type) { + return true; + } + + var kind = type.getKind(); + + if ((kind & 8388608 /* ObjectType */) != 0) { + return true; + } + if ((kind & 16 /* Interface */) != 0) { + return true; + } else if ((kind & TypeScript.PullElementKind.SomeFunction) != 0) { + return this.canApplyContextualTypeToFunction(type, this.semanticInfoChain.getASTForDecl(type.getDeclarations[0]), true); + } else if ((kind & 128 /* Array */) != 0) { + return true; + } else if (type == this.semanticInfoChain.anyTypeSymbol || kind != 2 /* Primitive */) { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.findBestCommonType = function (initialType, targetType, collection, context, comparisonInfo) { + var len = collection.getLength(); + var nlastChecked = 0; + var bestCommonType = initialType; + + if (targetType && this.canApplyContextualType(bestCommonType)) { + if (bestCommonType) { + bestCommonType = this.mergeOrdered(bestCommonType, targetType, context); + } else { + bestCommonType = targetType; + } + } + + var convergenceType = bestCommonType; + + while (nlastChecked < len) { + for (var i = 0; i < len; i++) { + if (i === nlastChecked) { + continue; + } + + if (convergenceType && (bestCommonType = this.mergeOrdered(convergenceType, collection.getTypeAtIndex(i), context, comparisonInfo))) { + convergenceType = bestCommonType; + } + + if (bestCommonType === null || this.isAnyOrEquivalent(bestCommonType)) { + break; + } else if (targetType && !(bestCommonType.isTypeParameter() || targetType.isTypeParameter())) { + collection.setTypeAtIndex(i, targetType); + } + } + + if (convergenceType && bestCommonType) { + break; + } + + nlastChecked++; + if (nlastChecked < len) { + convergenceType = collection.getTypeAtIndex(nlastChecked); + } + } + + if (!bestCommonType) { + var emptyTypeDecl = new TypeScript.PullDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, new TypeScript.TextSpan(0, 0), this.currentUnit.getPath()); + var emptyType = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); + + emptyTypeDecl.setSymbol(emptyType); + emptyType.addDeclaration(emptyTypeDecl); + + bestCommonType = emptyType; + } + + return bestCommonType; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, val) { + if (t1 === t2) { + return true; + } + + if (!t1 || !t2) { + return false; + } + + if (val && t1.isPrimitive() && (t1).isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { + return (val.nodeType === 5 /* StringLiteral */) && (TypeScript.stripQuotes((val).actualText) === TypeScript.stripQuotes(t1.getName())); + } + + if (val && t2.isPrimitive() && (t2).isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { + return (val.nodeType === 5 /* StringLiteral */) && (TypeScript.stripQuotes((val).actualText) === TypeScript.stripQuotes(t2.getName())); + } + + if (t1.isPrimitive() && (t1).isStringConstant() && t2.isPrimitive() && (t2).isStringConstant()) { + return TypeScript.stripQuotes(t1.getName()) === TypeScript.stripQuotes(t2.getName()); + } + + if (t1.isPrimitive() || t2.isPrimitive()) { + return false; + } + + if (t1.isClass()) { + return false; + } + + if (t1.isError() && t2.isError()) { + return true; + } + + if (t1.isTypeParameter()) { + if (!t2.isTypeParameter()) { + return false; + } + + var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); + var t2ParentDeclaration = t2.getDeclarations()[0].getParentDecl(); + + if (t1ParentDeclaration === t2ParentDeclaration) { + return this.symbolsShareDeclaration(t1, t2); + } else { + return true; + } + } + + var comboId = t2.getSymbolID().toString() + "#" + t1.getSymbolID().toString(); + + if (this.identicalCache[comboId] != undefined) { + return true; + } + + if ((t1.getKind() & 64 /* Enum */) || (t2.getKind() & 64 /* Enum */)) { + return t1.getAssociatedContainerType() === t2 || t2.getAssociatedContainerType() === t1; + } + + if (t1.isArray() || t2.isArray()) { + if (!(t1.isArray() && t2.isArray())) { + return false; + } + this.identicalCache[comboId] = false; + var ret = this.typesAreIdentical(t1.getElementType(), t2.getElementType()); + if (ret) { + this.identicalCache[comboId] = true; + } else { + this.identicalCache[comboId] = undefined; + } + + return ret; + } + + if (t1.isPrimitive() != t2.isPrimitive()) { + return false; + } + + this.identicalCache[comboId] = false; + + if (t1.hasMembers() && t2.hasMembers()) { + var t1Members = t1.getMembers(); + var t2Members = t2.getMembers(); + + if (t1Members.length != t2Members.length) { + this.identicalCache[comboId] = undefined; + return false; + } + + var t1MemberSymbol = null; + var t2MemberSymbol = null; + + var t1MemberType = null; + var t2MemberType = null; + + for (var iMember = 0; iMember < t1Members.length; iMember++) { + t1MemberSymbol = t1Members[iMember]; + t2MemberSymbol = this.getMemberSymbol(t1MemberSymbol.getName(), TypeScript.PullElementKind.SomeValue, t2); + + if (!t2MemberSymbol || (t1MemberSymbol.getIsOptional() != t2MemberSymbol.getIsOptional())) { + this.identicalCache[comboId] = undefined; + return false; + } + + t1MemberType = t1MemberSymbol.getType(); + t2MemberType = t2MemberSymbol.getType(); + + if (t1MemberType && t2MemberType && (this.identicalCache[t2MemberType.getSymbolID().toString() + "#" + t1MemberType.getSymbolID().toString()] != undefined)) { + continue; + } + + if (!this.typesAreIdentical(t1MemberType, t2MemberType)) { + this.identicalCache[comboId] = undefined; + return false; + } + } + } else if (t1.hasMembers() || t2.hasMembers()) { + this.identicalCache[comboId] = undefined; + return false; + } + + var t1CallSigs = t1.getCallSignatures(); + var t2CallSigs = t2.getCallSignatures(); + + var t1ConstructSigs = t1.getConstructSignatures(); + var t2ConstructSigs = t2.getConstructSignatures(); + + var t1IndexSigs = t1.getIndexSignatures(); + var t2IndexSigs = t2.getIndexSignatures(); + + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs)) { + this.identicalCache[comboId] = undefined; + return false; + } + + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs)) { + this.identicalCache[comboId] = undefined; + return false; + } + + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs)) { + this.identicalCache[comboId] = undefined; + return false; + } + + this.identicalCache[comboId] = true; + return true; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + if (sg1 === sg2) { + return true; + } + + if (!sg1 || !sg2) { + return false; + } + + if (sg1.length != sg2.length) { + return false; + } + + var sig1 = null; + var sig2 = null; + var sigsMatch = false; + + for (var iSig1 = 0; iSig1 < sg1.length; iSig1++) { + sig1 = sg1[iSig1]; + + for (var iSig2 = 0; iSig2 < sg2.length; iSig2++) { + sig2 = sg2[iSig2]; + + if (this.signaturesAreIdentical(sig1, sig2)) { + sigsMatch = true; + break; + } + } + + if (sigsMatch) { + sigsMatch = false; + continue; + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2) { + if (s1.hasVariableParamList() != s2.hasVariableParamList()) { + return false; + } + + if (s1.getNonOptionalParameterCount() != s2.getNonOptionalParameterCount()) { + return false; + } + + var s1Params = s1.getParameters(); + var s2Params = s2.getParameters(); + + if (s1Params.length != s2Params.length) { + return false; + } + + if (!this.typesAreIdentical(s1.getReturnType(), s2.getReturnType())) { + return false; + } + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + if (!this.typesAreIdentical(s1Params[iParam].getType(), s2Params[iParam].getType())) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.substituteUpperBoundForType = function (type) { + if (!type || !type.isTypeParameter()) { + return type; + } + + var constraint = (type).getConstraint(); + + if (constraint) { + return this.substituteUpperBoundForType(constraint); + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType(); + } + + return type; + }; + + PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { + var decls1 = symbol1.getDeclarations(); + var decls2 = symbol2.getDeclarations(); + + if (decls1.length && decls2.length) { + return decls1[0].isEqual(decls2[0]); + } + + return false; + }; + + PullTypeResolver.prototype.sourceIsSubtypeOfTarget = function (source, target, context, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceMembersAreSubtypeOfTargetMembers = function (source, target, context, comparisonInfo) { + return this.sourceMembersAreRelatableToTargetMembers(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourcePropertyIsSubtypeOfTargetProperty = function (source, target, sourceProp, targetProp, context, comparisonInfo) { + return this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreSubtypeOfTargetCallSignatures = function (source, target, context, comparisonInfo) { + return this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures = function (source, target, context, comparisonInfo) { + return this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures = function (source, target, context, comparisonInfo) { + return this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.typeIsSubtypeOfFunction = function (source, context) { + var callSignatures = source.getCallSignatures(); + + if (callSignatures.length) { + return true; + } + + var constructSignatures = source.getConstructSignatures(); + + if (constructSignatures.length) { + return true; + } + + if (this.cachedFunctionInterfaceType()) { + return this.sourceIsSubtypeOfTarget(source, this.cachedFunctionInterfaceType(), context); + } + + return false; + }; + + PullTypeResolver.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, context, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.signatureIsSubtypeOfTarget = function (s1, s2, context, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, context, comparisonInfo, isInProvisionalResolution) { + if (typeof isInProvisionalResolution === "undefined") { isInProvisionalResolution = false; } + var cache = isInProvisionalResolution ? {} : this.assignableCache; + return this.sourceIsRelatableToTarget(source, target, true, cache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, context, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, context, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + if (source === target) { + return true; + } + + if (!(source && target)) { + return true; + } + + if (context.specializingToAny && (target.isTypeParameter() || source.isTypeParameter())) { + return true; + } + + if (context.specializingToObject) { + if (target.isTypeParameter()) { + target = this.cachedObjectInterfaceType(); + } + if (source.isTypeParameter()) { + target = this.cachedObjectInterfaceType(); + } + } + + var sourceSubstitution = source; + + if (source == this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { + if (!this.cachedStringInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedStringInterfaceType(), null, context); + } + sourceSubstitution = this.cachedStringInterfaceType(); + } else if (source == this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { + if (!this.cachedNumberInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedNumberInterfaceType(), null, context); + } + sourceSubstitution = this.cachedNumberInterfaceType(); + } else if (source == this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { + if (!this.cachedBooleanInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedBooleanInterfaceType(), null, context); + } + sourceSubstitution = this.cachedBooleanInterfaceType(); + } else if (TypeScript.PullHelpers.symbolIsEnum(source) && this.cachedNumberInterfaceType()) { + sourceSubstitution = this.cachedNumberInterfaceType(); + } else if (source.isTypeParameter()) { + sourceSubstitution = this.substituteUpperBoundForType(source); + } + + var comboId = source.getSymbolID().toString() + "#" + target.getSymbolID().toString(); + + if (comparisonCache[comboId] != undefined) { + return true; + } + + if (assignableTo) { + if (this.isAnyOrEquivalent(source) || this.isAnyOrEquivalent(target)) { + return true; + } + + if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && (target).isStringConstant()) { + return comparisonInfo && comparisonInfo.stringConstantVal && (comparisonInfo.stringConstantVal.nodeType === 5 /* StringLiteral */) && (TypeScript.stripQuotes((comparisonInfo.stringConstantVal).actualText) === TypeScript.stripQuotes(target.getName())); + } + } else { + if (this.isAnyOrEquivalent(target)) { + return true; + } + + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && (source).isStringConstant()) { + return true; + } + } + + if (source.isPrimitive() && (source).isStringConstant() && target.isPrimitive() && (target).isStringConstant()) { + return TypeScript.stripQuotes(source.getName()) === TypeScript.stripQuotes(target.getName()); + } + + if (source === this.semanticInfoChain.undefinedTypeSymbol) { + return true; + } + + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target != this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + return true; + } + + if (target == this.semanticInfoChain.voidTypeSymbol) { + if (source == this.semanticInfoChain.anyTypeSymbol || source == this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + return true; + } + + return false; + } else if (source == this.semanticInfoChain.voidTypeSymbol) { + if (target == this.semanticInfoChain.anyTypeSymbol) { + return true; + } + + return false; + } + + if (target === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(source)) { + return true; + } + + if (source === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(target)) { + return true; + } + + if (TypeScript.PullHelpers.symbolIsEnum(target) && TypeScript.PullHelpers.symbolIsEnum(source)) { + return this.symbolsShareDeclaration(target, source); + } + + if ((source.getKind() & 64 /* Enum */) || (target.getKind() & 64 /* Enum */)) { + return false; + } + + if (source.isArray() && target.isArray()) { + comparisonCache[comboId] = false; + var ret = this.sourceIsRelatableToTarget(source.getElementType(), target.getElementType(), assignableTo, comparisonCache, context, comparisonInfo); + if (ret) { + comparisonCache[comboId] = true; + } else { + comparisonCache[comboId] = undefined; + } + + return ret; + } else if (source.isArray() && target == this.cachedArrayInterfaceType()) { + return true; + } else if (target.isArray() && source == this.cachedArrayInterfaceType()) { + return true; + } + + if (source.isPrimitive() && target.isPrimitive()) { + return false; + } else if (source.isPrimitive() != target.isPrimitive()) { + if (target.isPrimitive()) { + return false; + } + } + + if (target.isTypeParameter()) { + if (source.isTypeParameter() && (source == sourceSubstitution)) { + var targetParentDeclaration = target.getDeclarations()[0].getParentDecl(); + var sourceParentDeclaration = source.getDeclarations()[0].getParentDecl(); + + if (targetParentDeclaration !== sourceParentDeclaration) { + return this.symbolsShareDeclaration(target, source); + } else { + return true; + } + } else { + if (context.isComparingSpecializedSignatures) { + target = this.substituteUpperBoundForType(target); + } else { + return false; + } + } + } + + comparisonCache[comboId] = false; + + if (sourceSubstitution.hasBase(target)) { + comparisonCache[comboId] = true; + return true; + } + + if (this.cachedObjectInterfaceType() && target === this.cachedObjectInterfaceType()) { + return true; + } + + if (this.cachedFunctionInterfaceType() && (sourceSubstitution.getCallSignatures().length || sourceSubstitution.getConstructSignatures().length) && target === this.cachedFunctionInterfaceType()) { + return true; + } + + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + comparisonCache[comboId] = true; + return true; + }; + + PullTypeResolver.prototype.sourceMembersAreRelatableToTargetMembers = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetProps = target.getAllMembers(TypeScript.PullElementKind.SomeValue, true); + + for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { + var targetProp = targetProps[itargetProp]; + var sourceProp = this.getMemberSymbol(targetProp.getName(), TypeScript.PullElementKind.SomeValue, source); + + if (!targetProp.isResolved()) { + this.resolveDeclaredSymbol(targetProp, null, context); + } + + var targetPropType = targetProp.getType(); + + if (!sourceProp) { + if (this.cachedObjectInterfaceType()) { + sourceProp = this.getMemberSymbol(targetProp.getName(), TypeScript.PullElementKind.SomeValue, this.cachedObjectInterfaceType()); + } + + if (!sourceProp) { + if (this.cachedFunctionInterfaceType() && (targetPropType.getCallSignatures().length || targetPropType.getConstructSignatures().length)) { + sourceProp = this.getMemberSymbol(targetProp.getName(), TypeScript.PullElementKind.SomeValue, this.cachedFunctionInterfaceType()); + } + + if (!sourceProp) { + if (!(targetProp.getIsOptional())) { + if (comparisonInfo) { + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(240 /* Type__0__is_missing_property__1__from_type__2_ */, [source.toString(), targetProp.getScopedNameEx().toString(), target.toString()])); + } + return false; + } + continue; + } + } + } + + if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, context, comparisonInfo)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, context, comparisonInfo) { + var targetPropIsPrivate = targetProp.hasFlag(2 /* Private */); + var sourcePropIsPrivate = sourceProp.hasFlag(2 /* Private */); + + if (targetPropIsPrivate != sourcePropIsPrivate) { + if (comparisonInfo) { + if (targetPropIsPrivate) { + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(244 /* Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_ */, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(), targetProp.getContainer().toString()])); + } else { + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(243 /* Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_ */, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(), targetProp.getContainer().toString()])); + } + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + } + return false; + } else if (sourcePropIsPrivate && targetPropIsPrivate) { + var targetDecl = targetProp.getDeclarations()[0]; + var sourceDecl = sourceProp.getDeclarations()[0]; + + if (!targetDecl.isEqual(sourceDecl)) { + if (comparisonInfo) { + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(245 /* Types__0__and__1__define_property__2__as_private */, [sourceProp.getContainer().toString(), targetProp.getContainer().toString(), targetProp.getScopedNameEx().toString()])); + } + return false; + } + } + + if (!sourceProp.isResolved()) { + this.resolveDeclaredSymbol(sourceProp, null, context); + } + + var sourcePropType = sourceProp.getType(); + var targetPropType = targetProp.getType(); + + if (targetPropType && sourcePropType && (comparisonCache[sourcePropType.getSymbolID().toString() + "#" + targetPropType.getSymbolID().toString()] != undefined)) { + return true; + } + + var comparisonInfoPropertyTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoPropertyTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + if (!this.sourceIsRelatableToTarget(sourcePropType, targetPropType, assignableTo, comparisonCache, context, comparisonInfoPropertyTypeCheck)) { + if (comparisonInfo) { + comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; + var message; + if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(242 /* Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3 */, [targetProp.getScopedNameEx().toString(), source.toString(), target.toString(), comparisonInfoPropertyTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(241 /* Types_of_property__0__of_types__1__and__2__are_incompatible */, [targetProp.getScopedNameEx().toString(), source.toString(), target.toString()]); + } + comparisonInfo.addMessage(message); + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetCallSigs = target.getCallSignatures(); + + if (targetCallSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + + var sourceCallSigs = source.getCallSignatures(); + if (!this.signatureGroupIsRelatableToTarget(sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, context, comparisonInfoSignatuesTypeCheck)) { + if (comparisonInfo) { + var message; + if (sourceCallSigs.length && targetCallSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(247 /* Call_signatures_of_types__0__and__1__are_incompatible__NL__2 */, [source.toString(), target.toString(), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(246 /* Call_signatures_of_types__0__and__1__are_incompatible */, [source.toString(), target.toString()]); + } + } else { + var hasSig = targetCallSigs.length ? target.toString() : source.toString(); + var lacksSig = !targetCallSigs.length ? target.toString() : source.toString(); + message = TypeScript.getDiagnosticMessage(248 /* Type__0__requires_a_call_signature__but_Type__1__lacks_one */, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreRelatableToTargetConstructSignatures = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetConstructSigs = target.getConstructSignatures(); + if (targetConstructSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + + var sourceConstructSigs = source.getConstructSignatures(); + if (!this.signatureGroupIsRelatableToTarget(sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, context, comparisonInfoSignatuesTypeCheck)) { + if (comparisonInfo) { + var message; + if (sourceConstructSigs.length && targetConstructSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(250 /* Construct_signatures_of_types__0__and__1__are_incompatible__NL__2 */, [source.toString(), target.toString(), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(249 /* Construct_signatures_of_types__0__and__1__are_incompatible */, [source.toString(), target.toString()]); + } + } else { + var hasSig = targetConstructSigs.length ? target.toString() : source.toString(); + var lacksSig = !targetConstructSigs.length ? target.toString() : source.toString(); + message = TypeScript.getDiagnosticMessage(251 /* Type__0__requires_a_construct_signature__but_Type__1__lacks_one */, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetIndexSigs = target.getIndexSignatures(); + + if (targetIndexSigs.length) { + var sourceIndexSigs = source.getIndexSignatures(); + + var targetIndex = !targetIndexSigs.length && this.cachedObjectInterfaceType() ? this.cachedObjectInterfaceType().getIndexSignatures() : targetIndexSigs; + var sourceIndex = !sourceIndexSigs.length && this.cachedObjectInterfaceType() ? this.cachedObjectInterfaceType().getIndexSignatures() : sourceIndexSigs; + + var sourceStringSig = null; + var sourceNumberSig = null; + + var targetStringSig = null; + var targetNumberSig = null; + + var params; + + for (var i = 0; i < targetIndex.length; i++) { + if (targetStringSig && targetNumberSig) { + break; + } + + params = targetIndex[i].getParameters(); + + if (params.length) { + if (!targetStringSig && params[0].getType() === this.semanticInfoChain.stringTypeSymbol) { + targetStringSig = targetIndex[i]; + continue; + } else if (!targetNumberSig && params[0].getType() === this.semanticInfoChain.numberTypeSymbol) { + targetNumberSig = targetIndex[i]; + continue; + } + } + } + + for (var i = 0; i < sourceIndex.length; i++) { + if (sourceStringSig && sourceNumberSig) { + break; + } + + params = sourceIndex[i].getParameters(); + + if (params.length) { + if (!sourceStringSig && params[0].getType() === this.semanticInfoChain.stringTypeSymbol) { + sourceStringSig = sourceIndex[i]; + continue; + } else if (!sourceNumberSig && params[0].getType() === this.semanticInfoChain.numberTypeSymbol) { + sourceNumberSig = sourceIndex[i]; + continue; + } + } + } + + var comparable = true; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + + if (targetStringSig) { + if (sourceStringSig) { + comparable = this.signatureIsAssignableToTarget(sourceStringSig, targetStringSig, context, comparisonInfoSignatuesTypeCheck); + } else { + comparable = false; + } + } + + if (comparable && targetNumberSig) { + if (sourceNumberSig) { + comparable = this.signatureIsAssignableToTarget(sourceNumberSig, targetNumberSig, context, comparisonInfoSignatuesTypeCheck); + } else if (sourceStringSig) { + comparable = this.sourceIsAssignableToTarget(sourceStringSig.getReturnType(), targetNumberSig.getReturnType(), context, comparisonInfoSignatuesTypeCheck); + } else { + comparable = false; + } + } + + if (!comparable) { + if (comparisonInfo) { + var message; + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(253 /* Index_signatures_of_types__0__and__1__are_incompatible__NL__2 */, [source.toString(), target.toString(), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(252 /* Index_signatures_of_types__0__and__1__are_incompatible */, [source.toString(), target.toString()]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + if (targetStringSig && !source.isNamedTypeSymbol() && source.hasMembers()) { + var targetReturnType = targetStringSig.getReturnType(); + var sourceMembers = source.getMembers(); + + for (var i = 0; i < sourceMembers.length; i++) { + if (!this.sourceIsRelatableToTarget(sourceMembers[i].getType(), targetReturnType, assignableTo, comparisonCache, context, comparisonInfo)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, context, comparisonInfo) { + if (sourceSG === targetSG) { + return true; + } + + if (!(sourceSG.length && targetSG.length)) { + return false; + } + + var mSig = null; + var nSig = null; + var foundMatch = false; + + for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { + mSig = targetSG[iMSig]; + + if (mSig.isStringConstantOverloadSignature()) { + continue; + } + + for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { + nSig = sourceSG[iNSig]; + + if (nSig.isStringConstantOverloadSignature()) { + continue; + } + + if (this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, context, comparisonInfo)) { + foundMatch = true; + break; + } + } + + if (foundMatch) { + foundMatch = false; + continue; + } + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, context, comparisonInfo) { + var sourceParameters = sourceSig.getParameters(); + var targetParameters = targetSig.getParameters(); + + if (!sourceParameters || !targetParameters) { + return false; + } + + var targetVarArgCount = targetSig.getNonOptionalParameterCount(); + var sourceVarArgCount = sourceSig.getNonOptionalParameterCount(); + + if (sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableParamList()) { + if (comparisonInfo) { + comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(254 /* Call_signature_expects__0__or_fewer_parameters */, [targetVarArgCount])); + } + return false; + } + + var sourceReturnType = sourceSig.getReturnType(); + var targetReturnType = targetSig.getReturnType(); + + var prevSpecializingToObject = context.specializingToObject; + context.specializingToObject = true; + + if (targetReturnType != this.semanticInfoChain.voidTypeSymbol) { + if (!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, context, comparisonInfo)) { + if (comparisonInfo) { + comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; + } + context.specializingToObject = prevSpecializingToObject; + return false; + } + } + + var len = (sourceVarArgCount < targetVarArgCount && (sourceSig.hasVariableParamList() || (sourceParameters.length > sourceVarArgCount))) ? targetVarArgCount : sourceVarArgCount; + var sourceParamType = null; + var targetParamType = null; + var sourceParamName = ""; + var targetParamName = ""; + + for (var iSource = 0, iTarget = 0; iSource < len; iSource++, iTarget++) { + if (iSource < sourceParameters.length && (!sourceSig.hasVariableParamList() || iSource < sourceVarArgCount)) { + sourceParamType = sourceParameters[iSource].getType(); + sourceParamName = sourceParameters[iSource].getName(); + } else if (iSource === sourceVarArgCount) { + sourceParamType = sourceParameters[iSource].getType(); + if (sourceParamType.isArray()) { + sourceParamType = sourceParamType.getElementType(); + } + sourceParamName = sourceParameters[iSource].getName(); + } + + if (iTarget < targetParameters.length && iTarget < targetVarArgCount) { + targetParamType = targetParameters[iTarget].getType(); + targetParamName = targetParameters[iTarget].getName(); + } else if (targetSig.hasVariableParamList() && iTarget === targetVarArgCount) { + targetParamType = targetParameters[iTarget].getType(); + + if (targetParamType.isArray()) { + targetParamType = targetParamType.getElementType(); + } + targetParamName = targetParameters[iTarget].getName(); + } + + if (sourceParamType && sourceParamType.isTypeParameter() && this.cachedObjectInterfaceType()) { + sourceParamType = this.cachedObjectInterfaceType(); + } + if (targetParamType && targetParamType.isTypeParameter() && this.cachedObjectInterfaceType()) { + targetParamType = this.cachedObjectInterfaceType(); + } + + if (!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, context, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, context, comparisonInfo))) { + if (comparisonInfo) { + comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; + } + context.specializingToObject = prevSpecializingToObject; + return false; + } + } + context.specializingToObject = prevSpecializingToObject; + return true; + }; + + PullTypeResolver.prototype.resolveOverloads = function (application, group, enclosingDecl, haveTypeArgumentsAtCallSite, context, diagnostics) { + var rd = this.resolutionDataCache.getResolutionData(); + var actuals = rd.actuals; + var exactCandidates = rd.exactCandidates; + var conversionCandidates = rd.conversionCandidates; + var candidate = null; + var hasOverloads = group.length > 1; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var args = null; + var target = null; + + if (application.nodeType === 36 /* InvocationExpression */ || application.nodeType === 37 /* ObjectCreationExpression */) { + var callEx = application; + + args = callEx.arguments; + target = this.getLastIdentifierInTarget(callEx); + + if (callEx.arguments) { + var len = callEx.arguments.members.length; + + for (var i = 0; i < len; i++) { + var argSym = this.resolveAST(callEx.arguments.members[i], false, enclosingDecl, context).symbol; + actuals[i] = argSym.getType(); + } + } + } else if (application.nodeType === 35 /* ElementAccessExpression */) { + var binExp = application; + target = binExp.operand1; + args = new TypeScript.ASTList(); + args.members[0] = binExp.operand2; + var argSym = this.resolveAST(args.members[0], false, enclosingDecl, context).symbol; + actuals[0] = argSym.getType(); + } + + var signature; + var returnType; + var candidateInfo; + + for (var j = 0, groupLen = group.length; j < groupLen; j++) { + signature = group[j]; + if ((hasOverloads && signature.isDefinition()) || (haveTypeArgumentsAtCallSite && !signature.isGeneric())) { + continue; + } + + returnType = signature.getReturnType(); + + this.getCandidateSignatures(signature, actuals, args, exactCandidates, conversionCandidates, enclosingDecl, context, comparisonInfo); + } + if (exactCandidates.length === 0) { + var applicableCandidates = this.getApplicableSignaturesFromCandidates(conversionCandidates, args, comparisonInfo, enclosingDecl, context); + if (applicableCandidates.length > 0) { + candidateInfo = this.findMostApplicableSignature(applicableCandidates, args, enclosingDecl, context); + + candidate = candidateInfo.sig; + } else { + if (comparisonInfo.message) { + diagnostics.push(context.postError(this.unitPath, target.minChar, target.getLength(), 151 /* Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0 */, [comparisonInfo.message])); + } else { + diagnostics.push(context.postError(this.unitPath, target.minChar, target.getLength(), 150 /* Supplied_parameters_do_not_match_any_signature_of_call_target */, null)); + } + } + } else { + if (exactCandidates.length > 1) { + var applicableSigs = []; + for (var i = 0; i < exactCandidates.length; i++) { + applicableSigs[i] = { signature: exactCandidates[i], hadProvisionalErrors: false }; + } + candidateInfo = this.findMostApplicableSignature(applicableSigs, args, enclosingDecl, context); + + candidate = candidateInfo.sig; + } else { + candidate = exactCandidates[0]; + } + } + + this.resolutionDataCache.returnResolutionData(rd); + return candidate; + }; + + PullTypeResolver.prototype.getLastIdentifierInTarget = function (callEx) { + return (callEx.target.nodeType === 32 /* MemberAccessExpression */) ? (callEx.target).operand2 : callEx.target; + }; + + PullTypeResolver.prototype.getCandidateSignatures = function (signature, actuals, args, exactCandidates, conversionCandidates, enclosingDecl, context, comparisonInfo) { + var parameters = signature.getParameters(); + var lowerBound = signature.getNonOptionalParameterCount(); + var upperBound = parameters.length; + var formalLen = lowerBound; + var acceptable = false; + + if ((actuals.length >= lowerBound) && (signature.hasVariableParamList() || actuals.length <= upperBound)) { + formalLen = (signature.hasVariableParamList() ? parameters.length : actuals.length); + acceptable = true; + } + + var repeatType = null; + + if (acceptable) { + if (signature.hasVariableParamList()) { + formalLen -= 1; + repeatType = parameters[formalLen].getType(); + repeatType = repeatType.getElementType(); + acceptable = actuals.length >= (formalLen < lowerBound ? formalLen : lowerBound); + } + var len = actuals.length; + + var exact = acceptable; + var convert = acceptable; + + var typeA; + var typeB; + + for (var i = 0; i < len; i++) { + if (i < formalLen) { + typeA = parameters[i].getType(); + } else { + typeA = repeatType; + } + + typeB = actuals[i]; + + if (typeA && !typeA.isResolved()) { + this.resolveDeclaredSymbol(typeA, enclosingDecl, context); + } + + if (typeB && !typeB.isResolved()) { + this.resolveDeclaredSymbol(typeB, enclosingDecl, context); + } + + if (!typeA || !typeB || !(this.typesAreIdentical(typeA, typeB, args.members[i]))) { + exact = false; + } + + comparisonInfo.stringConstantVal = args.members[i]; + + if (!this.sourceIsAssignableToTarget(typeB, typeA, context, comparisonInfo)) { + convert = false; + } + + comparisonInfo.stringConstantVal = null; + + if (!(exact || convert)) { + break; + } + } + if (exact) { + exactCandidates[exactCandidates.length] = signature; + } else if (convert && (exactCandidates.length === 0)) { + conversionCandidates[conversionCandidates.length] = signature; + } + } + }; + + PullTypeResolver.prototype.getApplicableSignaturesFromCandidates = function (candidateSignatures, args, comparisonInfo, enclosingDecl, context) { + var applicableSigs = []; + var memberType = null; + var miss = false; + var cxt = null; + var hadProvisionalErrors = false; + + var parameters; + var signature; + var argSym; + + for (var i = 0; i < candidateSignatures.length; i++) { + miss = false; + + signature = candidateSignatures[i]; + parameters = signature.getParameters(); + + for (var j = 0; j < args.members.length; j++) { + if (j >= parameters.length) { + continue; + } + + if (!parameters[j].isResolved()) { + this.resolveDeclaredSymbol(parameters[j], enclosingDecl, context); + } + + memberType = parameters[j].getType(); + + if (signature.hasVariableParamList() && (j >= signature.getNonOptionalParameterCount()) && memberType.isArray()) { + memberType = memberType.getElementType(); + } + + if (this.isAnyOrEquivalent(memberType)) { + continue; + } else if (args.members[j].nodeType === 12 /* FunctionDeclaration */) { + if (this.cachedFunctionInterfaceType() && memberType === this.cachedFunctionInterfaceType()) { + continue; + } + + argSym = this.resolveFunctionExpression(args.members[j], false, enclosingDecl, context); + + if (!this.canApplyContextualTypeToFunction(memberType, args.members[j], true)) { + if (this.canApplyContextualTypeToFunction(memberType, args.members[j], false)) { + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + break; + } + } else { + break; + } + } else { + argSym.invalidate(); + context.pushContextualType(memberType, true, null); + + argSym = this.resolveFunctionExpression(args.members[j], true, enclosingDecl, context); + + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + if (comparisonInfo) { + comparisonInfo.setMessage(TypeScript.getDiagnosticMessage(255 /* Could_not_apply_type__0__to_argument__1__which_is_of_type__2_ */, [memberType.toString(), (j + 1), argSym.getTypeName()])); + } + miss = true; + } + argSym.invalidate(); + cxt = context.popContextualType(); + hadProvisionalErrors = cxt.hadProvisionalErrors(); + + if (miss) { + break; + } + } + } else if (args.members[j].nodeType === 22 /* ObjectLiteralExpression */) { + if (this.cachedObjectInterfaceType() && memberType === this.cachedObjectInterfaceType()) { + continue; + } + + context.pushContextualType(memberType, true, null); + argSym = this.resolveObjectLiteralExpression(args.members[j], true, enclosingDecl, context).symbol; + + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + if (comparisonInfo) { + comparisonInfo.setMessage(TypeScript.getDiagnosticMessage(255 /* Could_not_apply_type__0__to_argument__1__which_is_of_type__2_ */, [memberType.toString(), (j + 1), argSym.getTypeName()])); + } + + miss = true; + } + + argSym.invalidate(); + cxt = context.popContextualType(); + hadProvisionalErrors = cxt.hadProvisionalErrors(); + + if (miss) { + break; + } + } else if (args.members[j].nodeType === 21 /* ArrayLiteralExpression */) { + if (memberType === this.cachedArrayInterfaceType()) { + continue; + } + + context.pushContextualType(memberType, true, null); + var argSym = this.resolveArrayLiteralExpression(args.members[j], true, enclosingDecl, context).symbol; + + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + if (comparisonInfo) { + comparisonInfo.setMessage(TypeScript.getDiagnosticMessage(255 /* Could_not_apply_type__0__to_argument__1__which_is_of_type__2_ */, [memberType.toString(), (j + 1), argSym.getTypeName()])); + } + break; + } + + argSym.invalidate(); + cxt = context.popContextualType(); + + hadProvisionalErrors = cxt.hadProvisionalErrors(); + + if (miss) { + break; + } + } + } + + if (j === args.members.length) { + applicableSigs[applicableSigs.length] = { signature: candidateSignatures[i], hadProvisionalErrors: hadProvisionalErrors }; + } + + hadProvisionalErrors = false; + } + + return applicableSigs; + }; + + PullTypeResolver.prototype.findMostApplicableSignature = function (signatures, args, enclosingDecl, context) { + if (signatures.length === 1) { + return { sig: signatures[0].signature, ambiguous: false }; + } + + var best = signatures[0]; + var Q = null; + + var AType = null; + var PType = null; + var QType = null; + + var ambiguous = false; + + var bestParams; + var qParams; + + for (var qSig = 1; qSig < signatures.length; qSig++) { + Q = signatures[qSig]; + + for (var i = 0; args && i < args.members.length; i++) { + var argSym = this.resolveAST(args.members[i], false, enclosingDecl, context).symbol; + + AType = argSym.getType(); + + argSym.invalidate(); + + bestParams = best.signature.getParameters(); + qParams = Q.signature.getParameters(); + + PType = i < bestParams.length ? bestParams[i].getType() : bestParams[bestParams.length - 1].getType().getElementType(); + QType = i < qParams.length ? qParams[i].getType() : qParams[qParams.length - 1].getType().getElementType(); + + if (this.typesAreIdentical(PType, QType) && !(QType.isPrimitive() && (QType).isStringConstant())) { + continue; + } else if (PType.isPrimitive() && (PType).isStringConstant() && args.members[i].nodeType === 5 /* StringLiteral */ && TypeScript.stripQuotes((args.members[i]).actualText) === TypeScript.stripQuotes((PType).getName())) { + break; + } else if (QType.isPrimitive() && (QType).isStringConstant() && args.members[i].nodeType === 5 /* StringLiteral */ && TypeScript.stripQuotes((args.members[i]).actualText) === TypeScript.stripQuotes((QType).getName())) { + best = Q; + } else if (this.typesAreIdentical(AType, PType)) { + break; + } else if (this.typesAreIdentical(AType, QType)) { + best = Q; + break; + } else if (this.sourceIsSubtypeOfTarget(PType, QType, context)) { + break; + } else if (this.sourceIsSubtypeOfTarget(QType, PType, context)) { + best = Q; + break; + } else if (Q.hadProvisionalErrors) { + break; + } else if (best.hadProvisionalErrors) { + best = Q; + break; + } + } + + if (!args || i === args.members.length) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return index ? Q.signature.getReturnType() : best.signature.getReturnType(); + } + }; + var bct = this.findBestCommonType(best.signature.getReturnType(), null, collection, context); + ambiguous = !bct; + } else { + ambiguous = false; + } + } + + return { sig: best.signature, ambiguous: ambiguous }; + }; + + PullTypeResolver.prototype.canApplyContextualTypeToFunction = function (candidateType, funcDecl, beStringent) { + if (funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation) { + return false; + } + + beStringent = beStringent || (this.cachedFunctionInterfaceType() === candidateType); + + if (!beStringent) { + return true; + } + var functionSymbol = this.getDeclForAST(funcDecl).getSymbol(); + var signature = functionSymbol.getType().getCallSignatures()[0]; + var parameters = signature.getParameters(); + var paramLen = parameters.length; + + for (var i = 0; i < paramLen; i++) { + var param = parameters[i]; + var argDecl = this.getASTForDecl(param.getDeclarations()[0]); + + if (beStringent && argDecl.typeExpr) { + return false; + } + } + + if (candidateType.getConstructSignatures().length && candidateType.getCallSignatures().length) { + return false; + } + + var candidateSigs = candidateType.getConstructSignatures().length ? candidateType.getConstructSignatures() : candidateType.getCallSignatures(); + + if (!candidateSigs || candidateSigs.length > 1) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (signature, args, comparisonInfo, enclosingDecl, context) { + var cxt = null; + var hadProvisionalErrors = false; + + var parameters = signature.getParameters(); + var typeParameters = signature.getTypeParameters(); + var argContext = new TypeScript.ArgumentInferenceContext(); + + var parameterType = null; + + for (var i = 0; i < typeParameters.length; i++) { + argContext.addInferenceRoot(typeParameters[i]); + } + + var substitutions; + var inferenceCandidates; + var inferenceCandidate; + + for (var i = 0; i < args.members.length; i++) { + if (i >= parameters.length) { + break; + } + + parameterType = parameters[i].getType(); + + if (signature.hasVariableParamList() && (i >= signature.getNonOptionalParameterCount() - 1) && parameterType.isArray()) { + parameterType = parameterType.getElementType(); + } + + inferenceCandidates = argContext.getInferenceCandidates(); + substitutions = {}; + + if (inferenceCandidates.length) { + for (var j = 0; j < inferenceCandidates.length; j++) { + argContext.resetRelationshipCache(); + + inferenceCandidate = inferenceCandidates[j]; + + substitutions = inferenceCandidates[j]; + + context.pushContextualType(parameterType, true, substitutions); + + var argSym = this.resolveAST(args.members[i], true, enclosingDecl, context).symbol; + + this.relateTypeToTypeParameters(argSym.getType(), parameterType, false, argContext, enclosingDecl, context); + + cxt = context.popContextualType(); + + argSym.invalidate(); + + hadProvisionalErrors = cxt.hadProvisionalErrors(); + } + } else { + context.pushContextualType(parameterType, true, {}); + var argSym = this.resolveAST(args.members[i], true, enclosingDecl, context).symbol; + + this.relateTypeToTypeParameters(argSym.getType(), parameterType, false, argContext, enclosingDecl, context); + + cxt = context.popContextualType(); + + argSym.invalidate(); + + hadProvisionalErrors = cxt.hadProvisionalErrors(); + } + } + + hadProvisionalErrors = false; + + var inferenceResults = argContext.inferArgumentTypes(this, context); + + if (inferenceResults.unfit) { + return null; + } + + var resultTypes = []; + + for (var i = 0; i < typeParameters.length; i++) { + for (var j = 0; j < inferenceResults.results.length; j++) { + if (inferenceResults.results[j].param == typeParameters[i]) { + resultTypes[resultTypes.length] = inferenceResults.results[j].type; + break; + } + } + } + + if (!args.members.length && !resultTypes.length && typeParameters.length) { + for (var i = 0; i < typeParameters.length; i++) { + resultTypes[resultTypes.length] = this.semanticInfoChain.anyTypeSymbol; + } + } else if (resultTypes.length && resultTypes.length < typeParameters.length) { + for (var i = resultTypes.length; i < typeParameters.length; i++) { + resultTypes[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + + return resultTypes; + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, enclosingDecl, context) { + if (!expressionType || !parameterType) { + return; + } + + if (expressionType.isError()) { + expressionType = this.semanticInfoChain.anyTypeSymbol; + } + + if (parameterType === expressionType) { + return; + } + + if (parameterType.isTypeParameter()) { + if (expressionType.isGeneric() && !expressionType.isFixed()) { + expressionType = this.specializeTypeToAny(expressionType, enclosingDecl, context); + } + argContext.addCandidateForInference(parameterType, expressionType, shouldFix); + return; + } + var parameterDeclarations = parameterType.getDeclarations(); + var expressionDeclarations = expressionType.getDeclarations(); + if (!parameterType.isArray() && parameterDeclarations.length && expressionDeclarations.length && (parameterDeclarations[0].isEqual(expressionDeclarations[0]) || (expressionType.isGeneric() && parameterType.isGeneric() && this.sourceIsSubtypeOfTarget(expressionType, parameterType, context, null))) && expressionType.isGeneric()) { + var typeParameters = parameterType.getIsSpecialized() ? parameterType.getTypeArguments() : parameterType.getTypeParameters(); + var typeArguments = expressionType.getTypeArguments(); + + if (!typeArguments) { + typeParameters = parameterType.getTypeArguments(); + typeArguments = expressionType.getIsSpecialized() ? expressionType.getTypeArguments() : expressionType.getTypeParameters(); + } + + if (typeParameters && typeArguments && typeParameters.length === typeArguments.length) { + for (var i = 0; i < typeParameters.length; i++) { + if (typeArguments[i] != typeParameters[i]) { + this.relateTypeToTypeParameters(typeArguments[i], typeParameters[i], true, argContext, enclosingDecl, context); + } + } + } + } + + var prevSpecializingToAny = context.specializingToAny; + context.specializingToAny = true; + + if (!this.sourceIsAssignableToTarget(expressionType, parameterType, context)) { + context.specializingToAny = prevSpecializingToAny; + return; + } + context.specializingToAny = prevSpecializingToAny; + + if (expressionType.isArray() && parameterType.isArray()) { + this.relateArrayTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, enclosingDecl, context); + + return; + } + + this.relateObjectTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, enclosingDecl, context); + }; + + PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, enclosingDecl, context) { + var expressionParams = expressionSignature.getParameters(); + var expressionReturnType = expressionSignature.getReturnType(); + + var parameterParams = parameterSignature.getParameters(); + var parameterReturnType = parameterSignature.getReturnType(); + + var len = parameterParams.length < expressionParams.length ? parameterParams.length : expressionParams.length; + + for (var i = 0; i < len; i++) { + this.relateTypeToTypeParameters(expressionParams[i].getType(), parameterParams[i].getType(), true, argContext, enclosingDecl, context); + } + + this.relateTypeToTypeParameters(expressionReturnType, parameterReturnType, false, argContext, enclosingDecl, context); + }; + + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, shouldFix, argContext, enclosingDecl, context) { + var parameterTypeMembers = parameterType.getMembers(); + var parameterSignatures; + var parameterSignature; + + var objectMember; + var objectSignatures; + + if (argContext.alreadyRelatingTypes(objectType, parameterType)) { + return; + } + + var objectTypeArguments = objectType.getTypeArguments(); + var parameterTypeParameters = parameterType.getTypeParameters(); + + if (objectTypeArguments && (objectTypeArguments.length === parameterTypeParameters.length)) { + for (var i = 0; i < objectTypeArguments.length; i++) { + argContext.addCandidateForInference(parameterTypeParameters[i], objectTypeArguments[i], shouldFix); + } + } + + for (var i = 0; i < parameterTypeMembers.length; i++) { + objectMember = this.getMemberSymbol(parameterTypeMembers[i].getName(), TypeScript.PullElementKind.SomeValue, objectType); + + if (objectMember) { + this.relateTypeToTypeParameters(objectMember.getType(), parameterTypeMembers[i].getType(), shouldFix, argContext, enclosingDecl, context); + } + } + + parameterSignatures = parameterType.getCallSignatures(); + objectSignatures = objectType.getCallSignatures(); + + for (var i = 0; i < parameterSignatures.length; i++) { + parameterSignature = parameterSignatures[i]; + + for (var j = 0; j < objectSignatures.length; j++) { + this.relateFunctionSignatureToTypeParameters(objectSignatures[j], parameterSignature, argContext, enclosingDecl, context); + } + } + + parameterSignatures = parameterType.getConstructSignatures(); + objectSignatures = objectType.getConstructSignatures(); + + for (var i = 0; i < parameterSignatures.length; i++) { + parameterSignature = parameterSignatures[i]; + + for (var j = 0; j < objectSignatures.length; j++) { + this.relateFunctionSignatureToTypeParameters(objectSignatures[j], parameterSignature, argContext, enclosingDecl, context); + } + } + + parameterSignatures = parameterType.getIndexSignatures(); + objectSignatures = objectType.getIndexSignatures(); + + for (var i = 0; i < parameterSignatures.length; i++) { + parameterSignature = parameterSignatures[i]; + + for (var j = 0; j < objectSignatures.length; j++) { + this.relateFunctionSignatureToTypeParameters(objectSignatures[j], parameterSignature, argContext, enclosingDecl, context); + } + } + }; + + PullTypeResolver.prototype.relateArrayTypeToTypeParameters = function (argArrayType, parameterArrayType, shouldFix, argContext, enclosingDecl, context) { + var argElement = argArrayType.getElementType(); + var paramElement = parameterArrayType.getElementType(); + + this.relateTypeToTypeParameters(argElement, paramElement, shouldFix, argContext, enclosingDecl, context); + }; + + PullTypeResolver.prototype.specializeTypeToAny = function (typeToSpecialize, enclosingDecl, context) { + var prevSpecialize = context.specializingToAny; + + context.specializingToAny = true; + + var rootType = TypeScript.getRootType(typeToSpecialize); + + var type = TypeScript.specializeType(rootType, [], this, enclosingDecl, context); + + context.specializingToAny = prevSpecialize; + + return type; + }; + + PullTypeResolver.prototype.specializeSignatureToAny = function (signatureToSpecialize, enclosingDecl, context) { + var typeParameters = signatureToSpecialize.getTypeParameters(); + var typeReplacementMap = {}; + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[i] = this.semanticInfoChain.anyTypeSymbol; + typeReplacementMap[typeParameters[i].getSymbolID().toString()] = typeArguments[i]; + } + if (!typeArguments.length) { + typeArguments[0] = this.semanticInfoChain.anyTypeSymbol; + } + + var prevSpecialize = context.specializingToAny; + + context.specializingToAny = true; + + var sig = TypeScript.specializeSignature(signatureToSpecialize, false, typeReplacementMap, typeArguments, this, enclosingDecl, context); + context.specializingToAny = prevSpecialize; + + return sig; + }; + return PullTypeResolver; + })(); + TypeScript.PullTypeResolver = PullTypeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullTypeResolver2 = (function () { + function PullTypeResolver2() { + } + return PullTypeResolver2; + })(); + TypeScript.PullTypeResolver2 = PullTypeResolver2; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TypeComparisonInfo = (function () { + function TypeComparisonInfo(sourceComparisonInfo) { + this.onlyCaptureFirstError = false; + this.flags = 0 /* SuccessfulComparison */; + this.message = ""; + this.stringConstantVal = null; + this.indent = 1; + if (sourceComparisonInfo) { + this.flags = sourceComparisonInfo.flags; + this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; + this.stringConstantVal = sourceComparisonInfo.stringConstantVal; + this.indent = sourceComparisonInfo.indent + 1; + } + } + TypeComparisonInfo.prototype.addMessage = function (message) { + if (!this.onlyCaptureFirstError && this.message) { + this.message = TypeScript.getDiagnosticMessage(2 /* _0__NL__1_TB__2 */, [this.message, this.indent, message]); + } else { + this.message = TypeScript.getDiagnosticMessage(3 /* _0_TB__1 */, [this.indent, message]); + } + }; + + TypeComparisonInfo.prototype.setMessage = function (message) { + this.message = TypeScript.getDiagnosticMessage(3 /* _0_TB__1 */, [this.indent, message]); + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + + var PullTypeCheckContext = (function () { + function PullTypeCheckContext(compiler, script, scriptName) { + this.compiler = compiler; + this.script = script; + this.scriptName = scriptName; + this.enclosingDeclStack = []; + this.enclosingDeclReturnStack = []; + this.semanticInfo = null; + this.inSuperConstructorCall = false; + this.inSuperConstructorTarget = false; + this.seenSuperConstructorCall = false; + this.inConstructorArguments = false; + this.inImportDeclaration = false; + } + PullTypeCheckContext.prototype.pushEnclosingDecl = function (decl) { + this.enclosingDeclStack[this.enclosingDeclStack.length] = decl; + this.enclosingDeclReturnStack[this.enclosingDeclReturnStack.length] = false; + }; + + PullTypeCheckContext.prototype.popEnclosingDecl = function () { + this.enclosingDeclStack.length--; + this.enclosingDeclReturnStack.length--; + }; + + PullTypeCheckContext.prototype.getEnclosingDecl = function (kind) { + if (typeof kind === "undefined") { kind = TypeScript.PullElementKind.All; } + for (var i = this.enclosingDeclStack.length - 1; i >= 0; i--) { + var decl = this.enclosingDeclStack[i]; + if (decl.getKind() & kind) { + return decl; + } + } + + return null; + }; + + PullTypeCheckContext.prototype.getEnclosingNonLambdaDecl = function () { + for (var i = this.enclosingDeclStack.length - 1; i >= 0; i--) { + var decl = this.enclosingDeclStack[i]; + if (!(decl.getKind() === 131072 /* FunctionExpression */ && (decl.getFlags() & 8192 /* FatArrow */))) { + return decl; + } + } + + return null; + }; + + PullTypeCheckContext.prototype.getEnclosingClassDecl = function () { + return this.getEnclosingDecl(8 /* Class */); + }; + + PullTypeCheckContext.prototype.getEnclosingDeclHasReturn = function () { + return this.enclosingDeclReturnStack[this.enclosingDeclReturnStack.length - 1]; + }; + + PullTypeCheckContext.prototype.setEnclosingDeclHasReturn = function () { + return this.enclosingDeclReturnStack[this.enclosingDeclReturnStack.length - 1] = true; + }; + return PullTypeCheckContext; + })(); + TypeScript.PullTypeCheckContext = PullTypeCheckContext; + + var PullTypeChecker = (function () { + function PullTypeChecker(compilationSettings, semanticInfoChain) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this.resolver = null; + this.context = new TypeScript.PullTypeResolutionContext(); + } + PullTypeChecker.prototype.setUnit = function (unitPath) { + this.resolver = new TypeScript.PullTypeResolver(this.compilationSettings, this.semanticInfoChain, unitPath); + }; + + PullTypeChecker.prototype.getScriptDecl = function (fileName) { + return this.semanticInfoChain.getUnit(fileName).getTopLevelDecls()[0]; + }; + + PullTypeChecker.prototype.checkForResolutionError = function (typeSymbol, decl) { + if (typeSymbol && typeSymbol.isError()) { + decl.addDiagnostic((typeSymbol).getDiagnostic()); + } + }; + + PullTypeChecker.prototype.postError = function (offset, length, fileName, diagnosticCode, arguments, enclosingDecl) { + enclosingDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(fileName, offset, length, diagnosticCode, arguments)); + }; + + PullTypeChecker.prototype.validateVariableDeclarationGroups = function (enclosingDecl, typeCheckContext) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + var decl; + var firstSymbol; + var symbol; + var boundDeclAST; + + for (var i = 0; i < declGroups.length; i++) { + for (var j = 0; j < declGroups[i].length; j++) { + decl = declGroups[i][j]; + symbol = decl.getSymbol(); + boundDeclAST = this.semanticInfoChain.getASTForDecl(decl); + this.resolver.resolveAST(boundDeclAST, false, enclosingDecl, this.context); + if (!j) { + firstSymbol = decl.getSymbol(); + + if (this.resolver.isAnyOrEquivalent(this.resolver.widenType(firstSymbol.getType()))) { + return; + } + continue; + } + + if (!this.resolver.typesAreIdentical(symbol.getType(), firstSymbol.getType())) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 199 /* Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_ */, [symbol.getDisplayName(), firstSymbol.getType().toString(), symbol.getType().toString()], enclosingDecl); + } + } + } + }; + + PullTypeChecker.prototype.typeCheckAST = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + if (!ast) { + return null; + } + + if (ast.typeCheckPhase >= PullTypeChecker.globalPullTypeCheckPhase) { + return null; + } else { + ast.typeCheckPhase = PullTypeChecker.globalPullTypeCheckPhase; + } + + switch (ast.nodeType) { + case 1 /* List */: + return this.typeCheckList(ast, typeCheckContext); + + case 17 /* VariableDeclarator */: + case 19 /* Parameter */: + return this.typeCheckBoundDecl(ast, typeCheckContext); + + case 12 /* FunctionDeclaration */: + return this.typeCheckFunction(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 13 /* ClassDeclaration */: + return this.typeCheckClass(ast, typeCheckContext); + + case 14 /* InterfaceDeclaration */: + return this.typeCheckInterface(ast, typeCheckContext); + + case 15 /* ModuleDeclaration */: + return this.typeCheckModule(ast, typeCheckContext); + + case 9 /* TypeParameter */: + return this.typeCheckTypeParameter(ast, typeCheckContext); + + case 16 /* ImportDeclaration */: + return this.typeCheckImportDeclaration(ast, typeCheckContext); + + case 38 /* AssignmentExpression */: + return this.typeCheckAssignment(ast, typeCheckContext); + + case 10 /* GenericType */: + return this.typeCheckGenericType(ast, typeCheckContext); + + case 22 /* ObjectLiteralExpression */: + return this.typeCheckObjectLiteral(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 21 /* ArrayLiteralExpression */: + return this.typeCheckArrayLiteral(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 29 /* ThisExpression */: + return this.typeCheckThisExpression(ast, typeCheckContext); + + case 30 /* SuperExpression */: + return this.typeCheckSuperExpression(ast, typeCheckContext); + + case 36 /* InvocationExpression */: + return this.typeCheckCallExpression(ast, typeCheckContext); + + case 37 /* ObjectCreationExpression */: + return this.typeCheckObjectCreationExpression(ast, typeCheckContext); + + case 78 /* CastExpression */: + return this.typeCheckTypeAssertion(ast, typeCheckContext); + + case 11 /* TypeRef */: + return this.typeCheckTypeReference(ast, typeCheckContext); + + case 87 /* ExportAssignment */: + return this.typeCheckExportAssignment(ast, typeCheckContext); + + case 57 /* NotEqualsWithTypeConversionExpression */: + case 56 /* EqualsWithTypeConversionExpression */: + case 58 /* EqualsExpression */: + case 59 /* NotEqualsExpression */: + case 60 /* LessThanExpression */: + case 61 /* LessThanOrEqualExpression */: + case 63 /* GreaterThanOrEqualExpression */: + case 62 /* GreaterThanExpression */: + return this.typeCheckLogicalOperation(ast, typeCheckContext); + + case 25 /* CommaExpression */: + return this.typeCheckCommaExpression(ast, typeCheckContext); + + case 64 /* AddExpression */: + case 39 /* AddAssignmentExpression */: + return this.typeCheckBinaryAdditionOperation(ast, typeCheckContext); + + case 65 /* SubtractExpression */: + case 66 /* MultiplyExpression */: + case 67 /* DivideExpression */: + case 68 /* ModuloExpression */: + case 53 /* BitwiseOrExpression */: + case 55 /* BitwiseAndExpression */: + case 69 /* LeftShiftExpression */: + case 70 /* SignedRightShiftExpression */: + case 71 /* UnsignedRightShiftExpression */: + case 54 /* BitwiseExclusiveOrExpression */: + case 45 /* ExclusiveOrAssignmentExpression */: + case 47 /* LeftShiftAssignmentExpression */: + case 48 /* SignedRightShiftAssignmentExpression */: + case 49 /* UnsignedRightShiftAssignmentExpression */: + case 40 /* SubtractAssignmentExpression */: + case 42 /* MultiplyAssignmentExpression */: + case 41 /* DivideAssignmentExpression */: + case 43 /* ModuloAssignmentExpression */: + case 46 /* OrAssignmentExpression */: + case 44 /* AndAssignmentExpression */: + return this.typeCheckBinaryArithmeticOperation(ast, typeCheckContext); + + case 26 /* PlusExpression */: + case 27 /* NegateExpression */: + case 72 /* BitwiseNotExpression */: + case 76 /* PostIncrementExpression */: + case 74 /* PreIncrementExpression */: + case 77 /* PostDecrementExpression */: + case 75 /* PreDecrementExpression */: + return this.typeCheckUnaryArithmeticOperation(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 35 /* ElementAccessExpression */: + return this.typeCheckElementAccessExpression(ast, typeCheckContext); + + case 73 /* LogicalNotExpression */: + return this.typeCheckLogicalNotExpression(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 51 /* LogicalOrExpression */: + case 52 /* LogicalAndExpression */: + return this.typeCheckLogicalAndOrExpression(ast, typeCheckContext); + + case 34 /* TypeOfExpression */: + return this.typeCheckTypeOf(ast, typeCheckContext); + + case 50 /* ConditionalExpression */: + return this.typeCheckConditionalExpression(ast, typeCheckContext); + + case 24 /* VoidExpression */: + return this.typeCheckVoidExpression(ast, typeCheckContext); + + case 95 /* ThrowStatement */: + return this.typeCheckThrowStatement(ast, typeCheckContext); + + case 28 /* DeleteExpression */: + return this.typeCheckDeleteExpression(ast, typeCheckContext); + + case 6 /* RegularExpressionLiteral */: + return this.typeCheckRegExpExpression(ast, typeCheckContext); + + case 31 /* InExpression */: + return this.typeCheckInExpression(ast, typeCheckContext); + + case 33 /* InstanceOfExpression */: + return this.typeCheckInstanceOfExpression(ast, typeCheckContext); + + case 79 /* ParenthesizedExpression */: + return this.typeCheckParenthesizedExpression(ast, typeCheckContext); + + case 90 /* ForStatement */: + return this.typeCheckForStatement(ast, typeCheckContext); + + case 89 /* ForInStatement */: + return this.typeCheckForInStatement(ast, typeCheckContext); + + case 98 /* WhileStatement */: + return this.typeCheckWhileStatement(ast, typeCheckContext); + + case 85 /* DoStatement */: + return this.typeCheckDoStatement(ast, typeCheckContext); + + case 91 /* IfStatement */: + return this.typeCheckIfStatement(ast, typeCheckContext); + + case 81 /* Block */: + return this.typeCheckBlock(ast, typeCheckContext); + + case 18 /* VariableDeclaration */: + return this.typeCheckVariableDeclaration(ast, typeCheckContext); + + case 97 /* VariableStatement */: + return this.typeCheckVariableStatement(ast, typeCheckContext); + + case 99 /* WithStatement */: + return this.typeCheckWithStatement(ast, typeCheckContext); + + case 96 /* TryStatement */: + return this.typeCheckTryStatement(ast, typeCheckContext); + + case 101 /* CatchClause */: + return this.typeCheckCatchClause(ast, typeCheckContext); + + case 93 /* ReturnStatement */: + return this.typeCheckReturnStatement(ast, typeCheckContext); + + case 20 /* Name */: + return this.typeCheckNameExpression(ast, typeCheckContext); + + case 32 /* MemberAccessExpression */: + return this.typeCheckMemberAccessExpression(ast, typeCheckContext); + + case 94 /* SwitchStatement */: + return this.typeCheckSwitchStatement(ast, typeCheckContext); + + case 88 /* ExpressionStatement */: + return this.typeCheckExpressionStatement(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 100 /* CaseClause */: + return this.typeCheckCaseClause(ast, typeCheckContext); + + case 92 /* LabeledStatement */: + return this.typeCheckLabeledStatement(ast, typeCheckContext); + + case 7 /* NumericLiteral */: + return this.semanticInfoChain.numberTypeSymbol; + + case 5 /* StringLiteral */: + return this.semanticInfoChain.stringTypeSymbol; + + case 8 /* NullLiteral */: + return this.semanticInfoChain.nullTypeSymbol; + + case 3 /* TrueLiteral */: + case 4 /* FalseLiteral */: + return this.semanticInfoChain.booleanTypeSymbol; + + case 9 /* TypeParameter */: + return this.typeCheckTypeParameter(ast, typeCheckContext); + + default: + break; + } + + return null; + }; + + PullTypeChecker.prototype.typeCheckScript = function (script, scriptName, compiler) { + var unit = this.semanticInfoChain.getUnit(scriptName); + + if (unit.getTypeChecked()) { + return; + } + + var typeCheckContext = new PullTypeCheckContext(compiler, script, scriptName); + + this.setUnit(scriptName); + + typeCheckContext.semanticInfo = typeCheckContext.compiler.semanticInfoChain.getUnit(typeCheckContext.scriptName); + var scriptDecl = typeCheckContext.semanticInfo.getTopLevelDecls()[0]; + typeCheckContext.pushEnclosingDecl(scriptDecl); + + PullTypeChecker.globalPullTypeCheckPhase++; + + this.typeCheckAST(script.moduleElements, typeCheckContext, false); + + this.validateVariableDeclarationGroups(scriptDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + unit.setTypeChecked(); + }; + + PullTypeChecker.prototype.typeCheckList = function (list, typeCheckContext) { + if (!list) { + return null; + } + + for (var i = 0; i < list.members.length; i++) { + this.typeCheckAST(list.members[i], typeCheckContext, false); + } + }; + + PullTypeChecker.prototype.reportDiagnostics = function (symbolAndDiagnostics, enclosingDecl) { + if (symbolAndDiagnostics && symbolAndDiagnostics.diagnostics) { + for (var i = 0, n = symbolAndDiagnostics.diagnostics.length; i < n; i++) { + this.context.postDiagnostic(symbolAndDiagnostics.diagnostics[i], enclosingDecl, true); + } + } + }; + + PullTypeChecker.prototype.resolveSymbolAndReportDiagnostics = function (ast, inContextuallyTypedAssignment, enclosingDecl) { + var symbolAndDiagnostics = this.resolver.resolveAST(ast, inContextuallyTypedAssignment, enclosingDecl, this.context); + + this.reportDiagnostics(symbolAndDiagnostics, enclosingDecl); + return symbolAndDiagnostics && symbolAndDiagnostics.symbol; + }; + + PullTypeChecker.prototype.typeCheckBoundDecl = function (ast, typeCheckContext) { + var _this = this; + var boundDeclAST = ast; + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var typeExprSymbol = null; + + if (boundDeclAST.typeExpr) { + typeExprSymbol = this.typeCheckAST(boundDeclAST.typeExpr, typeCheckContext, false); + + if (typeExprSymbol.isNamedTypeSymbol() && typeExprSymbol.isGeneric() && !typeExprSymbol.isTypeParameter() && !this.resolver.isArrayOrEquivalent(typeExprSymbol) && typeExprSymbol.isResolved() && typeExprSymbol.getTypeParameters().length && typeExprSymbol.getTypeArguments() == null && !typeExprSymbol.getIsSpecialized() && this.resolver.isTypeRefWithoutTypeArgs(boundDeclAST.typeExpr)) { + this.postError(boundDeclAST.typeExpr.minChar, boundDeclAST.typeExpr.getLength(), typeCheckContext.scriptName, 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl); + typeExprSymbol = this.resolver.specializeTypeToAny(typeExprSymbol, enclosingDecl, this.context); + } + } + + if (boundDeclAST.init) { + if (typeExprSymbol) { + this.context.pushContextualType(typeExprSymbol, this.context.inProvisionalResolution(), null); + } + + var initTypeSymbol = this.typeCheckAST(boundDeclAST.init, typeCheckContext, !!typeExprSymbol); + + if (typeExprSymbol) { + this.context.popContextualType(); + } + + if (typeExprSymbol && typeExprSymbol.isContainer()) { + var exportedTypeSymbol = (typeExprSymbol).getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceTypeSymbol = (typeExprSymbol.getType()).getInstanceSymbol().getType(); + + if (!instanceTypeSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceTypeSymbol)) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 190 /* Tried_to_set_variable_type_to_module_type__0__ */, [typeExprSymbol.toString()], enclosingDecl); + typeExprSymbol = null; + } else { + typeExprSymbol = instanceTypeSymbol.getType(); + } + } + } + + if (initTypeSymbol && initTypeSymbol.isContainer()) { + instanceTypeSymbol = (initTypeSymbol.getType()).getInstanceSymbol().getType(); + + if (!instanceTypeSymbol) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 191 /* Tried_to_set_variable_type_to_uninitialized_module_type__0__ */, [initTypeSymbol.toString()], enclosingDecl); + initTypeSymbol = null; + } else { + initTypeSymbol = instanceTypeSymbol.getType(); + } + } + + if (initTypeSymbol && typeExprSymbol) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.resolver.sourceIsAssignableToTarget(initTypeSymbol, typeExprSymbol, this.context, comparisonInfo); + + if (!isAssignable) { + if (comparisonInfo.message) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [initTypeSymbol.toString(), typeExprSymbol.toString(), comparisonInfo.message], enclosingDecl); + } else { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [initTypeSymbol.toString(), typeExprSymbol.toString()], enclosingDecl); + } + } + } + } + + var prevSupressErrors = this.context.suppressErrors; + this.context.suppressErrors = true; + var decl = this.resolver.getDeclForAST(boundDeclAST); + + var varTypeSymbol = this.resolveSymbolAndReportDiagnostics(boundDeclAST, false, enclosingDecl).getType(); + + if (typeExprSymbol && typeExprSymbol.isContainer() && varTypeSymbol.isError()) { + this.checkForResolutionError(varTypeSymbol, decl); + } + + this.context.suppressErrors = prevSupressErrors; + + var declSymbol = decl.getSymbol(); + + if (declSymbol.getKind() != 2048 /* Parameter */ && (declSymbol.getKind() != 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + this.checkTypePrivacy(declSymbol, varTypeSymbol, typeCheckContext, function (typeSymbol) { + return _this.variablePrivacyErrorReporter(declSymbol, typeSymbol, typeCheckContext); + }); + } + + return varTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckImportDeclaration = function (importDeclaration, typeCheckContext) { + var result = this.resolveSymbolAndReportDiagnostics(importDeclaration, false, typeCheckContext.getEnclosingDecl()); + + var savedInImportDeclaration = typeCheckContext.inImportDeclaration; + typeCheckContext.inImportDeclaration = true; + this.typeCheckAST(importDeclaration.alias, typeCheckContext, false); + typeCheckContext.inImportDeclaration = savedInImportDeclaration; + + return result; + }; + + PullTypeChecker.prototype.typeCheckFunction = function (funcDeclAST, typeCheckContext, inContextuallyTypedAssignment) { + if (funcDeclAST.isConstructor || TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 1024 /* ConstructMember */)) { + return this.typeCheckConstructor(funcDeclAST, typeCheckContext, inContextuallyTypedAssignment); + } else if (TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 4096 /* IndexerMember */)) { + return this.typeCheckIndexer(funcDeclAST, typeCheckContext, inContextuallyTypedAssignment); + } else if (funcDeclAST.isAccessor()) { + return this.typeCheckAccessor(funcDeclAST, typeCheckContext, inContextuallyTypedAssignment); + } + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var functionSymbol = this.resolveSymbolAndReportDiagnostics(funcDeclAST, inContextuallyTypedAssignment, enclosingDecl); + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.typeArguments, typeCheckContext, inContextuallyTypedAssignment); + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, inContextuallyTypedAssignment); + this.typeCheckAST(funcDeclAST.returnTypeAnnotation, typeCheckContext, false); + this.typeCheckAST(funcDeclAST.block, typeCheckContext, false); + + var hasReturn = typeCheckContext.getEnclosingDeclHasReturn(); + + this.validateVariableDeclarationGroups(functionDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + var functionSignature = functionDecl.getSignatureSymbol(); + + var parameters = functionSignature.getParameters(); + + if (parameters.length) { + for (var i = 0; i < parameters.length; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + } + + var returnType = functionSignature.getReturnType(); + + this.checkForResolutionError(returnType, enclosingDecl); + + if (funcDeclAST.block && funcDeclAST.returnTypeAnnotation != null && !hasReturn) { + var isVoidOrAny = this.resolver.isAnyOrEquivalent(returnType) || returnType === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !(funcDeclAST.block.statements.members.length > 0 && funcDeclAST.block.statements.members[0].nodeType === 95 /* ThrowStatement */)) { + var funcName = functionDecl.getDisplayName(); + funcName = funcName ? "'" + funcName + "'" : "expression"; + + this.postError(funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), typeCheckContext.scriptName, 192 /* Function__0__declared_a_non_void_return_type__but_has_no_return_expression */, [funcName], typeCheckContext.getEnclosingDecl()); + } + } + + this.typeCheckFunctionOverloads(funcDeclAST, typeCheckContext); + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + + return functionSymbol ? functionSymbol.getType() : null; + }; + + PullTypeChecker.prototype.typeCheckFunctionOverloads = function (funcDecl, typeCheckContext, signature, allSignatures) { + if (!signature) { + var functionSignatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(funcDecl, typeCheckContext.semanticInfo); + signature = functionSignatureInfo.signature; + allSignatures = functionSignatureInfo.allSignatures; + } + var functionDeclaration = typeCheckContext.semanticInfo.getDeclForAST(funcDecl); + var funcSymbol = functionDeclaration.getSymbol(); + + var definitionSignature = null; + for (var i = allSignatures.length - 1; i >= 0; i--) { + if (allSignatures[i].isDefinition()) { + definitionSignature = allSignatures[i]; + break; + } + } + + if (!signature.isDefinition()) { + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i] === signature) { + break; + } + + if (this.resolver.signaturesAreIdentical(allSignatures[i], signature)) { + if (funcDecl.isConstructor) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 210 /* Duplicate_constructor_overload_signature */, null, typeCheckContext.getEnclosingDecl()); + } else if (funcDecl.isConstructMember()) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 212 /* Duplicate_overload_construct_signature */, null, typeCheckContext.getEnclosingDecl()); + } else if (funcDecl.isCallMember()) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 211 /* Duplicate_overload_call_signature */, null, typeCheckContext.getEnclosingDecl()); + } else { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 209 /* Duplicate_overload_signature_for__0_ */, [funcSymbol.getScopedNameEx().toString()], typeCheckContext.getEnclosingDecl()); + } + + break; + } + } + } + + var isConstantOverloadSignature = signature.isStringConstantOverloadSignature(); + if (isConstantOverloadSignature) { + if (signature.isDefinition()) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 229 /* Overload_signature_implementation_cannot_use_specialized_type */, null, typeCheckContext.getEnclosingDecl()); + } else { + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var foundSubtypeSignature = false; + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i].isDefinition() || allSignatures[i] === signature) { + continue; + } + + if (!allSignatures[i].isResolved()) { + this.resolver.resolveDeclaredSymbol(allSignatures[i], typeCheckContext.getEnclosingDecl(), resolutionContext); + } + + if (allSignatures[i].isStringConstantOverloadSignature()) { + continue; + } + + if (this.resolver.signatureIsSubtypeOfTarget(signature, allSignatures[i], resolutionContext)) { + foundSubtypeSignature = true; + break; + } + } + + if (!foundSubtypeSignature) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 219 /* Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature */, null, typeCheckContext.getEnclosingDecl()); + } + } + } else if (definitionSignature && definitionSignature != signature) { + var comparisonInfo = new TypeComparisonInfo(); + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + if (!definitionSignature.isResolved()) { + this.resolver.resolveDeclaredSymbol(definitionSignature, typeCheckContext.getEnclosingDecl(), resolutionContext); + } + + if (!this.resolver.signatureIsAssignableToTarget(definitionSignature, signature, resolutionContext, comparisonInfo)) { + if (comparisonInfo.message) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 214 /* Overload_signature_is_not_compatible_with_function_definition__NL__0 */, [comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 213 /* Overload_signature_is_not_compatible_with_function_definition */, null, typeCheckContext.getEnclosingDecl()); + } + } + } + + var signatureForVisibilityCheck = definitionSignature; + if (!definitionSignature) { + if (allSignatures[0] === signature) { + return; + } + signatureForVisibilityCheck = allSignatures[0]; + } + + if (!funcDecl.isConstructor && !funcDecl.isConstructMember() && signature != signatureForVisibilityCheck) { + var errorCode; + + if (signatureForVisibilityCheck.hasFlag(2 /* Private */) != signature.hasFlag(2 /* Private */)) { + errorCode = 215 /* Overload_signatures_must_all_be_public_or_private */; + } else if (signatureForVisibilityCheck.hasFlag(1 /* Exported */) != signature.hasFlag(1 /* Exported */)) { + errorCode = 216 /* Overload_signatures_must_all_be_exported_or_local */; + } else if (signatureForVisibilityCheck.hasFlag(8 /* Ambient */) != signature.hasFlag(8 /* Ambient */)) { + errorCode = 217 /* Overload_signatures_must_all_be_ambient_or_non_ambient */; + } else if (signatureForVisibilityCheck.hasFlag(128 /* Optional */) != signature.hasFlag(128 /* Optional */)) { + errorCode = 218 /* Overload_signatures_must_all_be_optional_or_required */; + } + + if (errorCode) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, errorCode, null, typeCheckContext.getEnclosingDecl()); + } + } + }; + + PullTypeChecker.prototype.typeCheckTypeParameter = function (typeParameter, typeCheckContext) { + if (typeParameter.constraint) { + var constraintType = this.typeCheckAST(typeParameter.constraint, typeCheckContext, false); + + if (constraintType && !constraintType.isError() && constraintType.isPrimitive()) { + this.postError(typeParameter.constraint.minChar, typeParameter.constraint.getLength(), typeCheckContext.scriptName, 149 /* Type_parameter_constraint_cannot_be_a_primitive_type */, null, typeCheckContext.getEnclosingDecl()); + } + } + + return this.resolveSymbolAndReportDiagnostics(typeParameter, false, typeCheckContext.getEnclosingDecl()); + }; + + PullTypeChecker.prototype.typeCheckAccessor = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var funcDeclAST = ast; + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var accessorSymbol = this.resolveSymbolAndReportDiagnostics(ast, inContextuallyTypedAssignment, enclosingDecl); + this.checkForResolutionError(accessorSymbol.getType(), enclosingDecl); + + var isGetter = TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 32 /* GetAccessor */); + var isSetter = !isGetter; + + var getter = accessorSymbol.getGetter(); + var setter = accessorSymbol.getSetter(); + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, inContextuallyTypedAssignment); + + this.typeCheckAST(funcDeclAST.block, typeCheckContext, false); + + var hasReturn = typeCheckContext.getEnclosingDeclHasReturn(); + + this.validateVariableDeclarationGroups(functionDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + var functionSignature = functionDecl.getSignatureSymbol(); + + var parameters = functionSignature.getParameters(); + + var returnType = functionSignature.getReturnType(); + + this.checkForResolutionError(returnType, enclosingDecl); + + var funcNameAST = funcDeclAST.name; + + if (isGetter && !hasReturn) { + if (!(funcDeclAST.block.statements.members.length > 0 && funcDeclAST.block.statements.members[0].nodeType === 95 /* ThrowStatement */)) { + this.postError(funcNameAST.minChar, funcNameAST.getLength(), typeCheckContext.scriptName, 193 /* Getters_must_return_a_value */, null, typeCheckContext.getEnclosingDecl()); + } + } + + if (getter && setter) { + var getterDecl = getter.getDeclarations()[0]; + var setterDecl = setter.getDeclarations()[0]; + + var getterIsPrivate = getterDecl.getFlags() & 2 /* Private */; + var setterIsPrivate = setterDecl.getFlags() & 2 /* Private */; + + if (getterIsPrivate != setterIsPrivate) { + this.postError(funcNameAST.minChar, funcNameAST.getLength(), typeCheckContext.scriptName, 194 /* Getter_and_setter_accessors_do_not_agree_in_visibility */, null, typeCheckContext.getEnclosingDecl()); + } + } + + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + + return null; + }; + + PullTypeChecker.prototype.typeCheckConstructor = function (funcDeclAST, typeCheckContext, inContextuallyTypedAssignment) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var functionSymbol = this.resolveSymbolAndReportDiagnostics(funcDeclAST, inContextuallyTypedAssignment, enclosingDecl); + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.typeArguments, typeCheckContext, inContextuallyTypedAssignment); + + typeCheckContext.inConstructorArguments = true; + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, inContextuallyTypedAssignment); + typeCheckContext.inConstructorArguments = false; + + typeCheckContext.seenSuperConstructorCall = false; + + this.typeCheckAST(funcDeclAST.returnTypeAnnotation, typeCheckContext, false); + + this.typeCheckAST(funcDeclAST.block, typeCheckContext, false); + + this.validateVariableDeclarationGroups(functionDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + var constructorSignature = functionDecl.getSignatureSymbol(); + + var parameters = constructorSignature.getParameters(); + + if (parameters.length) { + for (var i = 0, n = parameters.length; i < n; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + } + + this.checkForResolutionError(constructorSignature.getReturnType(), enclosingDecl); + + if (functionDecl.getSignatureSymbol() && functionDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(typeCheckContext)) { + if (!typeCheckContext.seenSuperConstructorCall) { + this.postError(funcDeclAST.minChar, 11, typeCheckContext.scriptName, 173 /* Constructors_for_derived_classes_must_contain_a__super__call */, null, enclosingDecl); + } else if (this.superCallMustBeFirstStatementInConstructor(functionDecl, enclosingDecl)) { + var firstStatement = this.getFirstStatementFromFunctionDeclAST(funcDeclAST); + if (!firstStatement || !this.isSuperCallNode(firstStatement)) { + this.postError(funcDeclAST.minChar, 11, typeCheckContext.scriptName, 172 /* A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties */, null, enclosingDecl); + } + } + } + + this.typeCheckFunctionOverloads(funcDeclAST, typeCheckContext); + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + return functionSymbol ? functionSymbol.getType() : null; + }; + + PullTypeChecker.prototype.typeCheckIndexer = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.resolver.resolveAST(ast, inContextuallyTypedAssignment, enclosingDecl, this.context); + + var funcDeclAST = ast; + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, false); + + this.typeCheckAST(funcDeclAST.returnTypeAnnotation, typeCheckContext, false); + + typeCheckContext.popEnclosingDecl(); + + var indexSignature = functionDecl.getSignatureSymbol(); + var parameters = indexSignature.getParameters(); + + if (parameters.length) { + var parameterType = null; + + for (var i = 0; i < parameters.length; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + } + + this.checkForResolutionError(indexSignature.getReturnType(), enclosingDecl); + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + + var isNumericIndexer = parameters[0].getType() === this.semanticInfoChain.numberTypeSymbol; + + var allIndexSignatures = enclosingDecl.getSymbol().getType().getIndexSignatures(); + for (var i = 0; i < allIndexSignatures.length; i++) { + if (!allIndexSignatures[i].isResolved()) { + this.resolver.resolveDeclaredSymbol(allIndexSignatures[i], allIndexSignatures[i].getDeclarations()[0].getParentDecl(), this.context); + } + if (allIndexSignatures[i].getParameters()[0].getType() !== parameters[0].getType()) { + var stringIndexSignature; + var numberIndexSignature; + if (isNumericIndexer) { + numberIndexSignature = indexSignature; + stringIndexSignature = allIndexSignatures[i]; + } else { + numberIndexSignature = allIndexSignatures[i]; + stringIndexSignature = indexSignature; + + if (enclosingDecl.getSymbol() === numberIndexSignature.getDeclarations()[0].getParentDecl().getSymbol()) { + break; + } + } + var comparisonInfo = new TypeComparisonInfo(); + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + if (!this.resolver.sourceIsSubtypeOfTarget(numberIndexSignature.getReturnType(), stringIndexSignature.getReturnType(), resolutionContext, comparisonInfo)) { + if (comparisonInfo.message) { + this.postError(funcDeclAST.minChar, funcDeclAST.getLength(), typeCheckContext.scriptName, 234 /* Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2 */, [numberIndexSignature.getReturnType().toString(), stringIndexSignature.getReturnType().toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(funcDeclAST.minChar, funcDeclAST.getLength(), typeCheckContext.scriptName, 233 /* Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__ */, [numberIndexSignature.getReturnType().toString(), stringIndexSignature.getReturnType().toString()], typeCheckContext.getEnclosingDecl()); + } + } + break; + } + } + + var allMembers = enclosingDecl.getSymbol().getType().getAllMembers(TypeScript.PullElementKind.All, true); + for (var i = 0; i < allMembers.length; i++) { + var name = allMembers[i].getName(); + if (name) { + if (!allMembers[i].isResolved()) { + this.resolver.resolveDeclaredSymbol(allMembers[i], allMembers[i].getDeclarations()[0].getParentDecl(), this.context); + } + + if (enclosingDecl.getSymbol() !== allMembers[i].getContainer()) { + var isMemberNumeric = isFinite(+name); + if (isNumericIndexer === isMemberNumeric) { + this.checkThatMemberIsSubtypeOfIndexer(allMembers[i], indexSignature, funcDeclAST, typeCheckContext, isNumericIndexer); + } + } + } + } + + return null; + }; + + PullTypeChecker.prototype.typeCheckMembersAgainstIndexer = function (containerType, typeCheckContext) { + var indexSignatures = containerType.getIndexSignatures(); + if (indexSignatures.length > 0) { + var members = typeCheckContext.getEnclosingDecl().getChildDecls(); + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if (!member.getName() || member.getKind() & TypeScript.PullElementKind.SomeSignature) { + continue; + } + + var isMemberNumeric = isFinite(+member.getName()); + for (var j = 0; j < indexSignatures.length; j++) { + if (!indexSignatures[j].isResolved()) { + this.resolver.resolveDeclaredSymbol(indexSignatures[j], indexSignatures[j].getDeclarations()[0].getParentDecl(), this.context); + } + if ((indexSignatures[j].getParameters()[0].getType() === this.semanticInfoChain.numberTypeSymbol) === isMemberNumeric) { + this.checkThatMemberIsSubtypeOfIndexer(member.getSymbol(), indexSignatures[j], this.semanticInfoChain.getASTForDecl(member), typeCheckContext, isMemberNumeric); + break; + } + } + } + } + }; + + PullTypeChecker.prototype.checkThatMemberIsSubtypeOfIndexer = function (member, indexSignature, astForError, typeCheckContext, isNumeric) { + var comparisonInfo = new TypeComparisonInfo(); + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + if (!this.resolver.sourceIsSubtypeOfTarget(member.getType(), indexSignature.getReturnType(), resolutionContext, comparisonInfo)) { + if (isNumeric) { + if (comparisonInfo.message) { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 236 /* All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1 */, [indexSignature.getReturnType().toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 235 /* All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__ */, [indexSignature.getReturnType().toString()], typeCheckContext.getEnclosingDecl()); + } + } else { + if (comparisonInfo.message) { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 238 /* All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1 */, [indexSignature.getReturnType().toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 237 /* All_named_properties_must_be_subtypes_of_string_indexer_type___0__ */, [indexSignature.getReturnType().toString()], typeCheckContext.getEnclosingDecl()); + } + } + } + }; + + PullTypeChecker.prototype.typeCheckIfTypeMemberPropertyOkToOverride = function (typeSymbol, extendedType, typeMember, extendedTypeMember, comparisonInfo) { + if (!typeSymbol.isClass()) { + return true; + } + + var typeMemberKind = typeMember.getKind(); + var extendedMemberKind = extendedTypeMember.getKind(); + + if (typeMemberKind === extendedMemberKind) { + return true; + } + + var errorCode; + if (typeMemberKind === 4096 /* Property */) { + if (typeMember.isAccessor()) { + errorCode = 256 /* Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function */; + } else { + errorCode = 257 /* Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function */; + } + } else if (typeMemberKind === 65536 /* Method */) { + if (extendedTypeMember.isAccessor()) { + errorCode = 258 /* Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor */; + } else { + errorCode = 259 /* Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property */; + } + } + + var message = TypeScript.getDiagnosticMessage(errorCode, [typeSymbol.toString(), typeMember.getScopedNameEx().toString(), extendedType.toString()]); + comparisonInfo.addMessage(message); + return false; + }; + + PullTypeChecker.prototype.typeCheckIfTypeExtendsType = function (typeDecl, typeSymbol, extendedType, typeCheckContext) { + var typeMembers = typeSymbol.getMembers(); + + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var comparisonInfo = new TypeComparisonInfo(); + var foundError = false; + + for (var i = 0; i < typeMembers.length; i++) { + var propName = typeMembers[i].getName(); + var extendedTypeProp = extendedType.findMember(propName); + if (extendedTypeProp) { + foundError = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, comparisonInfo); + + if (!foundError) { + foundError = !this.resolver.sourcePropertyIsSubtypeOfTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, resolutionContext, comparisonInfo); + } + + if (foundError) { + break; + } + } + } + + if (!foundError && typeSymbol.hasOwnCallSignatures()) { + foundError = !this.resolver.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(typeSymbol, extendedType, resolutionContext, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnConstructSignatures()) { + foundError = !this.resolver.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(typeSymbol, extendedType, resolutionContext, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnIndexSignatures()) { + foundError = !this.resolver.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(typeSymbol, extendedType, resolutionContext, comparisonInfo); + } + + if (!foundError && typeSymbol.isClass()) { + var typeConstructorType = (typeSymbol).getConstructorMethod().getType(); + var typeConstructorTypeMembers = typeConstructorType.getMembers(); + if (typeConstructorTypeMembers.length) { + var extendedConstructorType = (extendedType).getConstructorMethod().getType(); + var comparisonInfoForPropTypeCheck = new TypeComparisonInfo(comparisonInfo); + + for (var i = 0; i < typeConstructorTypeMembers.length; i++) { + var propName = typeConstructorTypeMembers[i].getName(); + var extendedConstructorTypeProp = extendedConstructorType.findMember(propName); + if (extendedConstructorTypeProp) { + if (!extendedConstructorTypeProp.isResolved()) { + var extendedClassAst = typeCheckContext.semanticInfo.getASTForSymbol(extendedType); + var extendedClassDecl = typeCheckContext.semanticInfo.getDeclForAST(extendedClassAst); + this.resolver.resolveDeclaredSymbol(extendedConstructorTypeProp, extendedClassDecl, resolutionContext); + } + + var typeConstructorTypePropType = typeConstructorTypeMembers[i].getType(); + var extendedConstructorTypePropType = extendedConstructorTypeProp.getType(); + if (!this.resolver.sourceIsSubtypeOfTarget(typeConstructorTypePropType, extendedConstructorTypePropType, resolutionContext, comparisonInfoForPropTypeCheck)) { + var propMessage; + if (comparisonInfoForPropTypeCheck.message) { + propMessage = TypeScript.getDiagnosticMessage(261 /* Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3 */, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(), extendedType.toString(), comparisonInfoForPropTypeCheck.message]); + } else { + propMessage = TypeScript.getDiagnosticMessage(260 /* Types_of_static_property__0__of_class__1__and_class__2__are_incompatible */, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(), extendedType.toString()]); + } + comparisonInfo.addMessage(propMessage); + foundError = true; + break; + } + } + } + } + } + + if (foundError) { + var errorCode; + if (typeSymbol.isClass()) { + errorCode = 206 /* Class__0__cannot_extend_class__1__NL__2 */; + } else { + if (extendedType.isClass()) { + errorCode = 207 /* Interface__0__cannot_extend_class__1__NL__2 */; + } else { + errorCode = 208 /* Interface__0__cannot_extend_interface__1__NL__2 */; + } + } + + this.postError(typeDecl.name.minChar, typeDecl.name.getLength(), typeCheckContext.scriptName, errorCode, [typeSymbol.getScopedName(), extendedType.getScopedName(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } + }; + + PullTypeChecker.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, typeCheckContext) { + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var comparisonInfo = new TypeComparisonInfo(); + var foundError = !this.resolver.sourceMembersAreSubtypeOfTargetMembers(classSymbol, implementedType, resolutionContext, comparisonInfo); + if (!foundError) { + foundError = !this.resolver.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(classSymbol, implementedType, resolutionContext, comparisonInfo); + if (!foundError) { + foundError = !this.resolver.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(classSymbol, implementedType, resolutionContext, comparisonInfo); + if (!foundError) { + foundError = !this.resolver.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(classSymbol, implementedType, resolutionContext, comparisonInfo); + } + } + } + + if (foundError) { + var errorCode = implementedType.isClass() ? 203 /* Class__0__declares_class__1__but_does_not_implement_it__NL__2 */ : 202 /* Class__0__declares_interface__1__but_does_not_implement_it__NL__2 */; + + this.postError(classDecl.name.minChar, classDecl.name.getLength(), typeCheckContext.scriptName, errorCode, [classSymbol.getScopedName(), implementedType.getScopedName(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } + }; + + PullTypeChecker.prototype.typeCheckBase = function (typeDeclAst, typeSymbol, baseDeclAST, isExtendedType, typeCheckContext) { + var _this = this; + var typeDecl = typeCheckContext.semanticInfo.getDeclForAST(typeDeclAst); + var contextForBaseTypeResolution = new TypeScript.PullTypeResolutionContext(); + contextForBaseTypeResolution.isResolvingClassExtendedType = true; + + var baseType = this.typeCheckAST(new TypeScript.TypeReference(baseDeclAST, 0), typeCheckContext, false); + contextForBaseTypeResolution.isResolvingClassExtendedType = false; + + var typeDeclIsClass = typeSymbol.isClass(); + + if (!typeSymbol.isValidBaseKind(baseType, isExtendedType)) { + if (baseType.isError()) { + var error = (baseType).getDiagnostic(); + if (error) { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, error.diagnosticCode(), error.arguments(), typeCheckContext.getEnclosingDecl()); + } + } else if (isExtendedType) { + if (typeDeclIsClass) { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, 142 /* A_class_may_only_extend_another_class */, null, typeCheckContext.getEnclosingDecl()); + } else { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, 144 /* An_interface_may_only_extend_another_class_or_interface */, null, typeCheckContext.getEnclosingDecl()); + } + } else { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, 143 /* A_class_may_only_implement_another_class_or_interface */, null, typeCheckContext.getEnclosingDecl()); + } + return; + } + + if ((baseType.getRootSymbol()).hasBase(typeSymbol.getRootSymbol())) { + typeSymbol.setHasBaseTypeConflict(); + baseType.setHasBaseTypeConflict(); + + this.postError(typeDeclAst.name.minChar, typeDeclAst.name.getLength(), typeCheckContext.scriptName, typeDeclIsClass ? 168 /* Class__0__is_recursively_referenced_as_a_base_type_of_itself */ : 169 /* Interface__0__is_recursively_referenced_as_a_base_type_of_itself */, [typeSymbol.getScopedName()], typeCheckContext.getEnclosingDecl()); + return; + } + + if (isExtendedType) { + this.typeCheckIfTypeExtendsType(typeDeclAst, typeSymbol, baseType, typeCheckContext); + } else { + this.typeCheckIfClassImplementsType(typeDeclAst, typeSymbol, baseType, typeCheckContext); + } + + this.checkTypePrivacy(typeSymbol, baseType, typeCheckContext, function (errorTypeSymbol) { + return _this.baseListPrivacyErrorReporter(typeDeclAst, typeSymbol, baseDeclAST, isExtendedType, errorTypeSymbol, typeCheckContext); + }); + }; + + PullTypeChecker.prototype.typeCheckBases = function (typeDeclAst, typeSymbol, typeCheckContext) { + if (!typeDeclAst.extendsList && !typeDeclAst.implementsList) { + return; + } + + for (var i = 0; i < typeDeclAst.extendsList.members.length; i++) { + this.typeCheckBase(typeDeclAst, typeSymbol, typeDeclAst.extendsList.members[i], true, typeCheckContext); + } + + if (typeSymbol.isClass()) { + for (var i = 0; i < typeDeclAst.implementsList.members.length; i++) { + this.typeCheckBase(typeDeclAst, typeSymbol, typeDeclAst.implementsList.members[i], false, typeCheckContext); + } + } else if (typeDeclAst.implementsList) { + this.postError(typeDeclAst.implementsList.minChar, typeDeclAst.implementsList.getLength(), typeCheckContext.scriptName, 145 /* An_interface_cannot_implement_another_type */, null, typeCheckContext.getEnclosingDecl()); + } + }; + + PullTypeChecker.prototype.typeCheckClass = function (ast, typeCheckContext) { + var classAST = ast; + + var classSymbol = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(classSymbol, typeCheckContext.getEnclosingDecl()); + + this.typeCheckAST(classAST.typeParameters, typeCheckContext, false); + + var classDecl = typeCheckContext.semanticInfo.getDeclForAST(classAST); + typeCheckContext.pushEnclosingDecl(classDecl); + + this.typeCheckAST(classAST.typeParameters, typeCheckContext, false); + + this.typeCheckBases(classAST, classSymbol, typeCheckContext); + + this.typeCheckAST(classAST.members, typeCheckContext, false); + + if (!classSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(classSymbol, typeCheckContext); + } + + typeCheckContext.popEnclosingDecl(); + + return classSymbol; + }; + + PullTypeChecker.prototype.typeCheckInterface = function (ast, typeCheckContext) { + var interfaceAST = ast; + + var interfaceType = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(interfaceType, typeCheckContext.getEnclosingDecl()); + + var interfaceDecl = typeCheckContext.semanticInfo.getDeclForAST(interfaceAST); + typeCheckContext.pushEnclosingDecl(interfaceDecl); + + this.typeCheckAST(interfaceAST.typeParameters, typeCheckContext, false); + + this.typeCheckBases(ast, interfaceType, typeCheckContext); + + this.typeCheckAST(interfaceAST.members, typeCheckContext, false); + + if (!interfaceType.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(interfaceType, typeCheckContext); + } + + typeCheckContext.popEnclosingDecl(); + + return interfaceType; + }; + + PullTypeChecker.prototype.typeCheckModule = function (ast, typeCheckContext) { + var moduleDeclAST = ast; + var moduleType = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()); + + this.checkForResolutionError(moduleType, typeCheckContext.getEnclosingDecl()); + + var moduleDecl = typeCheckContext.semanticInfo.getDeclForAST(moduleDeclAST); + typeCheckContext.pushEnclosingDecl(moduleDecl); + + var modName = (moduleDeclAST.name).text; + var isDynamic = TypeScript.isQuoted(modName) || TypeScript.hasFlag(moduleDeclAST.getModuleFlags(), 512 /* IsDynamic */); + + if (isDynamic && moduleDeclAST.members && moduleDeclAST.members.members) { + for (var i = moduleDeclAST.members.members.length - 1; i >= 0; i--) { + if (moduleDeclAST.members.members[i] && moduleDeclAST.members.members[i].nodeType == 87 /* ExportAssignment */) { + this.typeCheckAST(moduleDeclAST.members.members[i], typeCheckContext, false); + break; + } + } + } + this.typeCheckAST(moduleDeclAST.members, typeCheckContext, false); + + this.validateVariableDeclarationGroups(moduleDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + return moduleType; + }; + + PullTypeChecker.prototype.checkAssignability = function (ast, source, target, typeCheckContext) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.resolver.sourceIsAssignableToTarget(source, target, this.context, comparisonInfo); + + if (!isAssignable) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + if (comparisonInfo.message) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [source.toString(), target.toString(), comparisonInfo.message], enclosingDecl); + } else { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [source.toString(), target.toString()], enclosingDecl); + } + } + }; + + PullTypeChecker.prototype.isValidLHS = function (ast, expressionSymbol) { + var expressionTypeSymbol = expressionSymbol.getType(); + + if (ast.nodeType === 35 /* ElementAccessExpression */ || this.resolver.isAnyOrEquivalent(expressionTypeSymbol)) { + return true; + } else if (!expressionSymbol.isType() || expressionTypeSymbol.isArray()) { + return ((expressionSymbol.getKind() & TypeScript.PullElementKind.SomeLHS) != 0) && !expressionSymbol.hasFlag(4096 /* Enum */); + } + + return false; + }; + + PullTypeChecker.prototype.typeCheckAssignment = function (binaryExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + + var leftExpr = this.resolveSymbolAndReportDiagnostics(binaryExpression.operand1, false, typeCheckContext.getEnclosingDecl()); + var leftType = leftExpr.getType(); + this.checkForResolutionError(leftType, enclosingDecl); + leftType = this.resolver.widenType(leftExpr.getType()); + + this.context.pushContextualType(leftType, this.context.inProvisionalResolution(), null); + var rightType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand2, typeCheckContext, true)); + this.context.popContextualType(); + + if (!this.isValidLHS(binaryExpression.operand1, leftExpr)) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 195 /* Invalid_left_hand_side_of_assignment_expression */, null, enclosingDecl); + } + + this.checkAssignability(binaryExpression.operand1, rightType, leftType, typeCheckContext); + return rightType; + }; + + PullTypeChecker.prototype.typeCheckGenericType = function (genericType, typeCheckContext) { + var savedResolvingTypeReference = this.context.resolvingTypeReference; + this.context.resolvingTypeReference = true; + this.typeCheckAST(genericType.name, typeCheckContext, false); + this.context.resolvingTypeReference = savedResolvingTypeReference; + + this.typeCheckAST(genericType.typeArguments, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(genericType, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckObjectLiteral = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var objectLitAST = ast; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var objectLitType = this.resolveSymbolAndReportDiagnostics(ast, inContextuallyTypedAssignment, enclosingDecl).getType(); + var memberDecls = objectLitAST.operand; + + var contextualType = this.context.getContextualType(); + var memberType; + + if (memberDecls) { + var member = null; + + for (var i = 0; i < memberDecls.members.length; i++) { + var binex = memberDecls.members[i]; + + if (contextualType) { + var text; + if (binex.operand1.nodeType === 20 /* Name */) { + text = (binex.operand1).text; + } else if (binex.operand1.nodeType === 5 /* StringLiteral */) { + text = (binex.operand1).text; + } + + member = contextualType.findMember(text); + + if (member) { + this.context.pushContextualType(member.getType(), this.context.inProvisionalResolution(), null); + } + } + + this.typeCheckAST(binex.operand2, typeCheckContext, member != null); + + if (member) { + this.context.popContextualType(); + member = null; + } + } + } + + this.checkForResolutionError(objectLitType, enclosingDecl); + + return objectLitType; + }; + + PullTypeChecker.prototype.typeCheckArrayLiteral = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var arrayLiteralAST = ast; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var type = this.resolveSymbolAndReportDiagnostics(ast, inContextuallyTypedAssignment, enclosingDecl).getType(); + var memberASTs = arrayLiteralAST.operand; + + var contextualType = this.context.getContextualType(); + var contextualMemberType = null; + if (contextualType && contextualType.isArray()) { + contextualMemberType = contextualType.getElementType(); + } + + if (memberASTs && memberASTs.members && memberASTs.members.length) { + var elementTypes = []; + + if (contextualMemberType) { + this.context.pushContextualType(contextualMemberType, this.context.inProvisionalResolution(), null); + } + + for (var i = 0; i < memberASTs.members.length; i++) { + elementTypes[elementTypes.length] = this.typeCheckAST(memberASTs.members[i], typeCheckContext, false); + } + + if (contextualMemberType) { + this.context.popContextualType(); + } + } + + this.checkForResolutionError(type, enclosingDecl); + + return type; + }; + + PullTypeChecker.prototype.enclosingClassIsDerived = function (typeCheckContext) { + var enclosingClass = typeCheckContext.getEnclosingDecl(8 /* Class */); + + if (enclosingClass) { + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length > 0) { + return true; + } + } + + return false; + }; + + PullTypeChecker.prototype.isSuperCallNode = function (node) { + if (node && node.nodeType === 88 /* ExpressionStatement */) { + var expressionStatement = node; + if (expressionStatement.expression && expressionStatement.expression.nodeType === 36 /* InvocationExpression */) { + var callExpression = expressionStatement.expression; + if (callExpression.target && callExpression.target.nodeType === 30 /* SuperExpression */) { + return true; + } + } + } + return false; + }; + + PullTypeChecker.prototype.getFirstStatementFromFunctionDeclAST = function (funcDeclAST) { + if (funcDeclAST.block && funcDeclAST.block.statements && funcDeclAST.block.statements.members) { + return funcDeclAST.block.statements.members[0]; + } + + return null; + }; + + PullTypeChecker.prototype.superCallMustBeFirstStatementInConstructor = function (enclosingConstructor, enclosingClass) { + if (enclosingConstructor && enclosingClass) { + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length === 0) { + return false; + } + + var classMembers = classSymbol.getMembers(); + for (var i = 0, n1 = classMembers.length; i < n1; i++) { + var member = classMembers[i]; + + if (member.getKind() === 4096 /* Property */) { + var declarations = member.getDeclarations(); + for (var j = 0, n2 = declarations.length; j < n2; j++) { + var declaration = declarations[j]; + var ast = this.semanticInfoChain.getASTForDecl(declaration); + if (ast.nodeType === 19 /* Parameter */) { + return true; + } + + if (ast.nodeType === 17 /* VariableDeclarator */) { + var variableDeclarator = ast; + if (variableDeclarator.init) { + return true; + } + } + } + } + } + } + + return false; + }; + + PullTypeChecker.prototype.checkForThisOrSuperCaptureInArrowFunction = function (expression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var declPath = typeCheckContext.enclosingDeclStack; + + if (declPath.length) { + var inFatArrow = false; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.getKind(); + var declFlags = decl.getFlags(); + + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(declFlags, 8192 /* FatArrow */)) { + inFatArrow = true; + continue; + } + + if (inFatArrow) { + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + decl.setFlags(decl.getFlags() | 262144 /* MustCaptureThis */); + + if (declKind === 8 /* Class */) { + decl.getChildDecls().filter(function (d) { + return d.getKind() === 32768 /* ConstructorMethod */; + }).map(function (d) { + return d.setFlags(d.getFlags() | 262144 /* MustCaptureThis */); + }); + } + break; + } + } + } + } + }; + + PullTypeChecker.prototype.typeCheckThisExpression = function (thisExpressionAST, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var enclosingNonLambdaDecl = typeCheckContext.getEnclosingNonLambdaDecl(); + + if (typeCheckContext.inSuperConstructorCall && this.superCallMustBeFirstStatementInConstructor(typeCheckContext.getEnclosingDecl(32768 /* ConstructorMethod */), typeCheckContext.getEnclosingDecl(8 /* Class */))) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 166 /* _this__cannot_be_referenced_in_current_location */, null, enclosingDecl); + } else if (enclosingNonLambdaDecl) { + if (enclosingNonLambdaDecl.getKind() === 8 /* Class */) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 205 /* _this__cannot_be_referenced_in_initializers_in_a_class_body */, null, enclosingDecl); + } else if (enclosingNonLambdaDecl.getKind() === 4 /* Container */ || enclosingNonLambdaDecl.getKind() === 32 /* DynamicModule */) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 176 /* _this__cannot_be_referenced_within_module_bodies */, null, enclosingDecl); + } else if (typeCheckContext.inConstructorArguments) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 220 /* _this__cannot_be_referenced_in_constructor_arguments */, null, enclosingDecl); + } + } + + this.checkForThisOrSuperCaptureInArrowFunction(thisExpressionAST, typeCheckContext); + + return this.resolveSymbolAndReportDiagnostics(thisExpressionAST, false, enclosingDecl).getType(); + }; + + PullTypeChecker.prototype.typeCheckSuperExpression = function (ast, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var nonLambdaEnclosingDecl = typeCheckContext.getEnclosingNonLambdaDecl(); + var nonLambdaEnclosingDeclKind = nonLambdaEnclosingDecl.getKind(); + var inSuperConstructorTarget = typeCheckContext.inSuperConstructorTarget; + + if (inSuperConstructorTarget && enclosingDecl.getKind() !== 32768 /* ConstructorMethod */) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 174 /* Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors */, null, enclosingDecl); + } else if ((nonLambdaEnclosingDeclKind !== 65536 /* Method */ && nonLambdaEnclosingDeclKind !== 262144 /* GetAccessor */ && nonLambdaEnclosingDeclKind !== 524288 /* SetAccessor */ && nonLambdaEnclosingDeclKind !== 32768 /* ConstructorMethod */) || ((nonLambdaEnclosingDecl.getFlags() & 16 /* Static */) !== 0)) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 170 /* _super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class */, null, enclosingDecl); + } else if (!this.enclosingClassIsDerived(typeCheckContext)) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 171 /* _super__cannot_be_referenced_in_non_derived_classes */, null, enclosingDecl); + } + + this.checkForThisOrSuperCaptureInArrowFunction(ast, typeCheckContext); + + return this.resolveSymbolAndReportDiagnostics(ast, false, enclosingDecl).getType(); + }; + + PullTypeChecker.prototype.typeCheckCallExpression = function (callExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var inSuperConstructorCall = (callExpression.target.nodeType === 30 /* SuperExpression */); + + var callResolutionData = new TypeScript.PullAdditionalCallResolutionData(); + var resultTypeAndDiagnostics = this.resolver.resolveCallExpression(callExpression, false, enclosingDecl, this.context, callResolutionData); + this.reportDiagnostics(resultTypeAndDiagnostics, enclosingDecl); + var resultType = resultTypeAndDiagnostics.symbol.getType(); + + this.typeCheckAST(callExpression.typeArguments, typeCheckContext, false); + + if (!resultType.isError()) { + var savedInSuperConstructorTarget = typeCheckContext.inSuperConstructorTarget; + if (inSuperConstructorCall) { + typeCheckContext.inSuperConstructorTarget = true; + } + + this.typeCheckAST(callExpression.target, typeCheckContext, false); + + typeCheckContext.inSuperConstructorTarget = savedInSuperConstructorTarget; + } + + if (inSuperConstructorCall && enclosingDecl.getKind() === 32768 /* ConstructorMethod */) { + typeCheckContext.seenSuperConstructorCall = true; + } + + var savedInSuperConstructorCall = typeCheckContext.inSuperConstructorCall; + if (inSuperConstructorCall) { + typeCheckContext.inSuperConstructorCall = true; + } + + var contextTypes = callResolutionData.actualParametersContextTypeSymbols; + if (callExpression.arguments) { + var argumentASTs = callExpression.arguments.members; + for (var i = 0, n = argumentASTs.length; i < n; i++) { + var argumentAST = argumentASTs[i]; + + if (contextTypes && contextTypes[i]) { + this.context.pushContextualType(contextTypes[i], this.context.inProvisionalResolution(), null); + } + + this.typeCheckAST(argumentAST, typeCheckContext, false); + + if (contextTypes && contextTypes[i]) { + this.context.popContextualType(); + } + } + } + + typeCheckContext.inSuperConstructorCall = savedInSuperConstructorCall; + + return resultType; + }; + + PullTypeChecker.prototype.typeCheckObjectCreationExpression = function (callExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var callResolutionData = new TypeScript.PullAdditionalCallResolutionData(); + var resultAndDiagnostics = this.resolver.resolveNewExpression(callExpression, false, enclosingDecl, this.context, callResolutionData); + this.reportDiagnostics(resultAndDiagnostics, typeCheckContext.getEnclosingDecl()); + + var result = resultAndDiagnostics.symbol.getType(); + + this.typeCheckAST(callExpression.target, typeCheckContext, false); + + this.typeCheckAST(callExpression.typeArguments, typeCheckContext, false); + + var contextTypes = callResolutionData.actualParametersContextTypeSymbols; + if (callExpression.arguments) { + var argumentASTs = callExpression.arguments.members; + for (var i = 0, n = argumentASTs.length; i < n; i++) { + var argumentAST = argumentASTs[i]; + + if (contextTypes && contextTypes[i]) { + this.context.pushContextualType(contextTypes[i], this.context.inProvisionalResolution(), null); + } + + this.typeCheckAST(argumentAST, typeCheckContext, false); + + if (contextTypes && contextTypes[i]) { + this.context.popContextualType(); + } + } + } + + return result; + }; + + PullTypeChecker.prototype.typeCheckTypeAssertion = function (ast, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var returnType = this.resolveSymbolAndReportDiagnostics(ast, false, enclosingDecl).getType(); + + if (returnType.isError()) { + var symbolName = (returnType).getData(); + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 164 /* Could_not_find_symbol__0_ */, [symbolName], typeCheckContext.getEnclosingDecl()); + } + + this.context.pushContextualType(returnType, this.context.inProvisionalResolution(), null); + var exprType = this.typeCheckAST(ast.operand, typeCheckContext, true); + this.context.popContextualType(); + + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.resolver.sourceIsAssignableToTarget(returnType, exprType, this.context, comparisonInfo) || this.resolver.sourceIsAssignableToTarget(exprType, returnType, this.context, comparisonInfo); + + if (!isAssignable) { + var message; + if (comparisonInfo.message) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [exprType.toString(), returnType.toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [exprType.toString(), returnType.toString()], typeCheckContext.getEnclosingDecl()); + } + } + + return returnType; + }; + + PullTypeChecker.prototype.typeCheckLogicalOperation = function (binex, typeCheckContext) { + var leftType = this.typeCheckAST(binex.operand1, typeCheckContext, false); + var rightType = this.typeCheckAST(binex.operand2, typeCheckContext, false); + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.resolver.sourceIsAssignableToTarget(leftType, rightType, this.context, comparisonInfo) && !this.resolver.sourceIsAssignableToTarget(rightType, leftType, this.context, comparisonInfo)) { + this.postError(binex.minChar, binex.getLength(), typeCheckContext.scriptName, 78 /* Operator__0__cannot_be_applied_to_types__1__and__2_ */, [TypeScript.BinaryExpression.getTextForBinaryToken(binex.nodeType), leftType.toString(), rightType.toString()], typeCheckContext.getEnclosingDecl()); + } + + return this.resolveSymbolAndReportDiagnostics(binex, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckLogicalAndOrExpression = function (binex, typeCheckContext) { + this.typeCheckAST(binex.operand1, typeCheckContext, false); + this.typeCheckAST(binex.operand2, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(binex, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckCommaExpression = function (binex, typeCheckContext) { + this.typeCheckAST(binex.operand1, typeCheckContext, false); + this.typeCheckAST(binex.operand2, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(binex, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckBinaryAdditionOperation = function (binaryExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.resolveSymbolAndReportDiagnostics(binaryExpression, false, enclosingDecl).getType(); + + var lhsType = this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + var rhsType = this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } else if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { + if (rhsType != this.semanticInfoChain.nullTypeSymbol && rhsType != this.semanticInfoChain.undefinedTypeSymbol) { + lhsType = rhsType; + } else { + lhsType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { + rhsType = this.semanticInfoChain.numberTypeSymbol; + } else if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { + if (lhsType != this.semanticInfoChain.nullTypeSymbol && lhsType != this.semanticInfoChain.undefinedTypeSymbol) { + rhsType = lhsType; + } else { + rhsType = this.semanticInfoChain.anyTypeSymbol; + } + } + + var exprType = null; + + if (lhsType === this.semanticInfoChain.stringTypeSymbol || rhsType === this.semanticInfoChain.stringTypeSymbol) { + exprType = this.semanticInfoChain.stringTypeSymbol; + } else if (this.resolver.isAnyOrEquivalent(lhsType) || this.resolver.isAnyOrEquivalent(rhsType)) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } else if (rhsType === this.semanticInfoChain.numberTypeSymbol && lhsType === this.semanticInfoChain.numberTypeSymbol) { + exprType = this.semanticInfoChain.numberTypeSymbol; + } + + if (exprType) { + if (binaryExpression.nodeType === 39 /* AddAssignmentExpression */) { + var lhsExpression = this.resolveSymbolAndReportDiagnostics(binaryExpression.operand1, false, typeCheckContext.getEnclosingDecl()); + if (!this.isValidLHS(binaryExpression.operand1, lhsExpression)) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 195 /* Invalid_left_hand_side_of_assignment_expression */, null, enclosingDecl); + } + + this.checkAssignability(binaryExpression.operand1, exprType, lhsType, typeCheckContext); + } + } else { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 178 /* Invalid__addition__expression___types_do_not_agree */, null, typeCheckContext.getEnclosingDecl()); + exprType = this.semanticInfoChain.anyTypeSymbol; + } + + return exprType; + }; + + PullTypeChecker.prototype.typeCheckBinaryArithmeticOperation = function (binaryExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.resolveSymbolAndReportDiagnostics(binaryExpression, false, enclosingDecl).getType(); + + var lhsType = this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + var rhsType = this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + var lhsIsFit = this.resolver.isAnyOrEquivalent(lhsType) || lhsType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(lhsType); + var rhsIsFit = this.resolver.isAnyOrEquivalent(rhsType) || rhsType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(rhsType); + + if (!rhsIsFit) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 179 /* The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!lhsIsFit) { + this.postError(binaryExpression.operand2.minChar, binaryExpression.operand2.getLength(), typeCheckContext.scriptName, 180 /* The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type */, null, typeCheckContext.getEnclosingDecl()); + } + + if (rhsIsFit && lhsIsFit) { + switch (binaryExpression.nodeType) { + case 47 /* LeftShiftAssignmentExpression */: + case 48 /* SignedRightShiftAssignmentExpression */: + case 49 /* UnsignedRightShiftAssignmentExpression */: + case 40 /* SubtractAssignmentExpression */: + case 42 /* MultiplyAssignmentExpression */: + case 41 /* DivideAssignmentExpression */: + case 43 /* ModuloAssignmentExpression */: + case 46 /* OrAssignmentExpression */: + case 44 /* AndAssignmentExpression */: + case 45 /* ExclusiveOrAssignmentExpression */: + var lhsExpression = this.resolveSymbolAndReportDiagnostics(binaryExpression.operand1, false, typeCheckContext.getEnclosingDecl()); + if (!this.isValidLHS(binaryExpression.operand1, lhsExpression)) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 195 /* Invalid_left_hand_side_of_assignment_expression */, null, enclosingDecl); + } + + this.checkAssignability(binaryExpression.operand1, rhsType, lhsType, typeCheckContext); + break; + } + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckLogicalNotExpression = function (unaryExpression, typeCheckContext, inContextuallyTypedAssignment) { + this.typeCheckAST(unaryExpression.operand, typeCheckContext, inContextuallyTypedAssignment); + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckUnaryArithmeticOperation = function (unaryExpression, typeCheckContext, inContextuallyTypedAssignment) { + var operandType = this.typeCheckAST(unaryExpression.operand, typeCheckContext, inContextuallyTypedAssignment); + + switch (unaryExpression.nodeType) { + case 26 /* PlusExpression */: + case 27 /* NegateExpression */: + case 72 /* BitwiseNotExpression */: + return this.semanticInfoChain.numberTypeSymbol; + } + + var operandIsFit = this.resolver.isAnyOrEquivalent(operandType) || operandType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(operandType); + + if (!operandIsFit) { + this.postError(unaryExpression.operand.minChar, unaryExpression.operand.getLength(), typeCheckContext.scriptName, 181 /* The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type */, null, typeCheckContext.getEnclosingDecl()); + } + + switch (unaryExpression.nodeType) { + case 76 /* PostIncrementExpression */: + case 74 /* PreIncrementExpression */: + case 77 /* PostDecrementExpression */: + case 75 /* PreDecrementExpression */: + var expression = this.resolveSymbolAndReportDiagnostics(unaryExpression.operand, false, typeCheckContext.getEnclosingDecl()); + if (!this.isValidLHS(unaryExpression.operand, expression)) { + this.postError(unaryExpression.operand.minChar, unaryExpression.operand.getLength(), typeCheckContext.scriptName, 204 /* The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer */, null, typeCheckContext.getEnclosingDecl()); + } + + break; + } + + return operandType; + }; + + PullTypeChecker.prototype.typeCheckElementAccessExpression = function (binaryExpression, typeCheckContext) { + this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(binaryExpression, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckTypeOf = function (ast, typeCheckContext) { + this.typeCheckAST((ast).operand, typeCheckContext, false); + + return this.semanticInfoChain.stringTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckTypeReference = function (typeRef, typeCheckContext) { + if (typeRef.term.nodeType === 12 /* FunctionDeclaration */) { + this.typeCheckFunctionTypeSignature(typeRef.term, typeCheckContext.getEnclosingDecl(), typeCheckContext); + } else if (typeRef.term.nodeType === 14 /* InterfaceDeclaration */) { + this.typeCheckInterfaceTypeReference(typeRef.term, typeCheckContext.getEnclosingDecl(), typeCheckContext); + } else { + var savedResolvingTypeReference = this.context.resolvingTypeReference; + this.context.resolvingTypeReference = true; + var type = this.typeCheckAST(typeRef.term, typeCheckContext, false); + + if (type && !type.isError() && !typeCheckContext.inImportDeclaration) { + if ((type.getKind() & TypeScript.PullElementKind.SomeType) === 0) { + if (type.getKind() & TypeScript.PullElementKind.SomeContainer) { + this.postError(typeRef.minChar, typeRef.getLength(), typeCheckContext.scriptName, 262 /* Type_reference_cannot_refer_to_container__0_ */, [type.toString()], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(typeRef.minChar, typeRef.getLength(), typeCheckContext.scriptName, 263 /* Type_reference_must_refer_to_type */, null, typeCheckContext.getEnclosingDecl()); + } + } + } + + this.context.resolvingTypeReference = savedResolvingTypeReference; + } + + return this.resolveSymbolAndReportDiagnostics(typeRef, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckExportAssignment = function (ast, typeCheckContext) { + return this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckFunctionTypeSignature = function (funcDeclAST, enclosingDecl, typeCheckContext) { + var funcDeclSymbolAndDiagnostics = this.resolver.getSymbolAndDiagnosticsForAST(funcDeclAST); + var funcDeclSymbol = funcDeclSymbolAndDiagnostics && funcDeclSymbolAndDiagnostics.symbol; + if (!funcDeclSymbol) { + funcDeclSymbol = this.resolver.resolveFunctionTypeSignature(funcDeclAST, enclosingDecl, this.context); + } + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + + typeCheckContext.pushEnclosingDecl(functionDecl); + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, false); + typeCheckContext.popEnclosingDecl(); + + var functionSignature = funcDeclSymbol.getKind() === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + var parameters = functionSignature.getParameters(); + for (var i = 0; i < parameters.length; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + + if (funcDeclAST.returnTypeAnnotation) { + var returnType = functionSignature.getReturnType(); + this.checkForResolutionError(returnType, enclosingDecl); + } + + this.typeCheckFunctionOverloads(funcDeclAST, typeCheckContext, functionSignature, [functionSignature]); + return funcDeclSymbol; + }; + + PullTypeChecker.prototype.typeCheckInterfaceTypeReference = function (interfaceAST, enclosingDecl, typeCheckContext) { + var interfaceSymbolAndDiagnostics = this.resolver.getSymbolAndDiagnosticsForAST(interfaceAST); + var interfaceSymbol = interfaceSymbolAndDiagnostics && interfaceSymbolAndDiagnostics.symbol; + if (!interfaceSymbol) { + interfaceSymbol = this.resolver.resolveInterfaceTypeReference(interfaceAST, enclosingDecl, this.context); + } + + var interfaceDecl = typeCheckContext.semanticInfo.getDeclForAST(interfaceAST); + typeCheckContext.pushEnclosingDecl(interfaceDecl); + this.typeCheckAST(interfaceAST.members, typeCheckContext, false); + this.typeCheckMembersAgainstIndexer(interfaceSymbol, typeCheckContext); + typeCheckContext.popEnclosingDecl(); + + return interfaceSymbol; + }; + + PullTypeChecker.prototype.typeCheckConditionalExpression = function (conditionalExpression, typeCheckContext) { + this.typeCheckAST(conditionalExpression.operand1, typeCheckContext, false); + this.typeCheckAST(conditionalExpression.operand2, typeCheckContext, false); + this.typeCheckAST(conditionalExpression.operand3, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(conditionalExpression, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckThrowStatement = function (throwStatement, typeCheckContext) { + this.typeCheckAST(throwStatement.expression, typeCheckContext, false); + + var type = this.resolveSymbolAndReportDiagnostics(throwStatement.expression, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(type, typeCheckContext.getEnclosingDecl()); + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckDeleteExpression = function (unaryExpression, typeCheckContext) { + this.typeCheckAST(unaryExpression.operand, typeCheckContext, false); + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var type = this.resolveSymbolAndReportDiagnostics(unaryExpression, false, enclosingDecl).getType(); + this.checkForResolutionError(type, enclosingDecl); + + return type; + }; + + PullTypeChecker.prototype.typeCheckVoidExpression = function (unaryExpression, typeCheckContext) { + this.typeCheckAST(unaryExpression.operand, typeCheckContext, false); + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var type = this.resolveSymbolAndReportDiagnostics(unaryExpression, false, enclosingDecl).getType(); + this.checkForResolutionError(type, enclosingDecl); + + return type; + }; + + PullTypeChecker.prototype.typeCheckRegExpExpression = function (ast, typeCheckContext) { + var type = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(type, typeCheckContext.getEnclosingDecl()); + return type; + }; + + PullTypeChecker.prototype.typeCheckForStatement = function (forStatement, typeCheckContext) { + this.typeCheckAST(forStatement.init, typeCheckContext, false); + this.typeCheckAST(forStatement.cond, typeCheckContext, false); + this.typeCheckAST(forStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckForInStatement = function (ast, typeCheckContext) { + var forInStatement = ast; + + var rhsType = this.resolver.widenType(this.typeCheckAST(forInStatement.obj, typeCheckContext, false)); + var lval = forInStatement.lval; + + if (lval.nodeType === 18 /* VariableDeclaration */) { + var declaration = forInStatement.lval; + var varDecl = declaration.declarators.members[0]; + + if (varDecl.typeExpr) { + this.postError(lval.minChar, lval.getLength(), typeCheckContext.scriptName, 182 /* Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation */, null, typeCheckContext.getEnclosingDecl()); + } + } + + var varSym = this.resolveSymbolAndReportDiagnostics(forInStatement.lval, false, typeCheckContext.getEnclosingDecl()); + this.checkForResolutionError(varSym.getType(), typeCheckContext.getEnclosingDecl()); + + var isStringOrNumber = varSym.getType() === this.semanticInfoChain.stringTypeSymbol || this.resolver.isAnyOrEquivalent(varSym.getType()); + + var isValidRHS = rhsType && (this.resolver.isAnyOrEquivalent(rhsType) || !rhsType.isPrimitive()); + + if (!isStringOrNumber) { + this.postError(lval.minChar, lval.getLength(), typeCheckContext.scriptName, 183 /* Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_ */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!isValidRHS) { + this.postError(forInStatement.obj.minChar, forInStatement.obj.getLength(), typeCheckContext.scriptName, 184 /* The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter */, null, typeCheckContext.getEnclosingDecl()); + } + + this.typeCheckAST(forInStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckInExpression = function (binaryExpression, typeCheckContext) { + var lhsType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false)); + var rhsType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false)); + + var isStringAnyOrNumber = lhsType.getType() === this.semanticInfoChain.stringTypeSymbol || this.resolver.isAnyOrEquivalent(lhsType.getType()) || this.resolver.isNumberOrEquivalent(lhsType.getType()); + var isValidRHS = rhsType && (this.resolver.isAnyOrEquivalent(rhsType) || !rhsType.isPrimitive()); + + if (!isStringAnyOrNumber) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 185 /* The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_ */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!isValidRHS) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 186 /* The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter */, null, typeCheckContext.getEnclosingDecl()); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckInstanceOfExpression = function (binaryExpression, typeCheckContext) { + var lhsType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false)); + var rhsType = this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + var isValidLHS = lhsType && (this.resolver.isAnyOrEquivalent(lhsType) || !lhsType.isPrimitive()); + var isValidRHS = rhsType && (this.resolver.isAnyOrEquivalent(rhsType) || rhsType.isClass() || this.resolver.typeIsSubtypeOfFunction(rhsType, this.context)); + + if (!isValidLHS) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 187 /* The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!isValidRHS) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 188 /* The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type */, null, typeCheckContext.getEnclosingDecl()); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckParenthesizedExpression = function (parenthesizedExpression, typeCheckContext) { + return this.typeCheckAST(parenthesizedExpression.expression, typeCheckContext, false); + }; + + PullTypeChecker.prototype.typeCheckWhileStatement = function (whileStatement, typeCheckContext) { + this.typeCheckAST(whileStatement.cond, typeCheckContext, false); + this.typeCheckAST(whileStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckDoStatement = function (doStatement, typeCheckContext) { + this.typeCheckAST(doStatement.cond, typeCheckContext, false); + this.typeCheckAST(doStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckIfStatement = function (ifStatement, typeCheckContext) { + this.typeCheckAST(ifStatement.cond, typeCheckContext, false); + this.typeCheckAST(ifStatement.thenBod, typeCheckContext, false); + this.typeCheckAST(ifStatement.elseBod, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckBlock = function (block, typeCheckContext) { + this.typeCheckAST(block.statements, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckVariableDeclaration = function (variableDeclaration, typeCheckContext) { + this.typeCheckAST(variableDeclaration.declarators, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckVariableStatement = function (variableStatement, typeCheckContext) { + this.typeCheckAST(variableStatement.declaration, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckWithStatement = function (withStatement, typeCheckContext) { + this.postError(withStatement.expr.minChar, withStatement.expr.getLength(), typeCheckContext.scriptName, 200 /* All_symbols_within_a__with__block_will_be_resolved_to__any__ */, null, typeCheckContext.getEnclosingDecl()); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckTryStatement = function (tryStatement, typeCheckContext) { + this.typeCheckAST(tryStatement.tryBody, typeCheckContext, false); + this.typeCheckAST(tryStatement.catchClause, typeCheckContext, false); + this.typeCheckAST(tryStatement.finallyBody, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckCatchClause = function (catchClause, typeCheckContext) { + var catchDecl = this.resolver.getDeclForAST(catchClause); + + typeCheckContext.pushEnclosingDecl(catchDecl); + this.typeCheckAST(catchClause.body, typeCheckContext, false); + typeCheckContext.popEnclosingDecl(); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckReturnStatement = function (returnAST, typeCheckContext) { + typeCheckContext.setEnclosingDeclHasReturn(); + + var returnExpr = returnAST.returnExpression; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var inContextuallyTypedAssignment = false; + var enclosingDeclAST; + + if (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction) { + enclosingDeclAST = this.resolver.getASTForDecl(enclosingDecl); + if (enclosingDeclAST.returnTypeAnnotation) { + var returnTypeAnnotationSymbol = this.resolver.resolveTypeReference(enclosingDeclAST.returnTypeAnnotation, enclosingDecl, this.context).symbol; + if (returnTypeAnnotationSymbol) { + inContextuallyTypedAssignment = true; + this.context.pushContextualType(returnTypeAnnotationSymbol, this.context.inProvisionalResolution(), null); + } + } else { + var currentContextualType = this.context.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var currentContextualTypeSignatureSymbol = currentContextualType.getDeclarations()[0].getSignatureSymbol(); + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.getReturnType(); + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + this.context.pushContextualType(currentContextualTypeReturnTypeSymbol, this.context.inProvisionalResolution(), null); + } + } + } + } + + var returnType = this.typeCheckAST(returnExpr, typeCheckContext, inContextuallyTypedAssignment); + + if (inContextuallyTypedAssignment) { + this.context.popContextualType(); + } + + if (enclosingDecl.getKind() === 524288 /* SetAccessor */ && returnExpr) { + this.postError(returnExpr.minChar, returnExpr.getLength(), typeCheckContext.scriptName, 189 /* Setters_cannot_return_a_value */, null, typeCheckContext.getEnclosingDecl()); + } + + if (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction) { + enclosingDeclAST = this.resolver.getASTForDecl(enclosingDecl); + + if (enclosingDeclAST.returnTypeAnnotation) { + var signatureSymbol = enclosingDecl.getSignatureSymbol(); + var sigReturnType = signatureSymbol.getReturnType(); + + if (returnType && sigReturnType) { + var comparisonInfo = new TypeComparisonInfo(); + var upperBound = null; + + if (returnType.isTypeParameter()) { + upperBound = (returnType).getConstraint(); + + if (upperBound) { + returnType = upperBound; + } + } + + if (sigReturnType.isTypeParameter()) { + upperBound = (sigReturnType).getConstraint(); + + if (upperBound) { + sigReturnType = upperBound; + } + } + + if (!returnType.isResolved()) { + this.resolver.resolveDeclaredSymbol(returnType, enclosingDecl, this.context); + } + + if (!sigReturnType.isResolved()) { + this.resolver.resolveDeclaredSymbol(sigReturnType, enclosingDecl, this.context); + } + + var isAssignable = this.resolver.sourceIsAssignableToTarget(returnType, sigReturnType, this.context, comparisonInfo); + + if (!isAssignable) { + if (comparisonInfo.message) { + this.postError(returnExpr.minChar, returnExpr.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [returnType.toString(), sigReturnType.toString(), comparisonInfo.message], enclosingDecl); + } else { + this.postError(returnExpr.minChar, returnExpr.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [returnType.toString(), sigReturnType.toString()], enclosingDecl); + } + } + } + } + } + + return returnType; + }; + + PullTypeChecker.prototype.typeCheckNameExpression = function (ast, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var type = this.resolveSymbolAndReportDiagnostics(ast, false, enclosingDecl).getType(); + this.checkForResolutionError(type, enclosingDecl); + return type; + }; + + PullTypeChecker.prototype.checkForSuperMemberAccess = function (memberAccessExpression, typeCheckContext, resolvedName) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + if (resolvedName) { + if (memberAccessExpression.operand1.nodeType === 30 /* SuperExpression */ && !resolvedName.isError() && resolvedName.getKind() !== 65536 /* Method */) { + this.postError(memberAccessExpression.operand2.minChar, memberAccessExpression.operand2.getLength(), typeCheckContext.scriptName, 232 /* Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword */, [], enclosingDecl); + return true; + } + } + + return false; + }; + + PullTypeChecker.prototype.checkForPrivateMemberAccess = function (memberAccessExpression, typeCheckContext, expressionType, resolvedName) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + if (resolvedName) { + if (resolvedName.hasFlag(2 /* Private */)) { + var memberContainer = resolvedName.getContainer(); + if (memberContainer && memberContainer.getKind() === 33554432 /* ConstructorType */) { + memberContainer = memberContainer.getAssociatedContainerType(); + } + + if (memberContainer && memberContainer.isClass()) { + var containingClass = typeCheckContext.getEnclosingClassDecl(); + if (!containingClass || containingClass.getSymbol() !== memberContainer) { + var name = memberAccessExpression.operand2; + this.postError(name.minChar, name.getLength(), typeCheckContext.scriptName, 175 /* _0_1__is_inaccessible */, [memberContainer.toString(false), name.actualText], enclosingDecl); + return true; + } + } + } + } + + return false; + }; + + PullTypeChecker.prototype.checkForStaticMemberAccess = function (memberAccessExpression, typeCheckContext, expressionType, resolvedName) { + if (expressionType && resolvedName && !resolvedName.isError()) { + if (expressionType.isClass() || expressionType.getKind() === 33554432 /* ConstructorType */) { + var name = memberAccessExpression.operand2; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + if (resolvedName.hasFlag(16 /* Static */) || this.resolver.isPrototypeMember(memberAccessExpression, enclosingDecl, this.context)) { + if (expressionType.getKind() !== 33554432 /* ConstructorType */) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + this.postError(name.minChar, name.getLength(), typeCheckContext.scriptName, 221 /* Static_member_cannot_be_accessed_off_an_instance_variable */, null, enclosingDecl); + return true; + } + } + } + } + + return false; + }; + + PullTypeChecker.prototype.typeCheckMemberAccessExpression = function (memberAccessExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var resolvedName = this.resolveSymbolAndReportDiagnostics(memberAccessExpression, false, enclosingDecl); + var type = resolvedName.getType(); + + this.checkForResolutionError(type, enclosingDecl); + var prevCanUseTypeSymbol = this.context.canUseTypeSymbol; + this.context.canUseTypeSymbol = true; + var expressionType = this.typeCheckAST(memberAccessExpression.operand1, typeCheckContext, false); + this.context.canUseTypeSymbol = prevCanUseTypeSymbol; + + this.checkForSuperMemberAccess(memberAccessExpression, typeCheckContext, resolvedName) || this.checkForPrivateMemberAccess(memberAccessExpression, typeCheckContext, expressionType, resolvedName) || this.checkForStaticMemberAccess(memberAccessExpression, typeCheckContext, expressionType, resolvedName); + + return type; + }; + + PullTypeChecker.prototype.typeCheckSwitchStatement = function (switchStatement, typeCheckContext) { + this.typeCheckAST(switchStatement.val, typeCheckContext, false); + this.typeCheckAST(switchStatement.caseList, typeCheckContext, false); + this.typeCheckAST(switchStatement.defaultCase, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckExpressionStatement = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + return this.typeCheckAST(ast.expression, typeCheckContext, inContextuallyTypedAssignment); + }; + + PullTypeChecker.prototype.typeCheckCaseClause = function (caseClause, typeCheckContext) { + this.typeCheckAST(caseClause.expr, typeCheckContext, false); + this.typeCheckAST(caseClause.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckLabeledStatement = function (labeledStatement, typeCheckContext) { + return this.typeCheckAST(labeledStatement.statement, typeCheckContext, false); + }; + + PullTypeChecker.prototype.checkTypePrivacy = function (declSymbol, typeSymbol, typeCheckContext, privacyErrorReporter) { + if (!typeSymbol || typeSymbol.getKind() === 2 /* Primitive */) { + return; + } + + if (typeSymbol.isArray()) { + this.checkTypePrivacy(declSymbol, (typeSymbol).getElementType(), typeCheckContext, privacyErrorReporter); + return; + } + + if (!typeSymbol.isNamedTypeSymbol()) { + var members = typeSymbol.getMembers(); + for (var i = 0; i < members.length; i++) { + this.checkTypePrivacy(declSymbol, members[i].getType(), typeCheckContext, privacyErrorReporter); + } + + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), typeCheckContext, privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), typeCheckContext, privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), typeCheckContext, privacyErrorReporter); + + return; + } + + if (declSymbol.isExternallyVisible()) { + var typeSymbolIsVisible = typeSymbol.isExternallyVisible(); + + if (typeSymbolIsVisible) { + var typeSymbolPath = typeSymbol.pathToRoot(); + if (typeSymbolPath.length && typeSymbolPath[typeSymbolPath.length - 1].getKind() === 32 /* DynamicModule */) { + var declSymbolPath = declSymbol.pathToRoot(); + if (declSymbolPath.length && declSymbolPath[declSymbolPath.length - 1] != typeSymbolPath[typeSymbolPath.length - 1]) { + typeSymbolIsVisible = false; + for (var i = typeSymbolPath.length - 1; i >= 0; i--) { + var aliasSymbol = typeSymbolPath[i].getAliasedSymbol(declSymbol); + if (aliasSymbol) { + TypeScript.CompilerDiagnostics.assert(aliasSymbol.getKind() === 256 /* TypeAlias */, "dynamic module need to be referenced by type alias"); + (aliasSymbol).setIsTypeUsedExternally(); + typeSymbolIsVisible = true; + break; + } + } + } + } + } + + if (!typeSymbolIsVisible) { + privacyErrorReporter(typeSymbol); + } + } + }; + + PullTypeChecker.prototype.checkTypePrivacyOfSignatures = function (declSymbol, signatures, typeCheckContext, privacyErrorReporter) { + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (signatures.length && signature.isDefinition()) { + continue; + } + + var typeParams = signature.getTypeParameters(); + for (var j = 0; j < typeParams.length; j++) { + this.checkTypePrivacy(declSymbol, typeParams[j], typeCheckContext, privacyErrorReporter); + } + + var params = signature.getParameters(); + for (var j = 0; j < params.length; j++) { + var paramType = params[j].getType(); + this.checkTypePrivacy(declSymbol, paramType, typeCheckContext, privacyErrorReporter); + } + + var returnType = signature.getReturnType(); + this.checkTypePrivacy(declSymbol, returnType, typeCheckContext, privacyErrorReporter); + } + }; + + PullTypeChecker.prototype.baseListPrivacyErrorReporter = function (declAST, declSymbol, baseAst, isExtendedType, typeSymbol, typeCheckContext) { + var decl = this.resolver.getDeclForAST(declAST); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var messageCode; + var messageArguments; + + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (declAST.nodeType === 13 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = 90 /* Exported_class__0__extends_class_from_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 91 /* Exported_class__0__implements_interface_from_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 92 /* Exported_interface__0__extends_interface_from_inaccessible_module__1_ */; + messageArguments = [declSymbol.getDisplayName(), typeSymbolName]; + } + } else { + if (declAST.nodeType === 13 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = 87 /* Exported_class__0__extends_private_class__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 88 /* Exported_class__0__implements_private_interface__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 89 /* Exported_interface__0__extends_private_interface__1_ */; + messageArguments = [declSymbol.getDisplayName(), typeSymbolName]; + } + } + + this.context.postError(typeCheckContext.scriptName, baseAst.minChar, baseAst.getLength(), messageCode, messageArguments, enclosingDecl, true); + }; + + PullTypeChecker.prototype.variablePrivacyErrorReporter = function (declSymbol, typeSymbol, typeCheckContext) { + var declAST = this.resolver.getASTForSymbol(declSymbol); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var isProperty = declSymbol.getKind() === 4096 /* Property */; + var isPropertyOfClass = false; + var declParent = declSymbol.getContainer(); + if (declParent && (declParent.getKind() === 8 /* Class */ || declParent.getKind() === 32768 /* ConstructorMethod */)) { + isPropertyOfClass = true; + } + + var messageCode; + var messageArguments; + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declSymbol.hasFlag(16 /* Static */)) { + messageCode = 97 /* Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = 98 /* Public_property__0__of__exported_class_is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 99 /* Property__0__of__exported_interface_is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 100 /* Exported_variable__0__is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + if (declSymbol.hasFlag(16 /* Static */)) { + messageCode = 93 /* Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = 94 /* Public_property__0__of__exported_class_has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 95 /* Property__0__of__exported_interface_has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 96 /* Exported_variable__0__has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } + + this.context.postError(typeCheckContext.scriptName, declAST.minChar, declAST.getLength(), messageCode, messageArguments, enclosingDecl, true); + }; + + PullTypeChecker.prototype.checkFunctionTypePrivacy = function (funcDeclAST, inContextuallyTypedAssignment, typeCheckContext) { + var _this = this; + if (inContextuallyTypedAssignment || (funcDeclAST.getFunctionFlags() & 8192 /* IsFunctionExpression */) || (funcDeclAST.getFunctionFlags() & 16384 /* IsFunctionProperty */)) { + return; + } + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + ; + var functionSignature; + + var isGetter = funcDeclAST.isGetAccessor(); + var isSetter = funcDeclAST.isSetAccessor(); + + if (isGetter || isSetter) { + var accessorSymbol = functionSymbol; + functionSignature = (isGetter ? accessorSymbol.getGetter() : accessorSymbol.getSetter()).getType().getCallSignatures()[0]; + } else { + if (!functionSymbol) { + var parentDecl = functionDecl.getParentDecl(); + functionSymbol = parentDecl.getSymbol(); + if (functionSymbol && functionSymbol.isType() && !(functionSymbol).isNamedTypeSymbol()) { + return; + } + } else if (functionSymbol.getKind() == 65536 /* Method */ && !functionSymbol.getContainer().isNamedTypeSymbol()) { + return; + } + functionSignature = functionDecl.getSignatureSymbol(); + } + + if (!isGetter) { + var funcParams = functionSignature.getParameters(); + for (var i = 0; i < funcParams.length; i++) { + this.checkTypePrivacy(functionSymbol, funcParams[i].getType(), typeCheckContext, function (typeSymbol) { + return _this.functionArgumentTypePrivacyErrorReporter(funcDeclAST, i, funcParams[i], typeSymbol, typeCheckContext); + }); + } + } + + if (!isSetter) { + this.checkTypePrivacy(functionSymbol, functionSignature.getReturnType(), typeCheckContext, function (typeSymbol) { + return _this.functionReturnTypePrivacyErrorReporter(funcDeclAST, functionSignature.getReturnType(), typeSymbol, typeCheckContext); + }); + } + }; + + PullTypeChecker.prototype.functionArgumentTypePrivacyErrorReporter = function (declAST, argIndex, paramSymbol, typeSymbol, typeCheckContext) { + var decl = this.resolver.getDeclForAST(declAST); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var isGetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 32 /* GetAccessor */); + var isSetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 64 /* SetAccessor */); + var isStatic = (decl.getFlags() & 16 /* Static */) === 16 /* Static */; + var isMethod = decl.getKind() === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.getKind() === 8 /* Class */ || declParent.getKind() === 32768 /* ConstructorMethod */)) { + isMethodOfClass = true; + } + + var start = declAST.arguments.members[argIndex].minChar; + var length = declAST.arguments.members[argIndex].getLength(); + + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declAST.isConstructor) { + this.context.postError(typeCheckContext.scriptName, start, length, 110 /* Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isSetter) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 111 /* Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 112 /* Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (declAST.isConstructMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 113 /* Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (declAST.isCallMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 114 /* Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethod) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 115 /* Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethodOfClass) { + this.context.postError(typeCheckContext.scriptName, start, length, 116 /* Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 117 /* Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (!isGetter) { + this.context.postError(typeCheckContext.scriptName, start, length, 118 /* Parameter__0__of_exported_function_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else { + if (declAST.isConstructor) { + this.context.postError(typeCheckContext.scriptName, start, length, 101 /* Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isSetter) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 102 /* Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 103 /* Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (declAST.isConstructMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 104 /* Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (declAST.isCallMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 105 /* Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethod) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 106 /* Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethodOfClass) { + this.context.postError(typeCheckContext.scriptName, start, length, 107 /* Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 108 /* Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (!isGetter && !declAST.isIndexerMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 109 /* Parameter__0__of_exported_function_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } + }; + + PullTypeChecker.prototype.functionReturnTypePrivacyErrorReporter = function (declAST, funcReturnType, typeSymbol, typeCheckContext) { + var _this = this; + var decl = this.resolver.getDeclForAST(declAST); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var isGetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 32 /* GetAccessor */); + var isSetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 64 /* SetAccessor */); + var isStatic = (decl.getFlags() & 16 /* Static */) === 16 /* Static */; + var isMethod = decl.getKind() === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.getKind() === 8 /* Class */ || declParent.getKind() === 32768 /* ConstructorMethod */)) { + isMethodOfClass = true; + } + + var messageCode = null; + var messageArguments; + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (isGetter) { + if (isStatic) { + messageCode = 128 /* Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 129 /* Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (declAST.isConstructMember()) { + messageCode = 130 /* Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isCallMember()) { + messageCode = 131 /* Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isIndexerMember()) { + messageCode = 132 /* Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethod) { + if (isStatic) { + messageCode = 133 /* Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethodOfClass) { + messageCode = 134 /* Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 135 /* Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (!isSetter && !declAST.isConstructor) { + messageCode = 136 /* Return_type_of_exported_function_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } + } else { + if (isGetter) { + if (isStatic) { + messageCode = 119 /* Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 120 /* Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (declAST.isConstructMember()) { + messageCode = 121 /* Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isCallMember()) { + messageCode = 122 /* Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isIndexerMember()) { + messageCode = 123 /* Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethod) { + if (isStatic) { + messageCode = 124 /* Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethodOfClass) { + messageCode = 125 /* Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 126 /* Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (!isSetter && !declAST.isConstructor) { + messageCode = 127 /* Return_type_of_exported_function_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } + } + + if (messageCode) { + var reportOnFuncDecl = false; + var contextForReturnTypeResolution = new TypeScript.PullTypeResolutionContext(); + if (declAST.returnTypeAnnotation) { + var returnExpressionSymbolAndDiagnostics = this.resolver.resolveTypeReference(declAST.returnTypeAnnotation, decl, contextForReturnTypeResolution); + var returnExpressionSymbol = returnExpressionSymbolAndDiagnostics && returnExpressionSymbolAndDiagnostics.symbol; + if (returnExpressionSymbol === funcReturnType) { + this.context.postError(typeCheckContext.scriptName, declAST.returnTypeAnnotation.minChar, declAST.returnTypeAnnotation.getLength(), messageCode, messageArguments, enclosingDecl, true); + } + } + + if (declAST.block) { + var reportErrorOnReturnExpressions = function (ast, parent, walker) { + var go = true; + switch (ast.nodeType) { + case 12 /* FunctionDeclaration */: + go = false; + break; + + case 93 /* ReturnStatement */: + var returnStatement = ast; + var returnExpressionSymbol = _this.resolver.resolveAST(returnStatement.returnExpression, false, decl, contextForReturnTypeResolution).symbol.getType(); + + if (returnExpressionSymbol === funcReturnType) { + _this.context.postError(typeCheckContext.scriptName, returnStatement.minChar, returnStatement.getLength(), messageCode, messageArguments, enclosingDecl, true); + } else { + reportOnFuncDecl = true; + } + go = false; + break; + + default: + break; + } + + walker.options.goChildren = go; + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(declAST.block, reportErrorOnReturnExpressions); + } + + if (reportOnFuncDecl) { + this.context.postError(typeCheckContext.scriptName, declAST.minChar, declAST.getLength(), messageCode, messageArguments, enclosingDecl, true); + } + } + }; + PullTypeChecker.globalPullTypeCheckPhase = 0; + return PullTypeChecker; + })(); + TypeScript.PullTypeChecker = PullTypeChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullDeclEdit) { + PullDeclEdit[PullDeclEdit["NoChanges"] = 0] = "NoChanges"; + PullDeclEdit[PullDeclEdit["DeclAdded"] = 1] = "DeclAdded"; + PullDeclEdit[PullDeclEdit["DeclRemoved"] = 2] = "DeclRemoved"; + PullDeclEdit[PullDeclEdit["DeclChanged"] = 3] = "DeclChanged"; + })(TypeScript.PullDeclEdit || (TypeScript.PullDeclEdit = {})); + var PullDeclEdit = TypeScript.PullDeclEdit; + + var PullDeclDiff = (function () { + function PullDeclDiff(oldDecl, newDecl, kind) { + this.oldDecl = oldDecl; + this.newDecl = newDecl; + this.kind = kind; + } + return PullDeclDiff; + })(); + TypeScript.PullDeclDiff = PullDeclDiff; + + var PullDeclDiffer = (function () { + function PullDeclDiffer(oldSemanticInfo, newSemanticInfo) { + this.oldSemanticInfo = oldSemanticInfo; + this.newSemanticInfo = newSemanticInfo; + this.differences = []; + } + PullDeclDiffer.diffDecls = function (oldDecl, oldSemanticInfo, newDecl, newSemanticInfo) { + var declDiffer = new PullDeclDiffer(oldSemanticInfo, newSemanticInfo); + declDiffer.diff(oldDecl, newDecl); + return declDiffer.differences; + }; + + PullDeclDiffer.prototype.diff = function (oldDecl, newDecl) { + TypeScript.Debug.assert(oldDecl.getName() === newDecl.getName()); + TypeScript.Debug.assert(oldDecl.getKind() === newDecl.getKind()); + + var oldAST = this.oldSemanticInfo.getASTForDecl(oldDecl); + var newAST = this.newSemanticInfo.getASTForDecl(newDecl); + TypeScript.Debug.assert(oldAST !== undefined); + TypeScript.Debug.assert(newAST !== undefined); + + if (oldAST === newAST) { + return; + } + + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclTypeCache, newDecl.childDeclTypeCache); + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclTypeParameterCache, newDecl.childDeclTypeParameterCache); + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclValueCache, newDecl.childDeclValueCache); + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclNamespaceCache, newDecl.childDeclNamespaceCache); + + if (!this.isEquivalent(oldAST, newAST)) { + this.differences.push(new PullDeclDiff(oldDecl, newDecl, 3 /* DeclChanged */)); + } + }; + + PullDeclDiffer.prototype.diff1 = function (oldDecl, newDecl, oldAST, newAST, oldNameToDecls, newNameToDecls) { + var oldChildrenOfName; + var newChildrenOfName; + var oldChild; + var newChild; + + for (var name in oldNameToDecls) { + oldChildrenOfName = oldNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + newChildrenOfName = newNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + + for (var i = 0, n = oldChildrenOfName.length; i < n; i++) { + oldChild = oldChildrenOfName[i]; + + switch (oldChild.getKind()) { + case 131072 /* FunctionExpression */: + case 512 /* ObjectLiteral */: + case 8388608 /* ObjectType */: + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + continue; + } + + if (i < newChildrenOfName.length) { + newChild = newChildrenOfName[i]; + + if (oldChild.getKind() === newChild.getKind()) { + this.diff(oldChild, newChildrenOfName[i]); + } else { + this.differences.push(new PullDeclDiff(oldChild, null, 2 /* DeclRemoved */)); + this.differences.push(new PullDeclDiff(oldDecl, newChild, 1 /* DeclAdded */)); + } + } else { + this.differences.push(new PullDeclDiff(oldChild, null, 2 /* DeclRemoved */)); + } + } + } + + for (var name in newNameToDecls) { + oldChildrenOfName = oldNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + newChildrenOfName = newNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + + for (var i = oldChildrenOfName.length, n = newChildrenOfName.length; i < n; i++) { + newChild = newChildrenOfName[i]; + this.differences.push(new PullDeclDiff(oldDecl, newChild, 1 /* DeclAdded */)); + } + } + }; + + PullDeclDiffer.prototype.isEquivalent = function (oldAST, newAST) { + TypeScript.Debug.assert(oldAST !== null); + TypeScript.Debug.assert(newAST !== null); + TypeScript.Debug.assert(oldAST !== newAST); + + if (oldAST.nodeType !== newAST.nodeType || oldAST.getFlags() !== newAST.getFlags()) { + return false; + } + + switch (oldAST.nodeType) { + case 16 /* ImportDeclaration */: + return this.importDeclarationIsEquivalent(oldAST, newAST); + case 15 /* ModuleDeclaration */: + return this.moduleDeclarationIsEquivalent(oldAST, newAST); + case 13 /* ClassDeclaration */: + return this.classDeclarationIsEquivalent(oldAST, newAST); + case 14 /* InterfaceDeclaration */: + return this.interfaceDeclarationIsEquivalent(oldAST, newAST); + case 19 /* Parameter */: + return this.argumentDeclarationIsEquivalent(oldAST, newAST); + case 17 /* VariableDeclarator */: + return this.variableDeclarationIsEquivalent(oldAST, newAST); + case 9 /* TypeParameter */: + return this.typeParameterIsEquivalent(oldAST, newAST); + case 12 /* FunctionDeclaration */: + return this.functionDeclarationIsEquivalent(oldAST, newAST); + case 101 /* CatchClause */: + return this.catchClauseIsEquivalent(oldAST, newAST); + case 99 /* WithStatement */: + return this.withStatementIsEquivalent(oldAST, newAST); + case 2 /* Script */: + return this.scriptIsEquivalent(oldAST, newAST); + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PullDeclDiffer.prototype.importDeclarationIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.alias, decl2.alias); + }; + + PullDeclDiffer.prototype.typeDeclarationIsEquivalent = function (decl1, decl2) { + return decl1.getVarFlags() === decl2.getVarFlags() && TypeScript.structuralEqualsNotIncludingPosition(decl1.typeParameters, decl2.typeParameters) && TypeScript.structuralEqualsNotIncludingPosition(decl1.extendsList, decl2.extendsList) && TypeScript.structuralEqualsNotIncludingPosition(decl1.implementsList, decl2.implementsList); + }; + + PullDeclDiffer.prototype.classDeclarationIsEquivalent = function (decl1, decl2) { + return this.typeDeclarationIsEquivalent(decl1, decl2); + }; + + PullDeclDiffer.prototype.interfaceDeclarationIsEquivalent = function (decl1, decl2) { + return this.typeDeclarationIsEquivalent(decl1, decl2); + }; + + PullDeclDiffer.prototype.typeParameterIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.constraint, decl2.constraint); + }; + + PullDeclDiffer.prototype.boundDeclarationIsEquivalent = function (decl1, decl2) { + if (decl1.getVarFlags() === decl2.getVarFlags() && TypeScript.structuralEqualsNotIncludingPosition(decl1.typeExpr, decl2.typeExpr)) { + if (decl1.typeExpr === null) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.init, decl2.init); + } else { + return true; + } + } + + return false; + }; + + PullDeclDiffer.prototype.argumentDeclarationIsEquivalent = function (decl1, decl2) { + return this.boundDeclarationIsEquivalent(decl1, decl2) && decl1.isOptional === decl2.isOptional; + }; + + PullDeclDiffer.prototype.variableDeclarationIsEquivalent = function (decl1, decl2) { + return this.boundDeclarationIsEquivalent(decl1, decl2); + }; + + PullDeclDiffer.prototype.functionDeclarationIsEquivalent = function (decl1, decl2) { + if (decl1.hint === decl2.hint && decl1.getFunctionFlags() === decl2.getFunctionFlags() && decl1.variableArgList === decl2.variableArgList && decl1.isConstructor === decl2.isConstructor && TypeScript.structuralEqualsNotIncludingPosition(decl1.returnTypeAnnotation, decl2.returnTypeAnnotation) && TypeScript.structuralEqualsNotIncludingPosition(decl1.typeArguments, decl2.typeArguments) && TypeScript.structuralEqualsNotIncludingPosition(decl1.arguments, decl2.arguments)) { + if (decl1.returnTypeAnnotation === null) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.block, decl2.block); + } else { + return true; + } + } + + return false; + }; + + PullDeclDiffer.prototype.catchClauseIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.param, decl2.param) && TypeScript.structuralEqualsNotIncludingPosition(decl1.body, decl2.body); + }; + + PullDeclDiffer.prototype.withStatementIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.expr, decl2.expr) && TypeScript.structuralEqualsNotIncludingPosition(decl1.body, decl2.body); + }; + + PullDeclDiffer.prototype.scriptIsEquivalent = function (decl1, decl2) { + return true; + }; + + PullDeclDiffer.prototype.moduleDeclarationIsEquivalent = function (decl1, decl2) { + return decl1.getModuleFlags() === decl2.getModuleFlags() && decl2.prettyName === decl2.prettyName && TypeScript.ArrayUtilities.sequenceEquals(decl1.amdDependencies, decl2.amdDependencies, TypeScript.StringUtilities.stringEquals); + }; + PullDeclDiffer.emptyDeclArray = []; + return PullDeclDiffer; + })(); + TypeScript.PullDeclDiffer = PullDeclDiffer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.declCacheHit = 0; + TypeScript.declCacheMiss = 0; + TypeScript.symbolCacheHit = 0; + TypeScript.symbolCacheMiss = 0; + + var SemanticInfo = (function () { + function SemanticInfo(compilationUnitPath) { + this.topLevelDecls = []; + this.topLevelSynthesizedDecls = []; + this.astDeclMap = new TypeScript.DataMap(); + this.declASTMap = new TypeScript.DataMap(); + this.syntaxElementDeclMap = new TypeScript.DataMap(); + this.declSyntaxElementMap = new TypeScript.DataMap(); + this.astSymbolMap = new TypeScript.DataMap(); + this.symbolASTMap = new TypeScript.DataMap(); + this.syntaxElementSymbolMap = new TypeScript.DataMap(); + this.symbolSyntaxElementMap = new TypeScript.DataMap(); + this.properties = new SemanticInfoProperties(); + this.hasBeenTypeChecked = false; + this.compilationUnitPath = compilationUnitPath; + } + SemanticInfo.prototype.addTopLevelDecl = function (decl) { + this.topLevelDecls[this.topLevelDecls.length] = decl; + }; + + SemanticInfo.prototype.setTypeChecked = function () { + this.hasBeenTypeChecked = true; + }; + SemanticInfo.prototype.getTypeChecked = function () { + return this.hasBeenTypeChecked; + }; + SemanticInfo.prototype.invalidate = function () { + this.astSymbolMap = new TypeScript.DataMap(); + this.symbolASTMap = new TypeScript.DataMap(); + }; + + SemanticInfo.prototype.getTopLevelDecls = function () { + return this.topLevelDecls; + }; + + SemanticInfo.prototype.getPath = function () { + return this.compilationUnitPath; + }; + + SemanticInfo.prototype.addSynthesizedDecl = function (decl) { + this.topLevelSynthesizedDecls[this.topLevelSynthesizedDecls.length] = decl; + }; + SemanticInfo.prototype.getSynthesizedDecls = function () { + return this.topLevelSynthesizedDecls; + }; + + SemanticInfo.prototype.getDeclForAST = function (ast) { + return this.astDeclMap.read(ast.getID().toString()); + }; + + SemanticInfo.prototype.setDeclForAST = function (ast, decl) { + this.astDeclMap.link(ast.getID().toString(), decl); + }; + + SemanticInfo.prototype.getDeclKey = function (decl) { + var decl1 = decl; + + if (!decl1.__declKey) { + decl1.__declKey = decl.getDeclID().toString() + "-" + decl.getKind().toString(); + } + + return decl1.__declKey; + }; + + SemanticInfo.prototype.getASTForDecl = function (decl) { + return this.declASTMap.read(this.getDeclKey(decl)); + }; + + SemanticInfo.prototype.setASTForDecl = function (decl, ast) { + this.declASTMap.link(this.getDeclKey(decl), ast); + }; + + SemanticInfo.prototype.setSymbolAndDiagnosticsForAST = function (ast, symbolAndDiagnostics) { + this.astSymbolMap.link(ast.getID().toString(), symbolAndDiagnostics); + this.symbolASTMap.link(symbolAndDiagnostics.symbol.getSymbolID().toString(), ast); + }; + + SemanticInfo.prototype.getSymbolAndDiagnosticsForAST = function (ast) { + return this.astSymbolMap.read(ast.getID().toString()); + }; + + SemanticInfo.prototype.getASTForSymbol = function (symbol) { + return this.symbolASTMap.read(symbol.getSymbolID().toString()); + }; + + SemanticInfo.prototype.getSyntaxElementForDecl = function (decl) { + return this.declSyntaxElementMap.read(this.getDeclKey(decl)); + }; + + SemanticInfo.prototype.setSyntaxElementForDecl = function (decl, syntaxElement) { + this.declSyntaxElementMap.link(this.getDeclKey(decl), syntaxElement); + }; + + SemanticInfo.prototype.getDeclForSyntaxElement = function (syntaxElement) { + return this.syntaxElementDeclMap.read(TypeScript.Collections.identityHashCode(syntaxElement).toString()); + }; + + SemanticInfo.prototype.setDeclForSyntaxElement = function (syntaxElement, decl) { + this.syntaxElementDeclMap.link(TypeScript.Collections.identityHashCode(syntaxElement).toString(), decl); + }; + + SemanticInfo.prototype.getSyntaxElementForSymbol = function (symbol) { + return this.symbolSyntaxElementMap.read(symbol.getSymbolID().toString()); + }; + + SemanticInfo.prototype.getSymbolForSyntaxElement = function (syntaxElement) { + return this.syntaxElementSymbolMap.read(TypeScript.Collections.identityHashCode(syntaxElement).toString()); + }; + + SemanticInfo.prototype.setSymbolForSyntaxElement = function (syntaxElement, symbol) { + this.syntaxElementSymbolMap.link(TypeScript.Collections.identityHashCode(syntaxElement).toString(), symbol); + this.symbolSyntaxElementMap.link(symbol.getSymbolID().toString(), syntaxElement); + }; + + SemanticInfo.prototype.getDiagnostics = function (semanticErrors) { + for (var i = 0; i < this.topLevelDecls.length; i++) { + TypeScript.getDiagnosticsFromEnclosingDecl(this.topLevelDecls[i], semanticErrors); + } + }; + + SemanticInfo.prototype.getProperties = function () { + return this.properties; + }; + return SemanticInfo; + })(); + TypeScript.SemanticInfo = SemanticInfo; + + var SemanticInfoProperties = (function () { + function SemanticInfoProperties() { + this.unitContainsBool = false; + } + return SemanticInfoProperties; + })(); + TypeScript.SemanticInfoProperties = SemanticInfoProperties; + + var SemanticInfoChain = (function () { + function SemanticInfoChain() { + this.units = [new SemanticInfo("")]; + this.declCache = new TypeScript.BlockIntrinsics(); + this.symbolCache = new TypeScript.BlockIntrinsics(); + this.unitCache = new TypeScript.BlockIntrinsics(); + this.declSymbolMap = new TypeScript.DataMap(); + this.anyTypeSymbol = null; + this.booleanTypeSymbol = null; + this.numberTypeSymbol = null; + this.stringTypeSymbol = null; + this.nullTypeSymbol = null; + this.undefinedTypeSymbol = null; + this.elementTypeSymbol = null; + this.voidTypeSymbol = null; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this; + } + + var globalDecl = this.getGlobalDecl(); + var globalInfo = this.units[0]; + globalInfo.addTopLevelDecl(globalDecl); + } + SemanticInfoChain.prototype.addPrimitiveType = function (name, globalDecl) { + var span = new TypeScript.TextSpan(0, 0); + var decl = new TypeScript.PullDecl(name, name, 2 /* Primitive */, 0 /* None */, span, ""); + var symbol = new TypeScript.PullPrimitiveTypeSymbol(name); + + symbol.addDeclaration(decl); + decl.setSymbol(symbol); + + symbol.setResolved(); + + if (globalDecl) { + globalDecl.addChildDecl(decl); + } + + return symbol; + }; + + SemanticInfoChain.prototype.addPrimitiveValue = function (name, type, globalDecl) { + var span = new TypeScript.TextSpan(0, 0); + var decl = new TypeScript.PullDecl(name, name, 1024 /* Variable */, 8 /* Ambient */, span, ""); + var symbol = new TypeScript.PullSymbol(name, 1024 /* Variable */); + + symbol.addDeclaration(decl); + decl.setSymbol(symbol); + symbol.setType(type); + symbol.setResolved(); + + globalDecl.addChildDecl(decl); + }; + + SemanticInfoChain.prototype.getGlobalDecl = function () { + var span = new TypeScript.TextSpan(0, 0); + var globalDecl = new TypeScript.PullDecl("", "", 0 /* Global */, 0 /* None */, span, ""); + + this.anyTypeSymbol = this.addPrimitiveType("any", globalDecl); + this.booleanTypeSymbol = this.addPrimitiveType("boolean", globalDecl); + this.numberTypeSymbol = this.addPrimitiveType("number", globalDecl); + this.stringTypeSymbol = this.addPrimitiveType("string", globalDecl); + this.voidTypeSymbol = this.addPrimitiveType("void", globalDecl); + this.elementTypeSymbol = this.addPrimitiveType("_element", globalDecl); + + this.nullTypeSymbol = this.addPrimitiveType("null", null); + this.undefinedTypeSymbol = this.addPrimitiveType("undefined", null); + this.addPrimitiveValue("undefined", this.undefinedTypeSymbol, globalDecl); + this.addPrimitiveValue("null", this.nullTypeSymbol, globalDecl); + + return globalDecl; + }; + + SemanticInfoChain.prototype.addUnit = function (unit) { + this.units[this.units.length] = unit; + this.unitCache[unit.getPath()] = unit; + }; + + SemanticInfoChain.prototype.getUnit = function (compilationUnitPath) { + for (var i = 0; i < this.units.length; i++) { + if (this.units[i].getPath() === compilationUnitPath) { + return this.units[i]; + } + } + + return null; + }; + + SemanticInfoChain.prototype.updateUnit = function (oldUnit, newUnit) { + for (var i = 0; i < this.units.length; i++) { + if (this.units[i].getPath() === oldUnit.getPath()) { + this.units[i] = newUnit; + this.unitCache[oldUnit.getPath()] = newUnit; + return; + } + } + }; + + SemanticInfoChain.prototype.collectAllTopLevelDecls = function () { + var decls = []; + var unitDecls; + + for (var i = 0; i < this.units.length; i++) { + unitDecls = this.units[i].getTopLevelDecls(); + for (var j = 0; j < unitDecls.length; j++) { + decls[decls.length] = unitDecls[j]; + } + } + + return decls; + }; + + SemanticInfoChain.prototype.collectAllSynthesizedDecls = function () { + var decls = []; + var synthDecls; + + for (var i = 0; i < this.units.length; i++) { + synthDecls = this.units[i].getSynthesizedDecls(); + for (var j = 0; j < synthDecls.length; j++) { + decls[decls.length] = synthDecls[j]; + } + } + + return decls; + }; + + SemanticInfoChain.prototype.getDeclPathCacheID = function (declPath, declKind) { + var cacheID = ""; + + for (var i = 0; i < declPath.length; i++) { + cacheID += "#" + declPath[i]; + } + + return cacheID + "#" + declKind.toString(); + }; + + SemanticInfoChain.prototype.findDecls = function (declPath, declKind) { + var cacheID = this.getDeclPathCacheID(declPath, declKind); + + if (declPath.length) { + var cachedDecls = this.declCache[cacheID]; + + if (cachedDecls && cachedDecls.length) { + TypeScript.declCacheHit++; + return cachedDecls; + } + } + + TypeScript.declCacheMiss++; + + var declsToSearch = this.collectAllTopLevelDecls(); + + var decls = []; + var path; + var foundDecls = []; + var keepSearching = (declKind & 4 /* Container */) || (declKind & 16 /* Interface */); + + for (var i = 0; i < declPath.length; i++) { + path = declPath[i]; + decls = []; + + for (var j = 0; j < declsToSearch.length; j++) { + foundDecls = declsToSearch[j].searchChildDecls(path, declKind); + + for (var k = 0; k < foundDecls.length; k++) { + decls[decls.length] = foundDecls[k]; + } + + if (foundDecls.length && !keepSearching) { + break; + } + } + + declsToSearch = decls; + + if (!declsToSearch) { + break; + } + } + + if (decls.length) { + this.declCache[cacheID] = decls; + } + + return decls; + }; + + SemanticInfoChain.prototype.findSymbol = function (declPath, declType) { + var cacheID = this.getDeclPathCacheID(declPath, declType); + + if (declPath.length) { + var cachedSymbol = this.symbolCache[cacheID]; + + if (cachedSymbol) { + TypeScript.symbolCacheHit++; + return cachedSymbol; + } + } + + TypeScript.symbolCacheMiss++; + + var decls = this.findDecls(declPath, declType); + var symbol = null; + + if (decls.length) { + symbol = decls[0].getSymbol(); + + if (symbol) { + this.symbolCache[cacheID] = symbol; + + symbol.addCacheID(cacheID); + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.cacheGlobalSymbol = function (symbol, kind) { + var cacheID1 = this.getDeclPathCacheID([symbol.getName()], kind); + var cacheID2 = this.getDeclPathCacheID([symbol.getName()], symbol.getKind()); + + if (!this.symbolCache[cacheID1]) { + this.symbolCache[cacheID1] = symbol; + symbol.addCacheID(cacheID1); + } + + if (!this.symbolCache[cacheID2]) { + this.symbolCache[cacheID2] = symbol; + symbol.addCacheID(cacheID2); + } + }; + + SemanticInfoChain.prototype.cleanDecl = function (decl) { + decl.setSymbol(null); + decl.setSignatureSymbol(null); + decl.setSpecializingSignatureSymbol(null); + decl.setIsBound(false); + + var children = decl.getChildDecls(); + + for (var i = 0; i < children.length; i++) { + this.cleanDecl(children[i]); + } + + var typeParameters = decl.getTypeParameters(); + + for (var i = 0; i < typeParameters.length; i++) { + this.cleanDecl(typeParameters[i]); + } + + var valueDecl = decl.getValueDecl(); + + if (valueDecl) { + this.cleanDecl(valueDecl); + } + }; + + SemanticInfoChain.prototype.cleanAllDecls = function () { + var topLevelDecls = this.collectAllTopLevelDecls(); + + for (var i = 1; i < topLevelDecls.length; i++) { + this.cleanDecl(topLevelDecls[i]); + } + + var synthesizedDecls = this.collectAllSynthesizedDecls(); + + for (var i = 0; i < synthesizedDecls.length; i++) { + this.cleanDecl(synthesizedDecls[i]); + } + }; + + SemanticInfoChain.prototype.update = function () { + this.declCache = new TypeScript.BlockIntrinsics(); + this.symbolCache = new TypeScript.BlockIntrinsics(); + this.units[0] = new SemanticInfo(""); + this.units[0].addTopLevelDecl(this.getGlobalDecl()); + this.cleanAllDecls(); + + for (var unit in this.unitCache) { + if (this.unitCache[unit]) { + this.unitCache[unit].invalidate(); + } + } + }; + + SemanticInfoChain.prototype.invalidateUnit = function (compilationUnitPath) { + var unit = this.unitCache[compilationUnitPath]; + if (unit) { + unit.invalidate(); + } + }; + + SemanticInfoChain.prototype.getDeclForAST = function (ast, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + return unit.getDeclForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getASTForDecl = function (decl) { + var unit = this.unitCache[decl.getScriptName()]; + + if (unit) { + return unit.getASTForDecl(decl); + } + + return null; + }; + + SemanticInfoChain.prototype.getSymbolAndDiagnosticsForAST = function (ast, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + return unit.getSymbolAndDiagnosticsForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getASTForSymbol = function (symbol, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + return unit.getASTForSymbol(symbol); + } + + return null; + }; + + SemanticInfoChain.prototype.setSymbolAndDiagnosticsForAST = function (ast, symbolAndDiagnostics, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + unit.setSymbolAndDiagnosticsForAST(ast, symbolAndDiagnostics); + } + }; + + SemanticInfoChain.prototype.setSymbolForDecl = function (decl, symbol) { + this.declSymbolMap.link(decl.getDeclID().toString(), symbol); + }; + SemanticInfoChain.prototype.getSymbolForDecl = function (decl) { + return this.declSymbolMap.read(decl.getDeclID().toString()); + }; + + SemanticInfoChain.prototype.removeSymbolFromCache = function (symbol) { + var path = [symbol.getName()]; + var kind = (symbol.getKind() & TypeScript.PullElementKind.SomeType) !== 0 ? TypeScript.PullElementKind.SomeType : TypeScript.PullElementKind.SomeValue; + + var kindID = this.getDeclPathCacheID(path, kind); + var symID = this.getDeclPathCacheID(path, symbol.getKind()); + + symbol.addCacheID(kindID); + symbol.addCacheID(symID); + + symbol.invalidateCachedIDs(this.symbolCache); + }; + + SemanticInfoChain.prototype.postDiagnostics = function () { + var errors = []; + + for (var i = 1; i < this.units.length; i++) { + this.units[i].getDiagnostics(errors); + } + + return errors; + }; + return SemanticInfoChain; + })(); + TypeScript.SemanticInfoChain = SemanticInfoChain; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclCollectionContext = (function () { + function DeclCollectionContext(semanticInfo, scriptName) { + if (typeof scriptName === "undefined") { scriptName = ""; } + this.semanticInfo = semanticInfo; + this.scriptName = scriptName; + this.parentChain = []; + this.foundValueDecl = false; + } + DeclCollectionContext.prototype.getParent = function () { + return this.parentChain ? this.parentChain[this.parentChain.length - 1] : null; + }; + + DeclCollectionContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + } + }; + + DeclCollectionContext.prototype.popParent = function () { + this.parentChain.length--; + }; + return DeclCollectionContext; + })(); + TypeScript.DeclCollectionContext = DeclCollectionContext; + + function preCollectImportDecls(ast, parentAST, context) { + var importDecl = ast; + var declFlags = 0 /* None */; + var span = TypeScript.TextSpan.fromBounds(importDecl.minChar, importDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(importDecl.id.text, importDecl.id.actualText, 256 /* TypeAlias */, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + return false; + } + TypeScript.preCollectImportDecls = preCollectImportDecls; + + function preCollectModuleDecls(ast, parentAST, context) { + var moduleDecl = ast; + var declFlags = 0 /* None */; + var modName = (moduleDecl.name).text; + var isDynamic = TypeScript.isQuoted(modName) || TypeScript.hasFlag(moduleDecl.getModuleFlags(), 512 /* IsDynamic */); + var kind = 4 /* Container */; + + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 128 /* IsEnum */)) { + declFlags |= (4096 /* Enum */ | 131072 /* InitializedEnum */); + kind = 64 /* Enum */; + } else { + kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; + } + + var span = TypeScript.TextSpan.fromBounds(moduleDecl.minChar, moduleDecl.limChar); + + var decl = new TypeScript.PullDecl(modName, (moduleDecl.name).actualText, kind, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + var parent = context.getParent(); + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectModuleDecls = preCollectModuleDecls; + + function preCollectClassDecls(classDecl, parentAST, context) { + var declFlags = 0 /* None */; + var constructorDeclKind = 1024 /* Variable */; + + if (TypeScript.hasFlag(classDecl.getVarFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(classDecl.getVarFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + var span = TypeScript.TextSpan.fromBounds(classDecl.minChar, classDecl.limChar); + + var decl = new TypeScript.PullDecl(classDecl.name.text, classDecl.name.actualText, 8 /* Class */, declFlags, span, context.scriptName); + + var constructorDecl = new TypeScript.PullDecl(classDecl.name.text, classDecl.name.actualText, constructorDeclKind, declFlags | 16384 /* ClassConstructorVariable */, span, context.scriptName); + + decl.setValueDecl(constructorDecl); + + var parent = context.getParent(); + parent.addChildDecl(decl); + parent.addChildDecl(constructorDecl); + decl.setParentDecl(parent); + constructorDecl.setParentDecl(parent); + + context.pushParent(decl); + + context.semanticInfo.setDeclForAST(classDecl, decl); + context.semanticInfo.setASTForDecl(decl, classDecl); + context.semanticInfo.setASTForDecl(constructorDecl, classDecl); + + return true; + } + TypeScript.preCollectClassDecls = preCollectClassDecls; + + function createObjectTypeDeclaration(interfaceDecl, context) { + var declFlags = 0 /* None */; + + var span = TypeScript.TextSpan.fromBounds(interfaceDecl.minChar, interfaceDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("", "", 8388608 /* ObjectType */, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(interfaceDecl, decl); + context.semanticInfo.setASTForDecl(decl, interfaceDecl); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.createObjectTypeDeclaration = createObjectTypeDeclaration; + + function preCollectInterfaceDecls(interfaceDecl, parentAST, context) { + var declFlags = 0 /* None */; + + if (interfaceDecl.getFlags() & 8 /* TypeReference */) { + return createObjectTypeDeclaration(interfaceDecl, context); + } + + if (TypeScript.hasFlag(interfaceDecl.getVarFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + var span = TypeScript.TextSpan.fromBounds(interfaceDecl.minChar, interfaceDecl.limChar); + + var decl = new TypeScript.PullDecl(interfaceDecl.name.text, interfaceDecl.name.actualText, 16 /* Interface */, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(interfaceDecl, decl); + context.semanticInfo.setASTForDecl(decl, interfaceDecl); + + var parent = context.getParent(); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectInterfaceDecls = preCollectInterfaceDecls; + + function preCollectParameterDecl(argDecl, parentAST, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasFlag(argDecl.getVarFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasFlag(argDecl.getFlags(), 4 /* OptionalName */) || TypeScript.hasFlag(argDecl.id.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var span = TypeScript.TextSpan.fromBounds(argDecl.minChar, argDecl.limChar); + + var decl = new TypeScript.PullDecl(argDecl.id.text, argDecl.id.actualText, 2048 /* Parameter */, declFlags, span, context.scriptName); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (TypeScript.hasFlag(argDecl.getVarFlags(), 256 /* Property */)) { + var propDecl = new TypeScript.PullDecl(argDecl.id.text, argDecl.id.actualText, 4096 /* Property */, declFlags, span, context.scriptName); + propDecl.setValueDecl(decl); + context.parentChain[context.parentChain.length - 2].addChildDecl(propDecl); + propDecl.setParentDecl(context.parentChain[context.parentChain.length - 2]); + context.semanticInfo.setASTForDecl(decl, argDecl); + context.semanticInfo.setASTForDecl(propDecl, argDecl); + context.semanticInfo.setDeclForAST(argDecl, propDecl); + } else { + context.semanticInfo.setASTForDecl(decl, argDecl); + context.semanticInfo.setDeclForAST(argDecl, decl); + } + + if (argDecl.typeExpr && ((argDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (argDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((argDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.preCollectParameterDecl = preCollectParameterDecl; + + function preCollectTypeParameterDecl(typeParameterDecl, parentAST, context) { + var declFlags = 0 /* None */; + + var span = TypeScript.TextSpan.fromBounds(typeParameterDecl.minChar, typeParameterDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(typeParameterDecl.name.text, typeParameterDecl.name.actualText, 8192 /* TypeParameter */, declFlags, span, context.scriptName); + context.semanticInfo.setASTForDecl(decl, typeParameterDecl); + context.semanticInfo.setDeclForAST(typeParameterDecl, decl); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (typeParameterDecl.constraint && ((typeParameterDecl.constraint).term.nodeType === 14 /* InterfaceDeclaration */ || (typeParameterDecl.constraint).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((typeParameterDecl.constraint).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.preCollectTypeParameterDecl = preCollectTypeParameterDecl; + + function createPropertySignature(propertyDecl, context) { + var declFlags = 4 /* Public */; + var parent = context.getParent(); + var declType = parent.getKind() === 64 /* Enum */ ? 67108864 /* EnumMember */ : 4096 /* Property */; + + if (TypeScript.hasFlag(propertyDecl.id.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + if (TypeScript.hasFlag(propertyDecl.getVarFlags(), 4096 /* Constant */)) { + declFlags |= 524288 /* Constant */; + } + + var span = TypeScript.TextSpan.fromBounds(propertyDecl.minChar, propertyDecl.limChar); + + var decl = new TypeScript.PullDecl(propertyDecl.id.text, propertyDecl.id.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(propertyDecl, decl); + context.semanticInfo.setASTForDecl(decl, propertyDecl); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (propertyDecl.typeExpr && ((propertyDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (propertyDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((propertyDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.createPropertySignature = createPropertySignature; + + function createMemberVariableDeclaration(memberDecl, context) { + var declFlags = 0 /* None */; + var declType = 4096 /* Property */; + + if (TypeScript.hasFlag(memberDecl.getVarFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasFlag(memberDecl.getVarFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + var span = TypeScript.TextSpan.fromBounds(memberDecl.minChar, memberDecl.limChar); + + var decl = new TypeScript.PullDecl(memberDecl.id.text, memberDecl.id.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(memberDecl, decl); + context.semanticInfo.setASTForDecl(decl, memberDecl); + + var parent = context.getParent(); + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (memberDecl.typeExpr && ((memberDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (memberDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((memberDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.createMemberVariableDeclaration = createMemberVariableDeclaration; + + function createVariableDeclaration(varDecl, context) { + var declFlags = 0 /* None */; + var declType = 1024 /* Variable */; + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + var span = TypeScript.TextSpan.fromBounds(varDecl.minChar, varDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(varDecl.id.text, varDecl.id.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(varDecl, decl); + context.semanticInfo.setASTForDecl(decl, varDecl); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (varDecl.typeExpr && ((varDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (varDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((varDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.createVariableDeclaration = createVariableDeclaration; + + function preCollectVarDecls(ast, parentAST, context) { + var varDecl = ast; + var declFlags = 0 /* None */; + var declType = 1024 /* Variable */; + var isProperty = false; + var isStatic = false; + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 2048 /* ClassProperty */)) { + return createMemberVariableDeclaration(varDecl, context); + } else if (TypeScript.hasFlag(varDecl.getVarFlags(), 256 /* Property */)) { + return createPropertySignature(varDecl, context); + } + + return createVariableDeclaration(varDecl, context); + } + TypeScript.preCollectVarDecls = preCollectVarDecls; + + function createFunctionTypeDeclaration(functionTypeDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 16777216 /* FunctionType */; + + var span = TypeScript.TextSpan.fromBounds(functionTypeDeclAST.minChar, functionTypeDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("", "", declType, declFlags, span, context.semanticInfo.getPath()); + context.semanticInfo.setDeclForAST(functionTypeDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, functionTypeDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (functionTypeDeclAST.returnTypeAnnotation && ((functionTypeDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (functionTypeDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((functionTypeDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createFunctionTypeDeclaration = createFunctionTypeDeclaration; + + function createConstructorTypeDeclaration(constructorTypeDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 33554432 /* ConstructorType */; + + var span = TypeScript.TextSpan.fromBounds(constructorTypeDeclAST.minChar, constructorTypeDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("{new}", "{new}", declType, declFlags, span, context.semanticInfo.getPath()); + context.semanticInfo.setDeclForAST(constructorTypeDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, constructorTypeDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (constructorTypeDeclAST.returnTypeAnnotation && ((constructorTypeDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (constructorTypeDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((constructorTypeDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createConstructorTypeDeclaration = createConstructorTypeDeclaration; + + function createFunctionDeclaration(funcDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 16384 /* Function */; + + if (TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + if (!funcDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var span = TypeScript.TextSpan.fromBounds(funcDeclAST.minChar, funcDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(funcDeclAST.name.text, funcDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(funcDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, funcDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (funcDeclAST.returnTypeAnnotation && ((funcDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (funcDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((funcDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createFunctionDeclaration = createFunctionDeclaration; + + function createFunctionExpressionDeclaration(functionExpressionDeclAST, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasFlag(functionExpressionDeclAST.getFunctionFlags(), 2048 /* IsFatArrowFunction */)) { + declFlags |= 8192 /* FatArrow */; + } + + var span = TypeScript.TextSpan.fromBounds(functionExpressionDeclAST.minChar, functionExpressionDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var name = functionExpressionDeclAST.name ? functionExpressionDeclAST.name.actualText : ""; + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(functionExpressionDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, functionExpressionDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (functionExpressionDeclAST.returnTypeAnnotation && ((functionExpressionDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (functionExpressionDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((functionExpressionDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createFunctionExpressionDeclaration = createFunctionExpressionDeclaration; + + function createMemberFunctionDeclaration(memberFunctionDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + if (TypeScript.hasFlag(memberFunctionDeclAST.getFunctionFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasFlag(memberFunctionDeclAST.getFunctionFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (!memberFunctionDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + if (TypeScript.hasFlag(memberFunctionDeclAST.name.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + var span = TypeScript.TextSpan.fromBounds(memberFunctionDeclAST.minChar, memberFunctionDeclAST.limChar); + + var decl = new TypeScript.PullDecl(memberFunctionDeclAST.name.text, memberFunctionDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(memberFunctionDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, memberFunctionDeclAST); + + var parent = context.getParent(); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (memberFunctionDeclAST.returnTypeAnnotation && ((memberFunctionDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (memberFunctionDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((memberFunctionDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createMemberFunctionDeclaration = createMemberFunctionDeclaration; + + function createIndexSignatureDeclaration(indexSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */ | 1024 /* Index */; + var declType = 4194304 /* IndexSignature */; + + var span = TypeScript.TextSpan.fromBounds(indexSignatureDeclAST.minChar, indexSignatureDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("[]", "[]", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(indexSignatureDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, indexSignatureDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (indexSignatureDeclAST.returnTypeAnnotation && ((indexSignatureDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (indexSignatureDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((indexSignatureDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createIndexSignatureDeclaration = createIndexSignatureDeclaration; + + function createCallSignatureDeclaration(callSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */ | 256 /* Call */; + var declType = 1048576 /* CallSignature */; + + var span = TypeScript.TextSpan.fromBounds(callSignatureDeclAST.minChar, callSignatureDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("()", "()", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(callSignatureDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, callSignatureDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (callSignatureDeclAST.returnTypeAnnotation && ((callSignatureDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (callSignatureDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((callSignatureDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createCallSignatureDeclaration = createCallSignatureDeclaration; + + function createConstructSignatureDeclaration(constructSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */ | 256 /* Call */; + var declType = 2097152 /* ConstructSignature */; + + var span = TypeScript.TextSpan.fromBounds(constructSignatureDeclAST.minChar, constructSignatureDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("new", "new", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(constructSignatureDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, constructSignatureDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (constructSignatureDeclAST.returnTypeAnnotation && ((constructSignatureDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (constructSignatureDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((constructSignatureDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createConstructSignatureDeclaration = createConstructSignatureDeclaration; + + function createClassConstructorDeclaration(constructorDeclAST, context) { + var declFlags = 512 /* Constructor */; + var declType = 32768 /* ConstructorMethod */; + + if (!constructorDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var span = TypeScript.TextSpan.fromBounds(constructorDeclAST.minChar, constructorDeclAST.limChar); + + var parent = context.getParent(); + + if (parent) { + var parentFlags = parent.getFlags(); + + if (parentFlags & 1 /* Exported */) { + declFlags |= 1 /* Exported */; + } + } + + var decl = new TypeScript.PullDecl(parent.getName(), parent.getDisplayName(), declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(constructorDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, constructorDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (constructorDeclAST.returnTypeAnnotation && ((constructorDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (constructorDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((constructorDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createClassConstructorDeclaration = createClassConstructorDeclaration; + + function createGetAccessorDeclaration(getAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 262144 /* GetAccessor */; + + if (TypeScript.hasFlag(getAccessorDeclAST.getFunctionFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasFlag(getAccessorDeclAST.name.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + if (TypeScript.hasFlag(getAccessorDeclAST.getFunctionFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var span = TypeScript.TextSpan.fromBounds(getAccessorDeclAST.minChar, getAccessorDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(getAccessorDeclAST.name.text, getAccessorDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(getAccessorDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, getAccessorDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (getAccessorDeclAST.returnTypeAnnotation && ((getAccessorDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (getAccessorDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((getAccessorDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createGetAccessorDeclaration = createGetAccessorDeclaration; + + function createSetAccessorDeclaration(setAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 524288 /* SetAccessor */; + + if (TypeScript.hasFlag(setAccessorDeclAST.getFunctionFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasFlag(setAccessorDeclAST.name.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + if (TypeScript.hasFlag(setAccessorDeclAST.getFunctionFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var span = TypeScript.TextSpan.fromBounds(setAccessorDeclAST.minChar, setAccessorDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(setAccessorDeclAST.name.actualText, setAccessorDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(setAccessorDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, setAccessorDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.createSetAccessorDeclaration = createSetAccessorDeclaration; + + function preCollectCatchDecls(ast, parentAST, context) { + var declFlags = 0 /* None */; + var declType = 1073741824 /* CatchBlock */; + + var span = TypeScript.TextSpan.fromBounds(ast.minChar, ast.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("", "", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectCatchDecls = preCollectCatchDecls; + + function preCollectWithDecls(ast, parentAST, context) { + var declFlags = 0 /* None */; + var declType = 536870912 /* WithBlock */; + + var span = TypeScript.TextSpan.fromBounds(ast.minChar, ast.limChar); + + var parent = context.getParent(); + + var decl = new TypeScript.PullDecl("", "", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectWithDecls = preCollectWithDecls; + + function preCollectFuncDecls(ast, parentAST, context) { + var funcDecl = ast; + + if (funcDecl.isConstructor) { + return createClassConstructorDeclaration(funcDecl, context); + } else if (funcDecl.isGetAccessor()) { + return createGetAccessorDeclaration(funcDecl, context); + } else if (funcDecl.isSetAccessor()) { + return createSetAccessorDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 1024 /* ConstructMember */)) { + return TypeScript.hasFlag(funcDecl.getFlags(), 8 /* TypeReference */) ? createConstructorTypeDeclaration(funcDecl, context) : createConstructSignatureDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 512 /* CallMember */)) { + return createCallSignatureDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 4096 /* IndexerMember */)) { + return createIndexSignatureDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFlags(), 8 /* TypeReference */)) { + return createFunctionTypeDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 256 /* Method */)) { + return createMemberFunctionDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), (8192 /* IsFunctionExpression */ | 2048 /* IsFatArrowFunction */ | 16384 /* IsFunctionProperty */))) { + return createFunctionExpressionDeclaration(funcDecl, context); + } + + return createFunctionDeclaration(funcDecl, context); + } + TypeScript.preCollectFuncDecls = preCollectFuncDecls; + + function preCollectDecls(ast, parentAST, walker) { + var context = walker.state; + var go = false; + + if (ast.nodeType === 2 /* Script */) { + var script = ast; + var span = TypeScript.TextSpan.fromBounds(script.minChar, script.limChar); + + var decl = new TypeScript.PullDecl(context.scriptName, context.scriptName, 1 /* Script */, 0 /* None */, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + context.pushParent(decl); + + go = true; + } else if (ast.nodeType === 1 /* List */) { + go = true; + } else if (ast.nodeType === 81 /* Block */) { + go = true; + } else if (ast.nodeType === 18 /* VariableDeclaration */) { + go = true; + } else if (ast.nodeType === 97 /* VariableStatement */) { + go = true; + } else if (ast.nodeType === 15 /* ModuleDeclaration */) { + go = preCollectModuleDecls(ast, parentAST, context); + } else if (ast.nodeType === 13 /* ClassDeclaration */) { + go = preCollectClassDecls(ast, parentAST, context); + } else if (ast.nodeType === 14 /* InterfaceDeclaration */) { + go = preCollectInterfaceDecls(ast, parentAST, context); + } else if (ast.nodeType === 19 /* Parameter */) { + go = preCollectParameterDecl(ast, parentAST, context); + } else if (ast.nodeType === 17 /* VariableDeclarator */) { + go = preCollectVarDecls(ast, parentAST, context); + } else if (ast.nodeType === 12 /* FunctionDeclaration */) { + go = preCollectFuncDecls(ast, parentAST, context); + } else if (ast.nodeType === 16 /* ImportDeclaration */) { + go = preCollectImportDecls(ast, parentAST, context); + } else if (ast.nodeType === 9 /* TypeParameter */) { + go = preCollectTypeParameterDecl(ast, parentAST, context); + } else if (ast.nodeType === 91 /* IfStatement */) { + go = true; + } else if (ast.nodeType === 90 /* ForStatement */) { + go = true; + } else if (ast.nodeType === 89 /* ForInStatement */) { + go = true; + } else if (ast.nodeType === 98 /* WhileStatement */) { + go = true; + } else if (ast.nodeType === 85 /* DoStatement */) { + go = true; + } else if (ast.nodeType === 25 /* CommaExpression */) { + go = true; + } else if (ast.nodeType === 93 /* ReturnStatement */) { + go = true; + } else if (ast.nodeType === 94 /* SwitchStatement */ || ast.nodeType === 100 /* CaseClause */) { + go = true; + } else if (ast.nodeType === 36 /* InvocationExpression */) { + go = true; + } else if (ast.nodeType === 37 /* ObjectCreationExpression */) { + go = true; + } else if (ast.nodeType === 96 /* TryStatement */) { + go = true; + } else if (ast.nodeType === 92 /* LabeledStatement */) { + go = true; + } else if (ast.nodeType === 101 /* CatchClause */) { + go = preCollectCatchDecls(ast, parentAST, context); + } else if (ast.nodeType === 99 /* WithStatement */) { + go = preCollectWithDecls(ast, parentAST, context); + } + + walker.options.goChildren = go; + + return ast; + } + TypeScript.preCollectDecls = preCollectDecls; + + function isContainer(decl) { + return decl.getKind() === 4 /* Container */ || decl.getKind() === 32 /* DynamicModule */ || decl.getKind() === 64 /* Enum */; + } + + function getInitializationFlag(decl) { + if (decl.getKind() & 4 /* Container */) { + return 32768 /* InitializedModule */; + } else if (decl.getKind() & 64 /* Enum */) { + return 131072 /* InitializedEnum */; + } else if (decl.getKind() & 32 /* DynamicModule */) { + return 65536 /* InitializedDynamicModule */; + } + + return 0 /* None */; + } + + function hasInitializationFlag(decl) { + var kind = decl.getKind(); + + if (kind & 4 /* Container */) { + return (decl.getFlags() & 32768 /* InitializedModule */) !== 0; + } else if (kind & 64 /* Enum */) { + return (decl.getFlags() & 131072 /* InitializedEnum */) != 0; + } else if (kind & 32 /* DynamicModule */) { + return (decl.getFlags() & 65536 /* InitializedDynamicModule */) !== 0; + } + + return false; + } + + function postCollectDecls(ast, parentAST, walker) { + var context = walker.state; + var parentDecl; + var initFlag = 0 /* None */; + + if (ast.nodeType === 15 /* ModuleDeclaration */) { + var thisModule = context.getParent(); + context.popParent(); + parentDecl = context.getParent(); + + if (hasInitializationFlag(thisModule)) { + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + + var valueDecl = new TypeScript.PullDecl(thisModule.getName(), thisModule.getDisplayName(), 1024 /* Variable */, thisModule.getFlags(), thisModule.getSpan(), context.scriptName); + + thisModule.setValueDecl(valueDecl); + + context.semanticInfo.setASTForDecl(valueDecl, ast); + + if (parentDecl) { + parentDecl.addChildDecl(valueDecl); + valueDecl.setParentDecl(parentDecl); + } + } + } else if (ast.nodeType === 13 /* ClassDeclaration */) { + context.popParent(); + + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + } else if (ast.nodeType === 14 /* InterfaceDeclaration */) { + context.popParent(); + } else if (ast.nodeType === 12 /* FunctionDeclaration */) { + context.popParent(); + + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + } else if (ast.nodeType === 17 /* VariableDeclarator */) { + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + } else if (ast.nodeType === 101 /* CatchClause */) { + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + + context.popParent(); + } else if (ast.nodeType === 99 /* WithStatement */) { + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + + context.popParent(); + } + + return ast; + } + TypeScript.postCollectDecls = postCollectDecls; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.globalBindingPhase = 0; + + function getPathToDecl(decl) { + if (!decl) { + return []; + } + + var decls = decl.getParentPath(); + + if (decls) { + return decls; + } else { + decls = [decl]; + } + + var parentDecl = decl.getParentDecl(); + + while (parentDecl) { + if (parentDecl && decls[decls.length - 1] != parentDecl && !(parentDecl.getKind() & 512 /* ObjectLiteral */)) { + decls[decls.length] = parentDecl; + } + parentDecl = parentDecl.getParentDecl(); + } + + decls = decls.reverse(); + + decl.setParentPath(decls); + + return decls; + } + TypeScript.getPathToDecl = getPathToDecl; + + function findSymbolInContext(name, declKind, startingDecl) { + var startTime = new Date().getTime(); + var contextSymbolPath = getPathToDecl(startingDecl); + var copyOfContextSymbolPath = []; + var symbol = null; + + var endTime = 0; + + if (contextSymbolPath.length) { + for (var i = 0; i < contextSymbolPath.length; i++) { + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].getName(); + } + + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = name; + + while (copyOfContextSymbolPath.length >= 2) { + symbol = TypeScript.globalSemanticInfoChain.findSymbol(copyOfContextSymbolPath, declKind); + + if (symbol) { + endTime = new Date().getTime(); + TypeScript.time_in_findSymbol += endTime - startTime; + + return symbol; + } + copyOfContextSymbolPath.length -= 2; + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = name; + } + } + + symbol = TypeScript.globalSemanticInfoChain.findSymbol([name], declKind); + + endTime = new Date().getTime(); + TypeScript.time_in_findSymbol += endTime - startTime; + + return symbol; + } + TypeScript.findSymbolInContext = findSymbolInContext; + + var PullSymbolBinder = (function () { + function PullSymbolBinder(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + this.bindingPhase = TypeScript.globalBindingPhase++; + this.functionTypeParameterCache = new TypeScript.BlockIntrinsics(); + this.reBindingAfterChange = false; + this.startingDeclForRebind = TypeScript.pullDeclID; + this.startingSymbolForRebind = TypeScript.pullSymbolID; + } + PullSymbolBinder.prototype.findTypeParameterInCache = function (name) { + return this.functionTypeParameterCache[name]; + }; + + PullSymbolBinder.prototype.addTypeParameterToCache = function (typeParameter) { + this.functionTypeParameterCache[typeParameter.getName()] = typeParameter; + }; + + PullSymbolBinder.prototype.resetTypeParameterCache = function () { + this.functionTypeParameterCache = new TypeScript.BlockIntrinsics(); + }; + + PullSymbolBinder.prototype.setUnit = function (fileName) { + this.semanticInfo = this.semanticInfoChain.getUnit(fileName); + }; + + PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { + if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } + var parentDecl = decl.getParentDecl(); + + if (parentDecl.getKind() == 1 /* Script */) { + return null; + } + + var parent = parentDecl.getSymbol(); + + if (!parent && parentDecl && !parentDecl.isBound()) { + this.bindDeclToPullSymbol(parentDecl); + } + + parent = parentDecl.getSymbol(); + + if (parent) { + if (returnInstanceType && parent.isType() && parent.isContainer()) { + var instanceSymbol = (parent).getInstanceSymbol(); + + if (instanceSymbol) { + return instanceSymbol.getType(); + } + } + + return parent.getType(); + } + + return null; + }; + + PullSymbolBinder.prototype.findDeclsInContext = function (startingDecl, declKind, searchGlobally) { + if (!searchGlobally) { + var parentDecl = startingDecl.getParentDecl(); + return parentDecl.searchChildDecls(startingDecl.getName(), declKind); + } + + var contextSymbolPath = getPathToDecl(startingDecl); + + if (contextSymbolPath.length) { + var copyOfContextSymbolPath = []; + + for (var i = 0; i < contextSymbolPath.length; i++) { + if (contextSymbolPath[i].getKind() & 1 /* Script */) { + continue; + } + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].getName(); + } + + return this.semanticInfoChain.findDecls(copyOfContextSymbolPath, declKind); + } + + return this.semanticInfoChain.findDecls([name], declKind); + }; + + PullSymbolBinder.prototype.symbolIsRedeclaration = function (sym) { + var symID = sym.getSymbolID(); + return (symID >= this.startingSymbolForRebind) || ((sym.getRebindingID() === this.bindingPhase) && (symID !== this.startingSymbolForRebind)); + }; + + PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { + var modName = moduleContainerDecl.getName(); + + var moduleContainerTypeSymbol = null; + var moduleInstanceSymbol = null; + var moduleInstanceTypeSymbol = null; + + var moduleInstanceDecl = moduleContainerDecl.getValueDecl(); + + var moduleKind = moduleContainerDecl.getKind(); + + var parent = this.getParent(moduleContainerDecl); + var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); + var parentDecl = moduleContainerDecl.getParentDecl(); + var moduleAST = this.semanticInfo.getASTForDecl(moduleContainerDecl); + + var isExported = moduleContainerDecl.getFlags() & 1 /* Exported */; + var isEnum = (moduleKind & 64 /* Enum */) != 0; + var searchKind = isEnum ? 64 /* Enum */ : TypeScript.PullElementKind.SomeContainer; + var isInitializedModule = (moduleContainerDecl.getFlags() & TypeScript.PullElementFlags.SomeInitializedModule) != 0; + + var createdNewSymbol = false; + + if (parent) { + if (isExported) { + moduleContainerTypeSymbol = parent.findNestedType(modName, searchKind); + } else { + moduleContainerTypeSymbol = parent.findContainedMember(modName); + + if (moduleContainerTypeSymbol && !(moduleContainerTypeSymbol.getKind() & searchKind)) { + moduleContainerTypeSymbol = null; + } + } + } else if (!isExported || moduleContainerDecl.getKind() === 32 /* DynamicModule */) { + moduleContainerTypeSymbol = findSymbolInContext(modName, searchKind, moduleContainerDecl); + } + + if (moduleContainerTypeSymbol && moduleContainerTypeSymbol.getKind() !== moduleKind) { + if (isInitializedModule) { + moduleContainerDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), moduleAST.minChar, moduleAST.getLength(), 69 /* Duplicate_identifier__0_ */, [moduleContainerDecl.getDisplayName()])); + } + + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + moduleInstanceSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + } else { + moduleContainerTypeSymbol = new TypeScript.PullContainerTypeSymbol(modName, moduleKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(moduleContainerTypeSymbol, searchKind); + } + } + + if (!moduleInstanceSymbol && isInitializedModule) { + var variableSymbol = null; + if (!isEnum) { + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParent = declarations[0].getParentDecl(); + + if ((parentDecl !== variableSymbolParent) && (!this.reBindingAfterChange || (variableSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + variableSymbol = null; + } + } + } + } else if (!(moduleContainerDecl.getFlags() & 1 /* Exported */)) { + var siblingDecls = parentDecl.getChildDecls(); + var augmentedDecl = null; + + for (var i = 0; i < siblingDecls.length; i++) { + if (siblingDecls[i] == moduleContainerDecl) { + break; + } + + if ((siblingDecls[i].getName() == modName) && (siblingDecls[i].getKind() & (8 /* Class */ | TypeScript.PullElementKind.SomeFunction))) { + augmentedDecl = siblingDecls[i]; + break; + } + } + + if (augmentedDecl) { + variableSymbol = augmentedDecl.getSymbol(); + + if (variableSymbol && variableSymbol.isType()) { + variableSymbol = (variableSymbol).getConstructorMethod(); + } + } + } + } + + if (variableSymbol) { + var prevKind = variableSymbol.getKind(); + var acceptableRedeclaration = (prevKind == 16384 /* Function */) || (prevKind == 32768 /* ConstructorMethod */) || variableSymbol.hasFlag(TypeScript.PullElementFlags.ImplicitVariable); + + if (acceptableRedeclaration) { + moduleInstanceTypeSymbol = variableSymbol.getType(); + } else { + variableSymbol = null; + } + } + + if (!moduleInstanceTypeSymbol) { + moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol(modName, 8388608 /* ObjectType */); + } + + moduleInstanceTypeSymbol.addDeclaration(moduleContainerDecl); + + moduleInstanceTypeSymbol.setAssociatedContainerType(moduleContainerTypeSymbol); + + if (variableSymbol) { + moduleInstanceSymbol = variableSymbol; + } else { + moduleInstanceSymbol = new TypeScript.PullSymbol(modName, 1024 /* Variable */); + moduleInstanceSymbol.setType(moduleInstanceTypeSymbol); + } + + moduleContainerTypeSymbol.setInstanceSymbol(moduleInstanceSymbol); + } + + moduleContainerTypeSymbol.addDeclaration(moduleContainerDecl); + moduleContainerDecl.setSymbol(moduleContainerTypeSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(moduleAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(moduleContainerTypeSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(moduleAST, TypeScript.SymbolAndDiagnostics.fromSymbol(moduleContainerTypeSymbol)); + + var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); + if (isEnum && moduleDeclarations.length > 1 && moduleAST.members.members.length > 0) { + var multipleEnums = TypeScript.ArrayUtilities.where(moduleDeclarations, function (d) { + return d.getKind() === 64 /* Enum */; + }).length > 1; + if (multipleEnums) { + var firstVariable = moduleAST.members.members[0]; + var firstVariableDeclarator = firstVariable.declaration.declarators.members[0]; + if (firstVariableDeclarator.isImplicitlyInitialized) { + moduleContainerDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), firstVariableDeclarator.minChar, firstVariableDeclarator.getLength(), 264 /* Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element */, null)); + } + } + } + + if (createdNewSymbol) { + if (parent) { + var linkKind = moduleContainerDecl.getFlags() & 1 /* Exported */ ? 5 /* PublicMember */ : 6 /* PrivateMember */; + + if (linkKind === 5 /* PublicMember */) { + parent.addMember(moduleContainerTypeSymbol, linkKind); + } else { + moduleContainerTypeSymbol.setContainer(parent); + } + } + } else if (this.reBindingAfterChange) { + var decls = moduleContainerTypeSymbol.getDeclarations(); + var scriptName = moduleContainerDecl.getScriptName(); + + for (var i = 0; i < decls.length; i++) { + if (decls[i].getScriptName() === scriptName && decls[i].getDeclID() < this.startingDeclForRebind) { + moduleContainerTypeSymbol.removeDeclaration(decls[i]); + } + } + + moduleContainerTypeSymbol.invalidate(); + + moduleInstanceSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + + if (moduleInstanceSymbol) { + var moduleInstanceTypeSymbol = moduleInstanceSymbol.getType(); + decls = moduleInstanceTypeSymbol.getDeclarations(); + + for (var i = 0; i < decls.length; i++) { + if (decls[i].getScriptName() === scriptName && decls[i].getDeclID() < this.startingDeclForRebind) { + moduleInstanceTypeSymbol.removeDeclaration(decls[i]); + } + } + + moduleInstanceTypeSymbol.addDeclaration(moduleContainerDecl); + moduleInstanceTypeSymbol.invalidate(); + } + } + + if (isEnum) { + moduleInstanceTypeSymbol = moduleContainerTypeSymbol.getInstanceSymbol().getType(); + + if (this.reBindingAfterChange) { + var existingIndexSigs = moduleInstanceTypeSymbol.getIndexSignatures(); + + for (var i = 0; i < existingIndexSigs.length; i++) { + moduleInstanceTypeSymbol.removeIndexSignature(existingIndexSigs[i]); + } + } + + var enumIndexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var enumIndexParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); + enumIndexParameterSymbol.setType(this.semanticInfoChain.numberTypeSymbol); + enumIndexSignature.addParameter(enumIndexParameterSymbol); + enumIndexSignature.setReturnType(this.semanticInfoChain.stringTypeSymbol); + + moduleInstanceTypeSymbol.addIndexSignature(enumIndexSignature); + + moduleInstanceTypeSymbol.recomputeIndexSignatures(); + } + + var valueDecl = moduleContainerDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + var otherDecls = this.findDeclsInContext(moduleContainerDecl, moduleContainerDecl.getKind(), true); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindImportDeclaration = function (importDeclaration) { + var declFlags = importDeclaration.getFlags(); + var declKind = importDeclaration.getKind(); + var importDeclAST = this.semanticInfo.getASTForDecl(importDeclaration); + + var isExported = false; + var linkKind = 6 /* PrivateMember */; + var importSymbol = null; + var declName = importDeclaration.getName(); + var parentHadSymbol = false; + var parent = this.getParent(importDeclaration); + + if (parent) { + importSymbol = parent.findMember(declName, false); + + if (!importSymbol) { + importSymbol = parent.findContainedMember(declName); + + if (importSymbol) { + var declarations = importSymbol.getDeclarations(); + + if (declarations.length) { + var importSymbolParent = declarations[0].getParentDecl(); + + if ((importSymbolParent !== importDeclaration.getParentDecl()) && (!this.reBindingAfterChange || (importSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + importSymbol = null; + } + } + } + } + } else if (!(importDeclaration.getFlags() & 1 /* Exported */)) { + importSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeContainer, importDeclaration); + } + + if (importSymbol) { + parentHadSymbol = true; + } + + if (importSymbol && this.symbolIsRedeclaration(importSymbol)) { + importDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), importDeclAST.minChar, importDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [importDeclaration.getDisplayName()])); + importSymbol = null; + } + + if (this.reBindingAfterChange && importSymbol) { + var decls = importSymbol.getDeclarations(); + var scriptName = importDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + importSymbol.removeDeclaration(decls[j]); + } + } + + importSymbol.setUnresolved(); + } + + if (!importSymbol) { + importSymbol = new TypeScript.PullTypeAliasSymbol(declName); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(importSymbol, TypeScript.PullElementKind.SomeContainer); + } + } + + importSymbol.addDeclaration(importDeclaration); + importDeclaration.setSymbol(importSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(importDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(importSymbol)); + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(importSymbol, 5 /* PublicMember */); + } else { + importSymbol.setContainer(parent); + } + } + + importSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.cleanInterfaceSignatures = function (interfaceSymbol) { + var callSigs = interfaceSymbol.getCallSignatures(); + var constructSigs = interfaceSymbol.getConstructSignatures(); + var indexSigs = interfaceSymbol.getIndexSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + if (callSigs[i].getSymbolID() < this.startingSymbolForRebind) { + interfaceSymbol.removeCallSignature(callSigs[i], false); + } + } + for (var i = 0; i < constructSigs.length; i++) { + if (constructSigs[i].getSymbolID() < this.startingSymbolForRebind) { + interfaceSymbol.removeConstructSignature(constructSigs[i], false); + } + } + for (var i = 0; i < indexSigs.length; i++) { + if (indexSigs[i].getSymbolID() < this.startingSymbolForRebind) { + interfaceSymbol.removeIndexSignature(indexSigs[i], false); + } + } + + interfaceSymbol.recomputeCallSignatures(); + interfaceSymbol.recomputeConstructSignatures(); + interfaceSymbol.recomputeIndexSignatures(); + }; + + PullSymbolBinder.prototype.cleanClassSignatures = function (classSymbol) { + var callSigs = classSymbol.getCallSignatures(); + var constructSigs = classSymbol.getConstructSignatures(); + var indexSigs = classSymbol.getIndexSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + classSymbol.removeCallSignature(callSigs[i], false); + } + for (var i = 0; i < constructSigs.length; i++) { + classSymbol.removeConstructSignature(constructSigs[i], false); + } + for (var i = 0; i < indexSigs.length; i++) { + classSymbol.removeIndexSignature(indexSigs[i], false); + } + + classSymbol.recomputeCallSignatures(); + classSymbol.recomputeConstructSignatures(); + classSymbol.recomputeIndexSignatures(); + + var constructorSymbol = classSymbol.getConstructorMethod(); + var constructorTypeSymbol = (constructorSymbol ? constructorSymbol.getType() : null); + + if (constructorTypeSymbol) { + constructSigs = constructorTypeSymbol.getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + constructorTypeSymbol.removeConstructSignature(constructSigs[i], false); + } + + constructorTypeSymbol.recomputeConstructSignatures(); + constructorTypeSymbol.invalidate(); + constructorSymbol.invalidate(); + } + + classSymbol.invalidate(); + }; + + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { + var className = classDecl.getName(); + var classSymbol = null; + + var constructorSymbol = null; + var constructorTypeSymbol = null; + + var classAST = this.semanticInfo.getASTForDecl(classDecl); + var parentHadSymbol = false; + + var parent = this.getParent(classDecl); + var parentDecl = classDecl.getParentDecl(); + var cleanedPreviousDecls = false; + var isExported = classDecl.getFlags() & 1 /* Exported */; + var isGeneric = false; + + var acceptableSharedKind = 8 /* Class */; + + if (parent) { + if (isExported) { + classSymbol = parent.findNestedType(className); + + if (!classSymbol) { + classSymbol = parent.findMember(className, false); + } + } else { + classSymbol = parent.findContainedMember(className); + + if (classSymbol && (classSymbol.getKind() & acceptableSharedKind)) { + var declarations = classSymbol.getDeclarations(); + + if (declarations.length) { + var classSymbolParent = declarations[0].getParentDecl(); + + if ((classSymbolParent !== parentDecl) && (!this.reBindingAfterChange || (classSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + classSymbol = null; + } + } + } else { + classSymbol = null; + } + } + } else { + classSymbol = findSymbolInContext(className, acceptableSharedKind, classDecl); + } + + if (classSymbol && (!(classSymbol.getKind() & acceptableSharedKind) || !this.reBindingAfterChange || this.symbolIsRedeclaration(classSymbol))) { + classDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), classAST.minChar, classAST.getLength(), 69 /* Duplicate_identifier__0_ */, [classDecl.getDisplayName()])); + classSymbol = null; + } else if (classSymbol) { + parentHadSymbol = true; + } + + var decls; + + if (this.reBindingAfterChange && classSymbol) { + decls = classSymbol.getDeclarations(); + var scriptName = classDecl.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + classSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = constructorSymbol.getType(); + + decls = constructorSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + constructorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (constructorSymbol.getIsSynthesized()) { + classSymbol.setConstructorMethod(null); + } + + if (classSymbol.isGeneric()) { + isGeneric = true; + + var specializations = classSymbol.getKnownSpecializations(); + var specialization = null; + + for (var i = 0; i < specializations.length; i++) { + specializations[i].setUnresolved(); + specializations[i].invalidate(); + } + + classSymbol.cleanTypeParameters(); + constructorTypeSymbol.cleanTypeParameters(); + } + + classSymbol.setUnresolved(); + constructorSymbol.setUnresolved(); + constructorTypeSymbol.setUnresolved(); + } + + if (!parentHadSymbol) { + classSymbol = new TypeScript.PullClassTypeSymbol(className); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(classSymbol, acceptableSharedKind); + } + } + + classSymbol.addDeclaration(classDecl); + + classDecl.setSymbol(classSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(classAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(classSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(classAST, TypeScript.SymbolAndDiagnostics.fromSymbol(classSymbol)); + + if (parent && !parentHadSymbol) { + var linkKind = classDecl.getFlags() & 1 /* Exported */ ? 5 /* PublicMember */ : 6 /* PrivateMember */; + + if (linkKind === 5 /* PublicMember */) { + parent.addMember(classSymbol, linkKind); + } else { + classSymbol.setContainer(parent); + } + } + + if (parentHadSymbol && cleanedPreviousDecls) { + this.cleanClassSignatures(classSymbol); + + if (isGeneric) { + specializations = classSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + this.cleanClassSignatures(specializations[i]); + } + } + } + + this.resetTypeParameterCache(); + + this.resetTypeParameterCache(); + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = (constructorSymbol ? constructorSymbol.getType() : null); + + if (!constructorSymbol) { + constructorSymbol = new TypeScript.PullSymbol(className, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullConstructorTypeSymbol(); + + constructorSymbol.setIsSynthesized(); + + constructorSymbol.setType(constructorTypeSymbol); + constructorSymbol.addDeclaration(classDecl.getValueDecl()); + classSymbol.setConstructorMethod(constructorSymbol); + + constructorTypeSymbol.addDeclaration(classDecl); + + classSymbol.setHasDefaultConstructor(); + } + + constructorTypeSymbol.setAssociatedContainerType(classSymbol); + + var typeParameters = classDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = classSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + classSymbol.addMember(typeParameter, 18 /* TypeParameter */); + constructorTypeSymbol.addTypeParameter(typeParameter, true); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + classDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + var valueDecl = classDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + classSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { + var interfaceName = interfaceDecl.getName(); + var interfaceSymbol = findSymbolInContext(interfaceName, TypeScript.PullElementKind.SomeType, interfaceDecl); + + var interfaceAST = this.semanticInfo.getASTForDecl(interfaceDecl); + var createdNewSymbol = false; + var parent = this.getParent(interfaceDecl); + + var acceptableSharedKind = 16 /* Interface */; + + if (parent) { + interfaceSymbol = parent.findNestedType(interfaceName); + } else if (!(interfaceDecl.getFlags() & 1 /* Exported */)) { + interfaceSymbol = findSymbolInContext(interfaceName, acceptableSharedKind, interfaceDecl); + } + + if (interfaceSymbol && !(interfaceSymbol.getKind() & acceptableSharedKind)) { + interfaceDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), interfaceAST.minChar, interfaceAST.getLength(), 69 /* Duplicate_identifier__0_ */, [interfaceDecl.getDisplayName()])); + interfaceSymbol = null; + } + + if (!interfaceSymbol) { + interfaceSymbol = new TypeScript.PullTypeSymbol(interfaceName, 16 /* Interface */); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(interfaceSymbol, acceptableSharedKind); + } + } + + interfaceSymbol.addDeclaration(interfaceDecl); + interfaceDecl.setSymbol(interfaceSymbol); + + if (createdNewSymbol) { + if (parent) { + var linkKind = interfaceDecl.getFlags() & 1 /* Exported */ ? 5 /* PublicMember */ : 6 /* PrivateMember */; + + if (linkKind === 5 /* PublicMember */) { + parent.addMember(interfaceSymbol, linkKind); + } else { + interfaceSymbol.setContainer(parent); + } + } + } else if (this.reBindingAfterChange) { + var decls = interfaceSymbol.getDeclarations(); + var scriptName = interfaceDecl.getScriptName(); + + for (var i = 0; i < decls.length; i++) { + if (decls[i].getScriptName() === scriptName && decls[i].getDeclID() < this.startingDeclForRebind) { + interfaceSymbol.removeDeclaration(decls[i]); + } + } + + if (interfaceSymbol.isGeneric()) { + var specializations = interfaceSymbol.getKnownSpecializations(); + var specialization = null; + + for (var i = 0; i < specializations.length; i++) { + specialization = specializations[i]; + + this.cleanInterfaceSignatures(specialization); + specialization.invalidate(); + } + + interfaceSymbol.cleanTypeParameters(); + } + + this.cleanInterfaceSignatures(interfaceSymbol); + interfaceSymbol.invalidate(); + } + + this.resetTypeParameterCache(); + + this.resetTypeParameterCache(); + + var typeParameters = interfaceDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + interfaceSymbol.addMember(typeParameter, 18 /* TypeParameter */); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + for (var j = 0; j < typeParameterDecls.length; j++) { + var typeParameterDeclParent = typeParameterDecls[j].getParentDecl(); + + if (typeParameterDeclParent && typeParameterDeclParent === interfaceDecl) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + interfaceDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + + break; + } + } + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + var otherDecls = this.findDeclsInContext(interfaceDecl, interfaceDecl.getKind(), true); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { + var objectSymbolAST = this.semanticInfo.getASTForDecl(objectDecl); + + var objectSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + + objectSymbol.addDeclaration(objectDecl); + objectDecl.setSymbol(objectSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(objectSymbolAST, TypeScript.SymbolAndDiagnostics.fromSymbol(objectSymbol)); + + var childDecls = objectDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + + var typeParameters = objectDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = objectSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + objectSymbol.addMember(typeParameter, 18 /* TypeParameter */); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + objectDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindConstructorTypeDeclarationToPullSymbol = function (constructorTypeDeclaration) { + var declKind = constructorTypeDeclaration.getKind(); + var declFlags = constructorTypeDeclaration.getFlags(); + var constructorTypeAST = this.semanticInfo.getASTForDecl(constructorTypeDeclaration); + + var constructorTypeSymbol = new TypeScript.PullConstructorTypeSymbol(); + + constructorTypeDeclaration.setSymbol(constructorTypeSymbol); + constructorTypeSymbol.addDeclaration(constructorTypeDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(constructorTypeAST, TypeScript.SymbolAndDiagnostics.fromSymbol(constructorTypeSymbol)); + + var signature = new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */); + + if ((constructorTypeAST).variableArgList) { + signature.setHasVariableParamList(); + } + + signature.addDeclaration(constructorTypeDeclaration); + constructorTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(constructorTypeDeclaration), constructorTypeSymbol, signature); + + constructorTypeSymbol.addSignature(signature); + + var typeParameters = constructorTypeDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + constructorTypeSymbol.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + constructorTypeDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.getFlags(); + var declKind = variableDeclaration.getKind(); + var varDeclAST = this.semanticInfo.getASTForDecl(variableDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var linkKind = 6 /* PrivateMember */; + + var variableSymbol = null; + + var declName = variableDeclaration.getName(); + + var parentHadSymbol = false; + + var parent = this.getParent(variableDeclaration, true); + + var parentDecl = variableDeclaration.getParentDecl(); + + var isImplicit = (declFlags & TypeScript.PullElementFlags.ImplicitVariable) !== 0; + var isModuleValue = (declFlags & (32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */ | 131072 /* InitializedEnum */)) != 0; + var isEnumValue = (declFlags & 131072 /* InitializedEnum */) != 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) != 0; + + if (parentDecl && !isImplicit) { + parentDecl.addVariableDeclToGroup(variableDeclaration); + } + + if (parent) { + if (isExported) { + variableSymbol = parent.findMember(declName, false); + } else { + variableSymbol = parent.findContainedMember(declName); + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParent = declarations[0].getParentDecl(); + + if ((parentDecl !== variableSymbolParent) && (!this.reBindingAfterChange || (variableSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + variableSymbol = null; + } + } + } + } else if (!(variableDeclaration.getFlags() & 1 /* Exported */)) { + variableSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeValue, variableDeclaration); + } + + if (variableSymbol && !variableSymbol.isType()) { + parentHadSymbol = true; + } + + var span; + var decl; + var decls; + var ast; + var members; + + if (variableSymbol && this.symbolIsRedeclaration(variableSymbol)) { + var prevKind = variableSymbol.getKind(); + var prevIsAmbient = variableSymbol.hasFlag(8 /* Ambient */); + var prevIsEnum = variableSymbol.hasFlag(131072 /* InitializedEnum */); + var prevIsClass = prevKind == 32768 /* ConstructorMethod */; + var prevIsContainer = variableSymbol.hasFlag(32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */); + var onlyOneIsEnum = (isEnumValue || prevIsEnum) && !(isEnumValue && prevIsEnum); + var isAmbient = (variableDeclaration.getFlags() & 8 /* Ambient */) != 0; + var isClass = variableDeclaration.getKind() == 32768 /* ConstructorMethod */; + + var acceptableRedeclaration = isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevKind == 16384 /* Function */) || (!isModuleValue && prevIsContainer && isAmbient) || (!isModuleValue && prevIsClass) || variableSymbol.hasFlag(TypeScript.PullElementFlags.ImplicitVariable)); + + if (acceptableRedeclaration && prevIsClass && !prevIsAmbient) { + if (variableSymbol.getDeclarations()[0].getScriptName() != variableDeclaration.getScriptName()) { + acceptableRedeclaration = false; + } + } + + if ((!isModuleValue && !isClass && !isAmbient) || !acceptableRedeclaration || onlyOneIsEnum) { + span = variableDeclaration.getSpan(); + if (!parent || variableSymbol.getIsSynthesized()) { + var errorDecl = isImplicit ? variableSymbol.getDeclarations()[0] : variableDeclaration; + errorDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), span.start(), span.length(), 69 /* Duplicate_identifier__0_ */, [variableDeclaration.getDisplayName()])); + } + + variableSymbol = null; + parentHadSymbol = false; + } + } else if (variableSymbol && (variableSymbol.getKind() !== 1024 /* Variable */) && !isImplicit) { + span = variableDeclaration.getSpan(); + + variableDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), span.start(), span.length(), 69 /* Duplicate_identifier__0_ */, [variableDeclaration.getDisplayName()])); + variableSymbol = null; + parentHadSymbol = false; + } + + if (this.reBindingAfterChange && variableSymbol && !variableSymbol.isType()) { + decls = variableSymbol.getDeclarations(); + var scriptName = variableDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + variableSymbol.removeDeclaration(decls[j]); + } + } + + variableSymbol.invalidate(); + } + + var replaceProperty = false; + var previousProperty = null; + + if ((declFlags & TypeScript.PullElementFlags.ImplicitVariable) === 0) { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(varDeclAST.id, TypeScript.SymbolAndDiagnostics.fromSymbol(variableSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(varDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(variableSymbol)); + } else if (!parentHadSymbol) { + if (isClassConstructorVariable) { + var classTypeSymbol = variableSymbol; + + if (parent) { + members = parent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].getName() === declName) && (members[i].getKind() === 8 /* Class */)) { + classTypeSymbol = members[i]; + break; + } + } + } + + if (!classTypeSymbol) { + var parentDecl = variableDeclaration.getParentDecl(); + + if (parentDecl) { + var childDecls = parentDecl.searchChildDecls(declName, TypeScript.PullElementKind.SomeType); + + if (childDecls.length) { + for (var i = 0; i < childDecls.length; i++) { + if (childDecls[i].getValueDecl() === variableDeclaration) { + classTypeSymbol = childDecls[i].getSymbol(); + } + } + } + } + + if (!classTypeSymbol) { + classTypeSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeType, variableDeclaration); + } + } + + if (classTypeSymbol && (classTypeSymbol.getKind() !== 8 /* Class */)) { + classTypeSymbol = null; + } + + if (classTypeSymbol && classTypeSymbol.isClass()) { + replaceProperty = variableSymbol && variableSymbol.getIsSynthesized(); + + if (replaceProperty) { + previousProperty = variableSymbol; + } + + variableSymbol = classTypeSymbol.getConstructorMethod(); + variableDeclaration.setSymbol(variableSymbol); + + decls = classTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfo.getASTForDecl(decl); + + if (ast) { + this.semanticInfo.setASTForDecl(variableDeclaration, ast); + } + } + } else { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.setType(this.semanticInfoChain.anyTypeSymbol); + } + } else if (declFlags & TypeScript.PullElementFlags.SomeInitializedModule) { + var moduleContainerTypeSymbol = null; + var moduleParent = this.getParent(variableDeclaration); + + if (moduleParent) { + members = moduleParent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].getName() === declName) && (members[i].isContainer())) { + moduleContainerTypeSymbol = members[i]; + break; + } + } + } + + if (!moduleContainerTypeSymbol) { + var parentDecl = variableDeclaration.getParentDecl(); + + if (parentDecl) { + var searchKind = (declFlags & (32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */)) ? TypeScript.PullElementKind.SomeContainer : 64 /* Enum */; + var childDecls = parentDecl.searchChildDecls(declName, searchKind); + + if (childDecls.length) { + for (var i = 0; i < childDecls.length; i++) { + if (childDecls[i].getValueDecl() === variableDeclaration) { + moduleContainerTypeSymbol = childDecls[i].getSymbol(); + } + } + } + } + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeContainer, variableDeclaration); + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = findSymbolInContext(declName, 64 /* Enum */, variableDeclaration); + } + } + } + + if (moduleContainerTypeSymbol && (!moduleContainerTypeSymbol.isContainer())) { + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + decls = moduleContainerTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfo.getASTForDecl(decl); + + if (ast) { + this.semanticInfo.setASTForDecl(variableDeclaration, ast); + } + } + } else { + TypeScript.Debug.assert(false, "Attempted to bind invalid implicit variable symbol"); + } + } + } else { + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + } + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(variableSymbol, 5 /* PublicMember */); + } else { + variableSymbol.setContainer(parent); + } + } else if (replaceProperty) { + parent.removeMember(previousProperty); + parent.addMember(variableSymbol, linkKind); + } + + variableSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindPropertyDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.getFlags(); + var declKind = propertyDeclaration.getKind(); + var propDeclAST = this.semanticInfo.getASTForDecl(propertyDeclaration); + + var isStatic = false; + var isOptional = false; + + var linkKind = 5 /* PublicMember */; + + var propertySymbol = null; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + linkKind = 6 /* PrivateMember */; + } + + if (TypeScript.hasFlag(declFlags, 128 /* Optional */)) { + isOptional = true; + } + + var declName = propertyDeclaration.getName(); + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + if (parent.isClass() && isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + propertySymbol = parent.findMember(declName, false); + + if (propertySymbol && (!this.reBindingAfterChange || this.symbolIsRedeclaration(propertySymbol))) { + var span = propertyDeclaration.getSpan(); + + propertyDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), span.start(), span.length(), 69 /* Duplicate_identifier__0_ */, [propertyDeclaration.getDisplayName()])); + + propertySymbol = null; + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + if (this.reBindingAfterChange && propertySymbol) { + var decls = propertySymbol.getDeclarations(); + var scriptName = propertyDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + propertySymbol.removeDeclaration(decls[j]); + } + } + + propertySymbol.setUnresolved(); + } + + var classTypeSymbol; + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(propDeclAST.id, TypeScript.SymbolAndDiagnostics.fromSymbol(propertySymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(propDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(propertySymbol)); + + if (isOptional) { + propertySymbol.setIsOptional(); + } + + if (parent && !parentHadSymbol) { + if (parent.isClass()) { + classTypeSymbol = parent; + + classTypeSymbol.addMember(propertySymbol, linkKind); + } else { + parent.addMember(propertySymbol, linkKind); + } + } + + propertySymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindParameterSymbols = function (funcDecl, funcType, signatureSymbol) { + var parameters = []; + var decl = null; + var argDecl = null; + var parameterSymbol = null; + var isProperty = false; + var params = new TypeScript.BlockIntrinsics(); + + if (funcDecl.arguments) { + for (var i = 0; i < funcDecl.arguments.members.length; i++) { + argDecl = funcDecl.arguments.members[i]; + decl = this.semanticInfo.getDeclForAST(argDecl); + isProperty = TypeScript.hasFlag(argDecl.getVarFlags(), 256 /* Property */); + parameterSymbol = new TypeScript.PullSymbol(argDecl.id.text, 2048 /* Parameter */); + + if (funcDecl.variableArgList && i === funcDecl.arguments.members.length - 1) { + parameterSymbol.setIsVarArg(); + } + + if (decl.getFlags() & 128 /* Optional */) { + parameterSymbol.setIsOptional(); + } + + if (params[argDecl.id.text]) { + decl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), argDecl.minChar, argDecl.getLength(), 69 /* Duplicate_identifier__0_ */, [argDecl.id.actualText])); + } else { + params[argDecl.id.text] = true; + } + if (decl) { + if (isProperty) { + decl.ensureSymbolIsBound(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + valDecl.setSymbol(parameterSymbol); + parameterSymbol.addDeclaration(valDecl); + } + } else { + parameterSymbol.addDeclaration(decl); + decl.setSymbol(parameterSymbol); + } + } + + signatureSymbol.addParameter(parameterSymbol, parameterSymbol.getIsOptional()); + + if (signatureSymbol.isDefinition()) { + parameterSymbol.setContainer(funcType); + } + } + } + }; + + PullSymbolBinder.prototype.bindFunctionDeclarationToPullSymbol = function (functionDeclaration) { + var declKind = functionDeclaration.getKind(); + var declFlags = functionDeclaration.getFlags(); + var funcDeclAST = this.semanticInfo.getASTForDecl(functionDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = functionDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(functionDeclaration, true); + var parentDecl = functionDeclaration.getParentDecl(); + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var functionSymbol = null; + var functionTypeSymbol = null; + + if (parent) { + functionSymbol = parent.findMember(funcName, false); + + if (!functionSymbol) { + functionSymbol = parent.findContainedMember(funcName); + + if (functionSymbol) { + var declarations = functionSymbol.getDeclarations(); + + if (declarations.length) { + var funcSymbolParent = declarations[0].getParentDecl(); + + if ((parentDecl !== funcSymbolParent) && (!this.reBindingAfterChange || (funcSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + functionSymbol = null; + } + } + } + } + } else if (!(functionDeclaration.getFlags() & 1 /* Exported */)) { + functionSymbol = findSymbolInContext(funcName, TypeScript.PullElementKind.SomeValue, functionDeclaration); + } + + if (functionSymbol && (functionSymbol.getKind() !== 16384 /* Function */ || (this.symbolIsRedeclaration(functionSymbol) && !isSignature && !functionSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + functionDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [functionDeclaration.getDisplayName()])); + functionSymbol = null; + } + + if (functionSymbol) { + functionTypeSymbol = functionSymbol.getType(); + parentHadSymbol = true; + } + + if (this.reBindingAfterChange && functionSymbol) { + var decls = functionSymbol.getDeclarations(); + var scriptName = functionDeclaration.getScriptName(); + var isGeneric = functionTypeSymbol.isGeneric(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + functionSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + decls = functionTypeSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + functionTypeSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (isGeneric) { + var specializations = functionTypeSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + } + + functionSymbol.invalidate(); + functionTypeSymbol.invalidate(); + } + + if (!functionSymbol) { + functionSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + } + + if (!functionTypeSymbol) { + functionTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + functionSymbol.setType(functionTypeSymbol); + } + + functionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionDeclaration); + functionTypeSymbol.addDeclaration(functionDeclaration); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + + if (parent && !parentHadSymbol) { + if (isExported) { + parent.addMember(functionSymbol, 5 /* PublicMember */); + } else { + functionSymbol.setContainer(parent); + } + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = functionTypeSymbol.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + functionTypeSymbol.removeCallSignature(callSigs[i], false); + } + + functionSymbol.invalidate(); + functionTypeSymbol.invalidate(); + functionTypeSymbol.recomputeCallSignatures(); + + if (isGeneric) { + var specializations = functionTypeSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + callSigs = specializations[j].getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + callSigs[i].invalidate(); + } + } + } + } + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + signature.addDeclaration(functionDeclaration); + functionDeclaration.setSignatureSymbol(signature); + + if (funcDeclAST.variableArgList) { + signature.setHasVariableParamList(); + } + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(functionDeclaration), functionTypeSymbol, signature); + + var typeParameters = functionDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + functionDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + functionTypeSymbol.addCallSignature(signature); + + if (!isSignature) { + } + + functionSymbol.setIsBound(this.bindingPhase); + + var otherDecls = this.findDeclsInContext(functionDeclaration, functionDeclaration.getKind(), false); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { + var declKind = functionExpressionDeclaration.getKind(); + var declFlags = functionExpressionDeclaration.getFlags(); + var funcExpAST = this.semanticInfo.getASTForDecl(functionExpressionDeclaration); + + var functionName = declKind == 131072 /* FunctionExpression */ ? (functionExpressionDeclaration).getFunctionExpressionName() : functionExpressionDeclaration.getName(); + var functionSymbol = new TypeScript.PullSymbol(functionName, 16384 /* Function */); + var functionTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + functionSymbol.setType(functionTypeSymbol); + + functionExpressionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionExpressionDeclaration); + functionTypeSymbol.addDeclaration(functionExpressionDeclaration); + + if (funcExpAST.name) { + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcExpAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + } + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcExpAST, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + + var signature = new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + if (funcExpAST.variableArgList) { + signature.setHasVariableParamList(); + } + + var typeParameters = functionExpressionDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + functionExpressionDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionExpressionDeclaration); + functionExpressionDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(functionExpressionDeclaration), functionTypeSymbol, signature); + + functionTypeSymbol.addSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { + var declKind = functionTypeDeclaration.getKind(); + var declFlags = functionTypeDeclaration.getFlags(); + var funcTypeAST = this.semanticInfo.getASTForDecl(functionTypeDeclaration); + + var functionTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + functionTypeDeclaration.setSymbol(functionTypeSymbol); + functionTypeSymbol.addDeclaration(functionTypeDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcTypeAST, TypeScript.SymbolAndDiagnostics.fromSymbol(functionTypeSymbol)); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + if (funcTypeAST.variableArgList) { + signature.setHasVariableParamList(); + } + + var typeParameters = functionTypeDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + functionTypeDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionTypeDeclaration); + functionTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(functionTypeDeclaration), functionTypeSymbol, signature); + + functionTypeSymbol.addSignature(signature); + }; + + PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { + var declKind = methodDeclaration.getKind(); + var declFlags = methodDeclaration.getFlags(); + var methodAST = this.semanticInfo.getASTForDecl(methodDeclaration); + + var isPrivate = (declFlags & 2 /* Private */) !== 0; + var isStatic = (declFlags & 16 /* Static */) !== 0; + var isOptional = (declFlags & 128 /* Optional */) !== 0; + + var methodName = methodDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(methodDeclaration, true); + var parentHadSymbol = false; + + var cleanedPreviousDecls = false; + + var methodSymbol = null; + var methodTypeSymbol = null; + + var linkKind = isPrivate ? 6 /* PrivateMember */ : 5 /* PublicMember */; + + if (parent.isClass() && isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + methodSymbol = parent.findMember(methodName, false); + + if (methodSymbol && (methodSymbol.getKind() !== 65536 /* Method */ || (this.symbolIsRedeclaration(methodSymbol) && !isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + methodDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), methodAST.minChar, methodAST.getLength(), 69 /* Duplicate_identifier__0_ */, [methodDeclaration.getDisplayName()])); + methodSymbol = null; + } + + if (methodSymbol) { + methodTypeSymbol = methodSymbol.getType(); + parentHadSymbol = true; + } + + if (this.reBindingAfterChange && methodSymbol) { + var decls = methodSymbol.getDeclarations(); + var scriptName = methodDeclaration.getScriptName(); + var isGeneric = methodTypeSymbol.isGeneric(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + methodSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + decls = methodTypeSymbol.getDeclarations(); + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + methodTypeSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (isGeneric) { + var specializations = methodTypeSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + } + + methodSymbol.invalidate(); + methodTypeSymbol.invalidate(); + } + + if (!methodSymbol) { + methodSymbol = new TypeScript.PullSymbol(methodName, 65536 /* Method */); + } + + if (!methodTypeSymbol) { + methodTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + methodSymbol.setType(methodTypeSymbol); + } + + methodDeclaration.setSymbol(methodSymbol); + methodSymbol.addDeclaration(methodDeclaration); + methodTypeSymbol.addDeclaration(methodDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(methodAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(methodSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(methodAST, TypeScript.SymbolAndDiagnostics.fromSymbol(methodSymbol)); + + if (isOptional) { + methodSymbol.setIsOptional(); + } + + if (!parentHadSymbol) { + parent.addMember(methodSymbol, linkKind); + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = methodTypeSymbol.getCallSignatures(); + var constructSigs = methodTypeSymbol.getConstructSignatures(); + var indexSigs = methodTypeSymbol.getIndexSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + methodTypeSymbol.removeCallSignature(callSigs[i], false); + } + for (var i = 0; i < constructSigs.length; i++) { + methodTypeSymbol.removeConstructSignature(constructSigs[i], false); + } + for (var i = 0; i < indexSigs.length; i++) { + methodTypeSymbol.removeIndexSignature(indexSigs[i], false); + } + + methodSymbol.invalidate(); + methodTypeSymbol.invalidate(); + methodTypeSymbol.recomputeCallSignatures(); + methodTypeSymbol.recomputeConstructSignatures(); + methodTypeSymbol.recomputeIndexSignatures(); + + if (isGeneric) { + var specializations = methodTypeSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + callSigs = specializations[j].getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + callSigs[i].invalidate(); + } + } + } + } + + var sigKind = 1048576 /* CallSignature */; + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(sigKind) : new TypeScript.PullDefinitionSignatureSymbol(sigKind); + + if (methodAST.variableArgList) { + signature.setHasVariableParamList(); + } + + var typeParameters = methodDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + var typeParameterName; + var typeParameterAST; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterName = typeParameters[i].getName(); + typeParameterAST = this.semanticInfo.getASTForDecl(typeParameters[i]); + + typeParameter = signature.findTypeParameter(typeParameterName); + + if (!typeParameter) { + if (!typeParameterAST.constraint) { + typeParameter = this.findTypeParameterInCache(typeParameterName); + } + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName, true); + + if (!typeParameterAST.constraint) { + this.addTypeParameterToCache(typeParameter); + } + } + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + methodDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(methodDeclaration); + methodDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(methodDeclaration), methodTypeSymbol, signature); + + methodTypeSymbol.addSignature(signature); + + if (!isSignature) { + } + + var otherDecls = this.findDeclsInContext(methodDeclaration, methodDeclaration.getKind(), false); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindConstructorDeclarationToPullSymbol = function (constructorDeclaration) { + var declKind = constructorDeclaration.getKind(); + var declFlags = constructorDeclaration.getFlags(); + var constructorAST = this.semanticInfo.getASTForDecl(constructorDeclaration); + + var constructorName = constructorDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(constructorDeclaration, true); + + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var constructorSymbol = parent.getConstructorMethod(); + var constructorTypeSymbol = null; + + var linkKind = 7 /* ConstructorMethod */; + + if (constructorSymbol && (constructorSymbol.getKind() !== 32768 /* ConstructorMethod */ || (!isSignature && constructorSymbol.getType() && constructorSymbol.getType().hasOwnConstructSignatures() && (constructorSymbol.getType()).getDefinitionSignature() && !constructorSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + constructorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), constructorAST.minChar, constructorAST.getLength(), 139 /* Multiple_constructor_implementations_are_not_allowed */, null)); + + constructorSymbol = null; + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.getType(); + + if (this.reBindingAfterChange) { + var decls = constructorSymbol.getDeclarations(); + var scriptName = constructorDeclaration.getScriptName(); + var isGeneric = constructorTypeSymbol.isGeneric(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + constructorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + decls = constructorTypeSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + constructorTypeSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (isGeneric) { + var specializations = constructorTypeSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + } + + constructorSymbol.invalidate(); + constructorTypeSymbol.invalidate(); + } + } + + if (!constructorSymbol) { + constructorSymbol = new TypeScript.PullSymbol(constructorName, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullConstructorTypeSymbol(); + } + + parent.setConstructorMethod(constructorSymbol); + constructorSymbol.setType(constructorTypeSymbol); + + constructorDeclaration.setSymbol(constructorSymbol); + constructorSymbol.addDeclaration(constructorDeclaration); + constructorTypeSymbol.addDeclaration(constructorDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(constructorAST, TypeScript.SymbolAndDiagnostics.fromSymbol(constructorSymbol)); + + if (parentHadSymbol && cleanedPreviousDecls) { + var constructSigs = constructorTypeSymbol.getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + constructorTypeSymbol.removeConstructSignature(constructSigs[i]); + } + + constructorSymbol.invalidate(); + constructorTypeSymbol.invalidate(); + constructorTypeSymbol.recomputeConstructSignatures(); + + if (isGeneric) { + var specializations = constructorTypeSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + constructSigs = specializations[j].getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + constructSigs[i].invalidate(); + } + } + } + } + + var constructSignature = isSignature ? new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */); + + constructSignature.setReturnType(parent); + + constructSignature.addDeclaration(constructorDeclaration); + constructorDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(constructorAST, constructorTypeSymbol, constructSignature); + + var typeParameters = constructorTypeSymbol.getTypeParameters(); + + for (var i = 0; i < typeParameters.length; i++) { + constructSignature.addTypeParameter(typeParameters[i]); + } + + if (constructorAST.variableArgList) { + constructSignature.setHasVariableParamList(); + } + + constructorTypeSymbol.addSignature(constructSignature); + + if (!isSignature) { + } + + var otherDecls = this.findDeclsInContext(constructorDeclaration, constructorDeclaration.getKind(), false); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { + var parent = this.getParent(constructSignatureDeclaration, true); + var constructorAST = this.semanticInfo.getASTForDecl(constructSignatureDeclaration); + + var constructSigs = parent.getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + if (constructSigs[i].getSymbolID() < this.startingSymbolForRebind) { + parent.removeConstructSignature(constructSigs[i], false); + } + } + + parent.recomputeConstructSignatures(); + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + if (constructorAST.variableArgList) { + constructSignature.setHasVariableParamList(); + } + + var typeParameters = constructSignatureDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructSignature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + constructSignature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + constructSignatureDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructSignature.addDeclaration(constructSignatureDeclaration); + constructSignatureDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(constructSignatureDeclaration), null, constructSignature); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(this.semanticInfo.getASTForDecl(constructSignatureDeclaration), TypeScript.SymbolAndDiagnostics.fromSymbol(constructSignature)); + + parent.addConstructSignature(constructSignature); + }; + + PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { + var parent = this.getParent(callSignatureDeclaration, true); + var callSignatureAST = this.semanticInfo.getASTForDecl(callSignatureDeclaration); + + var callSigs = parent.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + if (callSigs[i].getSymbolID() < this.startingSymbolForRebind) { + parent.removeCallSignature(callSigs[i], false); + } + } + + parent.recomputeCallSignatures(); + + var callSignature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */); + + if (callSignatureAST.variableArgList) { + callSignature.setHasVariableParamList(); + } + + var typeParameters = callSignatureDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = callSignature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + callSignature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + callSignatureDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + callSignature.addDeclaration(callSignatureDeclaration); + callSignatureDeclaration.setSignatureSymbol(callSignature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(callSignatureDeclaration), null, callSignature); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(this.semanticInfo.getASTForDecl(callSignatureDeclaration), TypeScript.SymbolAndDiagnostics.fromSymbol(callSignature)); + + parent.addCallSignature(callSignature); + }; + + PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { + var parent = this.getParent(indexSignatureDeclaration, true); + + var indexSigs = parent.getIndexSignatures(); + + for (var i = 0; i < indexSigs.length; i++) { + if (indexSigs[i].getSymbolID() < this.startingSymbolForRebind) { + parent.removeIndexSignature(indexSigs[i], false); + } + } + + parent.recomputeIndexSignatures(); + + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + + var typeParameters = indexSignatureDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = indexSignature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + indexSignature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + indexSignatureDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + indexSignature.addDeclaration(indexSignatureDeclaration); + indexSignatureDeclaration.setSignatureSymbol(indexSignature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(indexSignatureDeclaration), null, indexSignature); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(this.semanticInfo.getASTForDecl(indexSignatureDeclaration), TypeScript.SymbolAndDiagnostics.fromSymbol(indexSignature)); + + parent.addIndexSignature(indexSignature); + }; + + PullSymbolBinder.prototype.bindGetAccessorDeclarationToPullSymbol = function (getAccessorDeclaration) { + var declKind = getAccessorDeclaration.getKind(); + var declFlags = getAccessorDeclaration.getFlags(); + var funcDeclAST = this.semanticInfo.getASTForDecl(getAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = getAccessorDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + var linkKind = 5 /* PublicMember */; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + linkKind = 6 /* PrivateMember */; + } + + var parent = this.getParent(getAccessorDeclaration, true); + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var accessorSymbol = null; + var getterSymbol = null; + var getterTypeSymbol = null; + + if (isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + getAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [getAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + } else { + getterSymbol = accessorSymbol.getGetter(); + + if (getterSymbol && (!this.reBindingAfterChange || this.symbolIsRedeclaration(getterSymbol))) { + getAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 84 /* Getter__0__already_declared */, [getAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + getterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && getterSymbol) { + getterTypeSymbol = getterSymbol.getType(); + } + + if (this.reBindingAfterChange && accessorSymbol) { + var decls = accessorSymbol.getDeclarations(); + var scriptName = getAccessorDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + accessorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (getterSymbol) { + decls = getterSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + getterSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + } + + accessorSymbol.invalidate(); + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!getterSymbol) { + getterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + getterTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + getterSymbol.setType(getterTypeSymbol); + + accessorSymbol.setGetter(getterSymbol); + } + + getAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(getAccessorDeclaration); + getterSymbol.addDeclaration(getAccessorDeclaration); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(getterSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(getterSymbol)); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol, linkKind); + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = getterTypeSymbol.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + getterTypeSymbol.removeCallSignature(callSigs[i], false); + } + + getterSymbol.invalidate(); + getterTypeSymbol.invalidate(); + getterTypeSymbol.recomputeCallSignatures(); + } + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + signature.addDeclaration(getAccessorDeclaration); + getAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(getAccessorDeclaration), getterTypeSymbol, signature); + + var typeParameters = getAccessorDeclaration.getTypeParameters(); + + if (typeParameters.length) { + getAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 86 /* Accessor_cannot_have_type_parameters */, null)); + } + + getterTypeSymbol.addSignature(signature); + + if (!isSignature) { + } + + getterSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { + var declKind = setAccessorDeclaration.getKind(); + var declFlags = setAccessorDeclaration.getFlags(); + var funcDeclAST = this.semanticInfo.getASTForDecl(setAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = setAccessorDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + var linkKind = 5 /* PublicMember */; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + linkKind = 6 /* PrivateMember */; + } + + var parent = this.getParent(setAccessorDeclaration, true); + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var accessorSymbol = null; + var setterSymbol = null; + var setterTypeSymbol = null; + + if (isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + setAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [setAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + } else { + setterSymbol = accessorSymbol.getSetter(); + + if (setterSymbol && (!this.reBindingAfterChange || this.symbolIsRedeclaration(setterSymbol))) { + setAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 85 /* Setter__0__already_declared */, [setAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + setterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && setterSymbol) { + setterTypeSymbol = setterSymbol.getType(); + } + + if (this.reBindingAfterChange && accessorSymbol) { + var decls = accessorSymbol.getDeclarations(); + var scriptName = setAccessorDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + accessorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (setterSymbol) { + decls = setterSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + setterSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + } + + accessorSymbol.invalidate(); + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!setterSymbol) { + setterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + setterTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + setterSymbol.setType(setterTypeSymbol); + + accessorSymbol.setSetter(setterSymbol); + } + + setAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(setAccessorDeclaration); + setterSymbol.addDeclaration(setAccessorDeclaration); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(setterSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(setterSymbol)); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol, linkKind); + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = setterTypeSymbol.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + setterTypeSymbol.removeCallSignature(callSigs[i], false); + } + + setterSymbol.invalidate(); + setterTypeSymbol.invalidate(); + setterTypeSymbol.recomputeCallSignatures(); + } + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + signature.addDeclaration(setAccessorDeclaration); + setAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(setAccessorDeclaration), setterTypeSymbol, signature); + + var typeParameters = setAccessorDeclaration.getTypeParameters(); + + if (typeParameters.length) { + setAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 86 /* Accessor_cannot_have_type_parameters */, null)); + } + + setterTypeSymbol.addSignature(signature); + + if (!isSignature) { + } + + setterSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindCatchBlockPullSymbols = function (catchBlockDecl) { + }; + + PullSymbolBinder.prototype.bindWithBlockPullSymbols = function (withBlockDecl) { + }; + + PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl, rebind) { + if (typeof rebind === "undefined") { rebind = false; } + if (rebind) { + this.startingDeclForRebind = TypeScript.lastBoundPullDeclId; + this.startingSymbolForRebind = TypeScript.lastBoundPullSymbolID; + this.reBindingAfterChange = true; + } + + if (decl.isBound()) { + return; + } + + decl.setIsBound(true); + + switch (decl.getKind()) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + break; + + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + this.bindModuleDeclarationToPullSymbol(decl); + break; + + case 16 /* Interface */: + this.bindInterfaceDeclarationToPullSymbol(decl); + break; + + case 8 /* Class */: + this.bindClassDeclarationToPullSymbol(decl); + break; + + case 16384 /* Function */: + this.bindFunctionDeclarationToPullSymbol(decl); + break; + + case 1024 /* Variable */: + this.bindVariableDeclarationToPullSymbol(decl); + break; + + case 67108864 /* EnumMember */: + case 4096 /* Property */: + this.bindPropertyDeclarationToPullSymbol(decl); + break; + + case 65536 /* Method */: + this.bindMethodDeclarationToPullSymbol(decl); + break; + + case 32768 /* ConstructorMethod */: + this.bindConstructorDeclarationToPullSymbol(decl); + break; + + case 1048576 /* CallSignature */: + this.bindCallSignatureDeclarationToPullSymbol(decl); + break; + + case 2097152 /* ConstructSignature */: + this.bindConstructSignatureDeclarationToPullSymbol(decl); + break; + + case 4194304 /* IndexSignature */: + this.bindIndexSignatureDeclarationToPullSymbol(decl); + break; + + case 262144 /* GetAccessor */: + this.bindGetAccessorDeclarationToPullSymbol(decl); + break; + + case 524288 /* SetAccessor */: + this.bindSetAccessorDeclarationToPullSymbol(decl); + break; + + case 8388608 /* ObjectType */: + this.bindObjectTypeDeclarationToPullSymbol(decl); + break; + + case 16777216 /* FunctionType */: + this.bindFunctionTypeDeclarationToPullSymbol(decl); + break; + + case 33554432 /* ConstructorType */: + this.bindConstructorTypeDeclarationToPullSymbol(decl); + break; + + case 131072 /* FunctionExpression */: + this.bindFunctionExpressionToPullSymbol(decl); + break; + + case 256 /* TypeAlias */: + this.bindImportDeclaration(decl); + break; + + case 2048 /* Parameter */: + case 8192 /* TypeParameter */: + break; + + case 1073741824 /* CatchBlock */: + this.bindCatchBlockPullSymbols(decl); + + case 536870912 /* WithBlock */: + this.bindWithBlockPullSymbols(decl); + break; + + default: + throw new Error("Unrecognized type declaration"); + } + }; + + PullSymbolBinder.prototype.bindDeclsForUnit = function (filePath, rebind) { + if (typeof rebind === "undefined") { rebind = false; } + this.setUnit(filePath); + + var topLevelDecls = this.semanticInfo.getTopLevelDecls(); + + for (var i = 0; i < topLevelDecls.length; i++) { + this.bindDeclToPullSymbol(topLevelDecls[i], rebind); + } + }; + return PullSymbolBinder; + })(); + TypeScript.PullSymbolBinder = PullSymbolBinder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.linkID = 0; + + var IListItem = (function () { + function IListItem(value) { + this.value = value; + this.next = null; + this.prev = null; + } + return IListItem; + })(); + TypeScript.IListItem = IListItem; + + var LinkList = (function () { + function LinkList() { + this.head = null; + this.last = null; + this.length = 0; + } + LinkList.prototype.addItem = function (item) { + if (!this.head) { + this.head = new IListItem(item); + this.last = this.head; + } else { + this.last.next = new IListItem(item); + this.last.next.prev = this.last; + this.last = this.last.next; + } + + this.length++; + }; + + LinkList.prototype.find = function (p) { + var node = this.head; + var vals = []; + + while (node) { + if (p(node.value)) { + vals[vals.length] = node.value; + } + node = node.next; + } + + return vals; + }; + + LinkList.prototype.remove = function (p) { + var node = this.head; + var prev = null; + var next = null; + + while (node) { + if (p(node.value)) { + if (node === this.head) { + if (this.last === this.head) { + this.last = null; + } + + this.head = this.head.next; + + if (this.head) { + this.head.prev = null; + } + } else { + prev = node.prev; + next = node.next; + + if (prev) { + prev.next = next; + } + if (next) { + next.prev = prev; + } + + if (node === this.last) { + this.last = prev; + } + } + + this.length--; + } + node = node.next; + } + }; + + LinkList.prototype.update = function (map, context) { + var node = this.head; + + while (node) { + map(node.value, context); + + node = node.next; + } + }; + return LinkList; + })(); + TypeScript.LinkList = LinkList; + + var PullSymbolLink = (function () { + function PullSymbolLink(start, end, kind) { + this.start = start; + this.end = end; + this.kind = kind; + this.id = TypeScript.linkID++; + } + return PullSymbolLink; + })(); + TypeScript.PullSymbolLink = PullSymbolLink; + + (function (GraphUpdateKind) { + GraphUpdateKind[GraphUpdateKind["NoUpdate"] = 0] = "NoUpdate"; + + GraphUpdateKind[GraphUpdateKind["SymbolRemoved"] = 1] = "SymbolRemoved"; + GraphUpdateKind[GraphUpdateKind["SymbolAdded"] = 2] = "SymbolAdded"; + + GraphUpdateKind[GraphUpdateKind["TypeChanged"] = 3] = "TypeChanged"; + })(TypeScript.GraphUpdateKind || (TypeScript.GraphUpdateKind = {})); + var GraphUpdateKind = TypeScript.GraphUpdateKind; + + var PullSymbolUpdate = (function () { + function PullSymbolUpdate(updateKind, symbolToUpdate, updater) { + this.updateKind = updateKind; + this.symbolToUpdate = symbolToUpdate; + this.updater = updater; + } + return PullSymbolUpdate; + })(); + TypeScript.PullSymbolUpdate = PullSymbolUpdate; + + TypeScript.updateVersion = 0; + + var PullSymbolGraphUpdater = (function () { + function PullSymbolGraphUpdater(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + } + PullSymbolGraphUpdater.prototype.removeDecl = function (declToRemove) { + var declSymbol = declToRemove.getSymbol(); + + if (declSymbol) { + declSymbol.removeDeclaration(declToRemove); + + var childDecls = declToRemove.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.removeDecl(childDecls[i]); + } + + var remainingDecls = declSymbol.getDeclarations(); + + if (!remainingDecls.length) { + this.removeSymbol(declSymbol); + + this.semanticInfoChain.removeSymbolFromCache(declSymbol); + } else { + declSymbol.invalidate(); + } + } + + var valDecl = declToRemove.getValueDecl(); + + if (valDecl) { + this.removeDecl(valDecl); + } + + TypeScript.updateVersion++; + }; + + PullSymbolGraphUpdater.prototype.addDecl = function (declToAdd) { + var symbolToAdd = declToAdd.getSymbol(); + + if (symbolToAdd) { + this.addSymbol(symbolToAdd); + } + + TypeScript.updateVersion++; + }; + + PullSymbolGraphUpdater.prototype.removeSymbol = function (symbolToRemove) { + if (symbolToRemove.removeUpdateVersion === TypeScript.updateVersion) { + return; + } + + symbolToRemove.removeUpdateVersion = TypeScript.updateVersion; + + symbolToRemove.updateOutgoingLinks(propagateRemovalToOutgoingLinks, new PullSymbolUpdate(1 /* SymbolRemoved */, symbolToRemove, this)); + + symbolToRemove.updateIncomingLinks(propagateRemovalToIncomingLinks, new PullSymbolUpdate(1 /* SymbolRemoved */, symbolToRemove, this)); + + symbolToRemove.unsetContainer(); + + this.semanticInfoChain.removeSymbolFromCache(symbolToRemove); + + var container = symbolToRemove.getContainer(); + + if (container) { + container.removeMember(symbolToRemove); + this.semanticInfoChain.removeSymbolFromCache(symbolToRemove); + } + + if (symbolToRemove.isAccessor()) { + var getterSymbol = (symbolToRemove).getGetter(); + var setterSymbol = (symbolToRemove).getSetter(); + + if (getterSymbol) { + this.removeSymbol(getterSymbol); + } + + if (setterSymbol) { + this.removeSymbol(setterSymbol); + } + } + + symbolToRemove.removeAllLinks(); + }; + + PullSymbolGraphUpdater.prototype.addSymbol = function (symbolToAdd) { + if (symbolToAdd.addUpdateVersion === TypeScript.updateVersion) { + return; + } + + symbolToAdd.addUpdateVersion = TypeScript.updateVersion; + + symbolToAdd.updateOutgoingLinks(propagateAdditionToOutgoingLinks, new PullSymbolUpdate(2 /* SymbolAdded */, symbolToAdd, this)); + + symbolToAdd.updateIncomingLinks(propagateAdditionToIncomingLinks, new PullSymbolUpdate(2 /* SymbolAdded */, symbolToAdd, this)); + }; + + PullSymbolGraphUpdater.prototype.invalidateType = function (symbolWhoseTypeChanged) { + if (!symbolWhoseTypeChanged) { + return; + } + + if (symbolWhoseTypeChanged.isPrimitive()) { + return; + } + + if (symbolWhoseTypeChanged.typeChangeUpdateVersion === TypeScript.updateVersion) { + return; + } + + symbolWhoseTypeChanged.typeChangeUpdateVersion = TypeScript.updateVersion; + + symbolWhoseTypeChanged.updateOutgoingLinks(propagateChangedTypeToOutgoingLinks, new PullSymbolUpdate(3 /* TypeChanged */, symbolWhoseTypeChanged, this)); + + symbolWhoseTypeChanged.updateIncomingLinks(propagateChangedTypeToIncomingLinks, new PullSymbolUpdate(3 /* TypeChanged */, symbolWhoseTypeChanged, this)); + + if (symbolWhoseTypeChanged.getKind() === 4 /* Container */) { + var instanceSymbol = (symbolWhoseTypeChanged).getInstanceSymbol(); + + this.invalidateType(instanceSymbol); + } + + if (symbolWhoseTypeChanged.isResolved()) { + symbolWhoseTypeChanged.invalidate(); + } + + this.invalidateUnitsForSymbol(symbolWhoseTypeChanged); + }; + + PullSymbolGraphUpdater.prototype.invalidateUnitsForSymbol = function (symbol) { + var declarations = symbol.getDeclarations(); + + for (var i = 0; i < declarations.length; i++) { + this.semanticInfoChain.invalidateUnit(declarations[i].getScriptName()); + } + }; + return PullSymbolGraphUpdater; + })(); + TypeScript.PullSymbolGraphUpdater = PullSymbolGraphUpdater; + + function propagateRemovalToOutgoingLinks(link, update) { + var symbolToRemove = update.symbolToUpdate; + var affectedSymbol = link.end; + + if (affectedSymbol.removeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 2 /* ProvidesInferredType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + (symbolToRemove).removeSpecialization(affectedSymbol); + update.updater.removeSymbol(affectedSymbol); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.removeSymbol(affectedSymbol); + } else if (link.kind === 6 /* PrivateMember */) { + update.updater.removeSymbol(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 10 /* ContainedBy */) { + (affectedSymbol).removeMember(symbolToRemove); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 13 /* Parameter */) { + update.updater.removeSymbol(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } + + symbolToRemove.removeOutgoingLink(link); + } + TypeScript.propagateRemovalToOutgoingLinks = propagateRemovalToOutgoingLinks; + + function propagateRemovalToIncomingLinks(link, update) { + var symbolToRemove = update.symbolToUpdate; + var affectedSymbol = link.start; + + if (affectedSymbol.removeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 0 /* TypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 1 /* ContextuallyTypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + (affectedSymbol).removeSpecialization(symbolToRemove); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + (affectedSymbol).removeMember(symbolToRemove); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 6 /* PrivateMember */) { + (affectedSymbol).removeMember(symbolToRemove); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 10 /* ContainedBy */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 11 /* Extends */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 12 /* Implements */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 13 /* Parameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 8 /* Aliases */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 9 /* ExportAliases */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateRemovalToIncomingLinks = propagateRemovalToIncomingLinks; + + function propagateAdditionToOutgoingLinks(link, update) { + var symbolToAdd = update.symbolToUpdate; + var affectedSymbol = link.end; + + if (affectedSymbol.addUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 10 /* ContainedBy */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 2 /* ProvidesInferredType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateAdditionToOutgoingLinks = propagateAdditionToOutgoingLinks; + + function propagateAdditionToIncomingLinks(link, update) { + var symbolToAdd = update.symbolToUpdate; + var affectedSymbol = link.start; + + if (affectedSymbol.addUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 0 /* TypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 1 /* ContextuallyTypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 11 /* Extends */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 12 /* Implements */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 8 /* Aliases */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 9 /* ExportAliases */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateAdditionToIncomingLinks = propagateAdditionToIncomingLinks; + + function propagateChangedTypeToOutgoingLinks(link, update) { + var symbolWhoseTypeChanged = update.symbolToUpdate; + var affectedSymbol = link.end; + + if (affectedSymbol.typeChangeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 2 /* ProvidesInferredType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 10 /* ContainedBy */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateChangedTypeToOutgoingLinks = propagateChangedTypeToOutgoingLinks; + + function propagateChangedTypeToIncomingLinks(link, update) { + var symbolWhoseTypeChanged = update.symbolToUpdate; + var affectedSymbol = link.start; + + if (affectedSymbol.typeChangeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 0 /* TypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 1 /* ContextuallyTypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 11 /* Extends */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 12 /* Implements */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 8 /* Aliases */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 9 /* ExportAliases */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateChangedTypeToIncomingLinks = propagateChangedTypeToIncomingLinks; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SemanticDiagnostic = (function (_super) { + __extends(SemanticDiagnostic, _super); + function SemanticDiagnostic() { + _super.apply(this, arguments); + } + SemanticDiagnostic.equals = function (diagnostic1, diagnostic2) { + return TypeScript.Diagnostic.equals(diagnostic1, diagnostic2); + }; + return SemanticDiagnostic; + })(TypeScript.Diagnostic); + TypeScript.SemanticDiagnostic = SemanticDiagnostic; + + function getDiagnosticsFromEnclosingDecl(enclosingDecl, errors) { + var declErrors = enclosingDecl.getDiagnostics(); + + if (declErrors) { + for (var i = 0; i < declErrors.length; i++) { + errors[errors.length] = declErrors[i]; + } + } + + var childDecls = enclosingDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + getDiagnosticsFromEnclosingDecl(childDecls[i], errors); + } + } + TypeScript.getDiagnosticsFromEnclosingDecl = getDiagnosticsFromEnclosingDecl; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullHelpers) { + function getSignatureForFuncDecl(funcDecl, semanticInfo) { + var functionDecl = semanticInfo.getDeclForAST(funcDecl); + var funcSymbol = functionDecl.getSymbol(); + + if (!funcSymbol) { + funcSymbol = functionDecl.getSignatureSymbol(); + } + + var functionSignature = null; + var typeSymbolWithAllSignatures = null; + if (funcSymbol.isSignature()) { + functionSignature = funcSymbol; + var parent = functionDecl.getParentDecl(); + typeSymbolWithAllSignatures = parent.getSymbol().getType(); + } else { + functionSignature = functionDecl.getSignatureSymbol(); + typeSymbolWithAllSignatures = funcSymbol.getType(); + } + var signatures; + if (funcDecl.isConstructor || funcDecl.isConstructMember()) { + signatures = typeSymbolWithAllSignatures.getConstructSignatures(); + } else if (funcDecl.isIndexerMember()) { + signatures = typeSymbolWithAllSignatures.getIndexSignatures(); + } else { + signatures = typeSymbolWithAllSignatures.getCallSignatures(); + } + return { + signature: functionSignature, + allSignatures: signatures + }; + } + PullHelpers.getSignatureForFuncDecl = getSignatureForFuncDecl; + + function getAccessorSymbol(getterOrSetter, semanticInfoChain, unitPath) { + var functionDecl = semanticInfoChain.getDeclForAST(getterOrSetter, unitPath); + var getterOrSetterSymbol = functionDecl.getSymbol(); + + return getterOrSetterSymbol; + } + PullHelpers.getAccessorSymbol = getAccessorSymbol; + + function getGetterAndSetterFunction(funcDecl, semanticInfoChain, unitPath) { + var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, semanticInfoChain, unitPath); + var result = { + getter: null, + setter: null + }; + var getter = accessorSymbol.getGetter(); + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + result.getter = semanticInfoChain.getASTForDecl(getterDecl); + } + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + result.setter = semanticInfoChain.getASTForDecl(setterDecl); + } + + return result; + } + PullHelpers.getGetterAndSetterFunction = getGetterAndSetterFunction; + + function symbolIsEnum(source) { + return source && ((source.getKind() & (64 /* Enum */ | 67108864 /* EnumMember */)) || source.hasFlag(131072 /* InitializedEnum */)); + } + PullHelpers.symbolIsEnum = symbolIsEnum; + })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); + var PullHelpers = TypeScript.PullHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var incrementalAst = true; + var SyntaxPositionMap = (function () { + function SyntaxPositionMap(node) { + this.position = 0; + this.elementToPosition = TypeScript.Collections.createHashTable(2048, TypeScript.Collections.identityHashCode); + this.process(node); + } + SyntaxPositionMap.prototype.process = function (element) { + if (element !== null) { + if (element.isToken()) { + this.elementToPosition.add(element, this.position); + this.position += element.fullWidth(); + } else { + if (element.isNode() || (element.isList() && (element).childCount() > 0) || (element.isSeparatedList() && (element).childCount() > 0)) { + this.elementToPosition.add(element, this.position); + } + + for (var i = 0, n = element.childCount(); i < n; i++) { + this.process(element.childAt(i)); + } + } + } + }; + + SyntaxPositionMap.create = function (node) { + var map = new SyntaxPositionMap(node); + return map; + }; + + SyntaxPositionMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxPositionMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxPositionMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxPositionMap.prototype.fullEnd = function (element) { + return this.fullStart(element) + element.fullWidth(); + }; + return SyntaxPositionMap; + })(); + TypeScript.SyntaxPositionMap = SyntaxPositionMap; + + var SyntaxTreeToAstVisitor = (function () { + function SyntaxTreeToAstVisitor(syntaxPositionMap, fileName, lineMap, compilationSettings) { + this.syntaxPositionMap = syntaxPositionMap; + this.fileName = fileName; + this.lineMap = lineMap; + this.compilationSettings = compilationSettings; + this.position = 0; + this.requiresExtendsBlock = false; + this.previousTokenTrailingComments = null; + this.isParsingAmbientModule = false; + this.containingModuleHasExportAssignment = false; + this.isParsingDeclareFile = TypeScript.isDTSFile(fileName); + } + SyntaxTreeToAstVisitor.visit = function (syntaxTree, fileName, compilationSettings) { + var map = SyntaxTreeToAstVisitor.checkPositions ? SyntaxPositionMap.create(syntaxTree.sourceUnit()) : null; + var visitor = new SyntaxTreeToAstVisitor(map, fileName, syntaxTree.lineMap(), compilationSettings); + return syntaxTree.sourceUnit().accept(visitor); + }; + + SyntaxTreeToAstVisitor.prototype.assertElementAtPosition = function (element) { + if (SyntaxTreeToAstVisitor.checkPositions) { + TypeScript.Debug.assert(this.position === this.syntaxPositionMap.fullStart(element)); + } + }; + + SyntaxTreeToAstVisitor.prototype.movePast = function (element) { + if (element !== null) { + this.assertElementAtPosition(element); + this.position += element.fullWidth(); + } + }; + + SyntaxTreeToAstVisitor.prototype.moveTo = function (element1, element2) { + if (element2 !== null) { + this.position += TypeScript.Syntax.childOffset(element1, element2); + } + }; + + SyntaxTreeToAstVisitor.prototype.applyDelta = function (ast, delta) { + var _this = this; + if (delta === 0) { + return; + } + + var applyDelta = function (ast) { + if (ast.minChar !== -1) { + ast.minChar += delta; + } + if (ast.limChar !== -1) { + ast.limChar += delta; + } + }; + + var applyDeltaToComments = function (comments) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + applyDelta(comment); + comment.minLine = _this.lineMap.getLineNumberFromPosition(comment.minChar); + comment.limLine = _this.lineMap.getLineNumberFromPosition(comment.limChar); + } + } + }; + + var pre = function (cur, parent, walker) { + applyDelta(cur); + applyDeltaToComments(cur.preComments); + applyDeltaToComments(cur.postComments); + + return cur; + }; + + TypeScript.getAstWalkerFactory().walk(ast, pre); + }; + + SyntaxTreeToAstVisitor.prototype.setSpan = function (span, fullStart, element) { + var desiredMinChar = fullStart + element.leadingTriviaWidth(); + var desiredLimChar = desiredMinChar + element.width(); + + this.setSpanExplicit(span, desiredMinChar, desiredLimChar); + + span.trailingTriviaWidth = element.trailingTriviaWidth(); + }; + + SyntaxTreeToAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + if (span.minChar !== -1) { + TypeScript.Debug.assert(span.limChar !== -1); + TypeScript.Debug.assert((span).nodeType !== undefined); + + var delta = start - span.minChar; + this.applyDelta(span, delta); + + span.limChar = end; + + TypeScript.Debug.assert(span.minChar === start); + TypeScript.Debug.assert(span.limChar === end); + } else { + TypeScript.Debug.assert(span.limChar === -1); + + span.minChar = start; + span.limChar = end; + } + + TypeScript.Debug.assert(!isNaN(span.minChar)); + TypeScript.Debug.assert(!isNaN(span.limChar)); + TypeScript.Debug.assert(span.minChar !== -1); + TypeScript.Debug.assert(span.limChar !== -1); + }; + + SyntaxTreeToAstVisitor.prototype.identifierFromToken = function (token, isOptional, useValueText) { + this.assertElementAtPosition(token); + + var result = null; + if (token.fullWidth() === 0) { + result = new TypeScript.MissingIdentifier(); + } else { + result = new TypeScript.Identifier(token.text()); + result.text = useValueText ? token.valueText() : result.text; + if (result.text == SyntaxTreeToAstVisitor.protoString) { + result.text = SyntaxTreeToAstVisitor.protoSubstitutionString; + } + } + + if (isOptional) { + result.setFlags(result.getFlags() | 4 /* OptionalName */); + } + + var start = this.position + token.leadingTriviaWidth(); + this.setSpanExplicit(result, start, start + token.width()); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getAST = function (element) { + if (this.previousTokenTrailingComments !== null) { + return null; + } + + if (incrementalAst) { + var result = (element)._ast; + return result ? result : null; + } else { + return null; + } + }; + + SyntaxTreeToAstVisitor.prototype.setAST = function (element, ast) { + if (incrementalAst) { + (element)._ast = ast; + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSyntaxList = function (list) { + var start = this.position; + var result = this.getAST(list); + if (result) { + this.movePast(list); + } else { + result = new TypeScript.ASTList(); + + for (var i = 0, n = list.childCount(); i < n; i++) { + result.append(list.childAt(i).accept(this)); + } + + if (n > 0) { + this.setAST(list, result); + } + } + + this.setSpan(result, start, list); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var start = this.position; + var result = this.getAST(list); + if (result) { + this.movePast(list); + } else { + result = new TypeScript.ASTList(); + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i % 2 === 0) { + result.append(list.childAt(i).accept(this)); + this.previousTokenTrailingComments = null; + } else { + var separatorToken = list.childAt(i); + this.previousTokenTrailingComments = this.convertTokenTrailingComments(separatorToken, this.position + separatorToken.leadingTriviaWidth() + separatorToken.width()); + this.movePast(separatorToken); + } + } + + result.postComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + if (n > 0) { + this.setAST(list, result); + } + } + + this.setSpan(result, start, list); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.createRef = function (text, minChar) { + var id = new TypeScript.Identifier(text); + id.minChar = minChar; + return id; + }; + + SyntaxTreeToAstVisitor.prototype.convertComment = function (trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia.fullText(), trivia.kind() === 6 /* MultiLineCommentTrivia */, hasTrailingNewLine); + + comment.minChar = commentStartPosition; + comment.limChar = commentStartPosition + trivia.fullWidth(); + comment.minLine = this.lineMap.getLineNumberFromPosition(comment.minChar); + comment.limLine = this.lineMap.getLineNumberFromPosition(comment.limChar); + + return comment; + }; + + SyntaxTreeToAstVisitor.prototype.convertComments = function (triviaList, commentStartPosition) { + var result = []; + + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result.push(this.convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + + commentStartPosition += trivia.fullWidth(); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.mergeComments = function (comments1, comments2) { + if (comments1 === null) { + return comments2; + } + + if (comments2 === null) { + return comments1; + } + + return comments1.concat(comments2); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenLeadingComments = function (token, commentStartPosition) { + if (token === null) { + return null; + } + + var preComments = token.hasLeadingComment() ? this.convertComments(token.leadingTrivia(), commentStartPosition) : null; + + var previousTokenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + return this.mergeComments(previousTokenTrailingComments, preComments); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenTrailingComments = function (token, commentStartPosition) { + if (token === null || !token.hasTrailingComment() || token.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(token.trailingTrivia(), commentStartPosition); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeLeadingComments = function (node, nodeStart) { + return this.convertTokenLeadingComments(node.firstToken(), nodeStart); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeTrailingComments = function (node, nodeStart) { + return this.convertTokenTrailingComments(node.lastToken(), nodeStart + node.leadingTriviaWidth() + node.width()); + }; + + SyntaxTreeToAstVisitor.prototype.visitToken = function (token) { + this.assertElementAtPosition(token); + + var result = this.getAST(token); + var fullStart = this.position; + + if (result) { + this.movePast(token); + } else { + if (token.kind() === 35 /* ThisKeyword */) { + result = new TypeScript.ThisExpression(); + } else if (token.kind() === 50 /* SuperKeyword */) { + result = new TypeScript.SuperExpression(); + } else if (token.kind() === 37 /* TrueKeyword */) { + result = new TypeScript.LiteralExpression(3 /* TrueLiteral */); + } else if (token.kind() === 24 /* FalseKeyword */) { + result = new TypeScript.LiteralExpression(4 /* FalseLiteral */); + } else if (token.kind() === 32 /* NullKeyword */) { + result = new TypeScript.LiteralExpression(8 /* NullLiteral */); + } else if (token.kind() === 14 /* StringLiteral */) { + result = new TypeScript.StringLiteral(token.text(), token.valueText()); + } else if (token.kind() === 12 /* RegularExpressionLiteral */) { + result = new TypeScript.RegexLiteral(token.text()); + } else if (token.kind() === 13 /* NumericLiteral */) { + var preComments = this.convertTokenLeadingComments(token, fullStart); + + var value = token.text().indexOf(".") > 0 ? parseFloat(token.text()) : parseInt(token.text()); + result = new TypeScript.NumberLiteral(value, token.text()); + + result.preComments = preComments; + } else { + result = this.identifierFromToken(token, false, true); + } + + this.movePast(token); + } + + var start = fullStart + token.leadingTriviaWidth(); + this.setAST(token, result); + this.setSpanExplicit(result, start, start + token.width()); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getLeadingComments = function (node) { + var firstToken = node.firstToken(); + var result = []; + + if (firstToken.hasLeadingComment()) { + var leadingTrivia = firstToken.leadingTrivia(); + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.isComment()) { + result.push(trivia); + } + } + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.hasTopLevelImportOrExport = function (node) { + var firstToken; + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var moduleElement = node.moduleElements.childAt(i); + + firstToken = moduleElement.firstToken(); + if (firstToken !== null && firstToken.kind() === 47 /* ExportKeyword */) { + return true; + } + + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + return true; + } + } + } + + var leadingComments = this.getLeadingComments(node); + for (var i = 0, n = leadingComments.length; i < n; i++) { + var trivia = leadingComments[i]; + + if (TypeScript.getImplicitImport(trivia.fullText())) { + return true; + } + } + + return false; + }; + + SyntaxTreeToAstVisitor.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s* 0; + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setVarFlags(result.getVarFlags() | 1 /* Exported */); + } else { + result.setVarFlags(result.getVarFlags() & ~1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + result.setVarFlags(result.getVarFlags() | 8 /* Ambient */); + } else { + result.setVarFlags(result.getVarFlags() & ~8 /* Ambient */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + + var extendsList = null; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + var heritageClause = node.heritageClauses.childAt(i); + if (i === 0) { + extendsList = heritageClause.accept(this); + } else { + this.movePast(heritageClause); + } + } + + this.movePast(node.body.openBraceToken); + var members = this.visitSeparatedSyntaxList(node.body.typeMembers); + + this.movePast(node.body.closeBraceToken); + + result = new TypeScript.InterfaceDeclaration(name, typeParameters, members, extendsList, null); + + result.preComments = preComments; + result.postComments = postComments; + } + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setVarFlags(result.getVarFlags() | 1 /* Exported */); + } else { + result.setVarFlags(result.getVarFlags() & ~1 /* Exported */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitHeritageClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + result = new TypeScript.ASTList(); + + this.movePast(node.extendsOrImplementsKeyword); + for (var i = 0, n = node.typeNames.childCount(); i < n; i++) { + if (i % 2 === 1) { + this.movePast(node.typeNames.childAt(i)); + } else { + var type = this.visitType(node.typeNames.childAt(i)).term; + result.append(type); + } + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getModuleNames = function (node) { + var result = []; + + if (node.stringLiteral !== null) { + result.push(this.identifierFromToken(node.stringLiteral, false, false)); + this.movePast(node.stringLiteral); + } else { + this.getModuleNamesHelper(node.moduleName, result); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getModuleNamesHelper = function (name, result) { + this.assertElementAtPosition(name); + + if (name.kind() === 122 /* QualifiedName */) { + var qualifiedName = name; + this.getModuleNamesHelper(qualifiedName.left, result); + this.movePast(qualifiedName.dotToken); + result.push(this.identifierFromToken(qualifiedName.right, false, false)); + this.movePast(qualifiedName.right); + } else { + result.push(this.identifierFromToken(name, false, false)); + this.movePast(name); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.moduleKeyword); + this.movePast(node.moduleKeyword); + var names = this.getModuleNames(node); + this.movePast(node.openBraceToken); + + var savedIsParsingAmbientModule = this.isParsingAmbientModule; + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingDeclareFile) { + this.isParsingAmbientModule = true; + } + + var savedContainingModuleHasExportAssignment = this.containingModuleHasExportAssignment; + this.containingModuleHasExportAssignment = TypeScript.ArrayUtilities.any(node.moduleElements.toArray(), function (m) { + return m.kind() === 134 /* ExportAssignment */; + }); + + var members = this.visitSyntaxList(node.moduleElements); + + this.isParsingAmbientModule = savedIsParsingAmbientModule; + this.containingModuleHasExportAssignment = savedContainingModuleHasExportAssignment; + + var closeBracePosition = this.position; + this.movePast(node.closeBraceToken); + var closeBraceSpan = new TypeScript.ASTSpan(); + this.setSpan(closeBraceSpan, closeBracePosition, node.closeBraceToken); + + for (var i = names.length - 1; i >= 0; i--) { + var innerName = names[i]; + + result = new TypeScript.ModuleDeclaration(innerName, members, closeBraceSpan); + this.setSpan(result, start, node); + + result.preComments = preComments; + result.postComments = postComments; + + preComments = null; + postComments = null; + + if (i) { + result.setModuleFlags(result.getModuleFlags() | 1 /* Exported */); + } else if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setModuleFlags(result.getModuleFlags() | 1 /* Exported */); + } + + members = new TypeScript.ASTList(); + members.append(result); + } + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + result.setModuleFlags(result.getModuleFlags() | 8 /* Ambient */); + } else { + result.setModuleFlags(result.getModuleFlags() & ~8 /* Ambient */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.hasDotDotDotParameter = function (parameters) { + for (var i = 0, n = parameters.nonSeparatorCount(); i < n; i++) { + if ((parameters.nonSeparatorAt(i)).dotDotDotToken) { + return true; + } + } + + return false; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + + this.movePast(node.identifier); + + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + result = new TypeScript.FunctionDeclaration(name, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + if (node.semicolonToken) { + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + } + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setFunctionFlags(result.getFunctionFlags() | 1 /* Exported */); + } else { + result.setFunctionFlags(result.getFunctionFlags() & ~1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + result.setFunctionFlags(result.getFunctionFlags() | 8 /* Ambient */); + } else { + result.setFunctionFlags(result.getFunctionFlags() & ~8 /* Ambient */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + + this.movePast(node.openBraceToken); + var members = new TypeScript.ASTList(); + + var lastValue = null; + var memberNames = []; + var memberName; + + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + if (i % 2 === 1) { + this.movePast(node.enumElements.childAt(i)); + } else { + var enumElement = node.enumElements.childAt(i); + + var memberValue = null; + + memberName = this.identifierFromToken(enumElement.propertyName, false, true); + this.movePast(enumElement.propertyName); + + if (enumElement.equalsValueClause !== null) { + memberValue = enumElement.equalsValueClause.accept(this); + lastValue = null; + } + + var memberStart = this.position; + + if (memberValue === null) { + if (lastValue === null) { + memberValue = new TypeScript.NumberLiteral(0, "0"); + lastValue = memberValue; + } else { + var nextValue = lastValue.value + 1; + memberValue = new TypeScript.NumberLiteral(nextValue, nextValue.toString()); + lastValue = memberValue; + } + } + + var declarator = new TypeScript.VariableDeclarator(memberName); + declarator.init = memberValue; + declarator.isImplicitlyInitialized = enumElement.equalsValueClause === null; + + declarator.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, -1), 0); + declarator.setVarFlags(declarator.getVarFlags() | 256 /* Property */); + this.setSpanExplicit(declarator, memberStart, this.position); + + if (memberValue.nodeType === 7 /* NumericLiteral */) { + declarator.setVarFlags(declarator.getVarFlags() | 4096 /* Constant */); + } else if (memberValue.nodeType === 69 /* LeftShiftExpression */) { + var binop = memberValue; + if (binop.operand1.nodeType === 7 /* NumericLiteral */ && binop.operand2.nodeType === 7 /* NumericLiteral */) { + declarator.setVarFlags(declarator.getVarFlags() | 4096 /* Constant */); + } + } else if (memberValue.nodeType === 20 /* Name */) { + var nameNode = memberValue; + for (var j = 0; j < memberNames.length; j++) { + memberName = memberNames[j]; + if (memberName.text === nameNode.text) { + declarator.setVarFlags(declarator.getVarFlags() | 4096 /* Constant */); + break; + } + } + } + + var declarators = new TypeScript.ASTList(); + declarators.append(declarator); + var declaration = new TypeScript.VariableDeclaration(declarators); + this.setSpanExplicit(declaration, memberStart, this.position); + + var statement = new TypeScript.VariableStatement(declaration); + statement.setFlags(16 /* EnumElement */); + this.setSpanExplicit(statement, memberStart, this.position); + + members.append(statement); + memberNames.push(memberName); + + declarator.setVarFlags(declarator.getVarFlags() | 1 /* Exported */); + } + } + + var closeBracePosition = this.position; + this.movePast(node.closeBraceToken); + var closeBraceSpan = new TypeScript.ASTSpan(); + this.setSpan(closeBraceSpan, closeBracePosition, node.closeBraceToken); + + var modDecl = new TypeScript.ModuleDeclaration(name, members, closeBraceSpan); + this.setSpan(modDecl, start, node); + + modDecl.preComments = preComments; + modDecl.postComments = postComments; + modDecl.setModuleFlags(modDecl.getModuleFlags() | 128 /* IsEnum */); + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + modDecl.setModuleFlags(modDecl.getModuleFlags() | 1 /* Exported */); + } + + return modDecl; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumElement = function (node) { + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxTreeToAstVisitor.prototype.visitImportDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.equalsToken); + var alias = node.moduleReference.accept(this); + this.movePast(node.semicolonToken); + + result = new TypeScript.ImportDeclaration(name, alias); + + result.preComments = preComments; + result.postComments = postComments; + result.isDynamicImport = node.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExportAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.semicolonToken); + + result = new TypeScript.ExportAssignment(name); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var preComments = null; + if (node.modifiers.childCount() > 0) { + preComments = this.convertTokenLeadingComments(node.modifiers.firstToken(), start); + } + + this.moveTo(node, node.variableDeclaration); + + var declaration = node.variableDeclaration.accept(this); + this.movePast(node.semicolonToken); + + for (var i = 0, n = declaration.declarators.members.length; i < n; i++) { + var varDecl = declaration.declarators.members[i]; + + if (i === 0) { + varDecl.preComments = this.mergeComments(preComments, varDecl.preComments); + } + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + varDecl.setVarFlags(varDecl.getVarFlags() | 1 /* Exported */); + } else { + varDecl.setVarFlags(varDecl.getVarFlags() & ~1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + varDecl.setVarFlags(varDecl.getVarFlags() | 8 /* Ambient */); + } else { + varDecl.setVarFlags(varDecl.getVarFlags() & ~8 /* Ambient */); + } + } + + var result = new TypeScript.VariableStatement(declaration); + + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.variableDeclarators); + var variableDecls = this.visitSeparatedSyntaxList(node.variableDeclarators); + + for (var i = 0; i < variableDecls.members.length; i++) { + if (i === 0) { + variableDecls.members[i].preComments = preComments; + variableDecls.members[i].postComments = postComments; + } + } + + var result = new TypeScript.VariableDeclaration(variableDecls); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclarator = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + var result = new TypeScript.VariableDeclarator(name); + this.setSpan(result, start, node); + + result.typeExpr = typeExpr; + result.init = init; + if (init && init.nodeType === 12 /* FunctionDeclaration */) { + var funcDecl = init; + funcDecl.hint = name.actualText; + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEqualsValueClause = function (node) { + this.assertElementAtPosition(node); + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(node.equalsToken, this.position + node.equalsToken.leadingTriviaWidth() + node.equalsToken.width()); + + this.movePast(node.equalsToken); + var result = node.value.accept(this); + + this.previousTokenTrailingComments = null; + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getUnaryExpressionNodeType = function (kind) { + switch (kind) { + case 163 /* PlusExpression */: + return 26 /* PlusExpression */; + case 164 /* NegateExpression */: + return 27 /* NegateExpression */; + case 165 /* BitwiseNotExpression */: + return 72 /* BitwiseNotExpression */; + case 166 /* LogicalNotExpression */: + return 73 /* LogicalNotExpression */; + case 167 /* PreIncrementExpression */: + return 74 /* PreIncrementExpression */; + case 168 /* PreDecrementExpression */: + return 75 /* PreDecrementExpression */; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.operatorToken); + var operand = node.operand.accept(this); + + result = new TypeScript.UnaryExpression(this.getUnaryExpressionNodeType(node.kind()), operand); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.isOnSingleLine = function (start, end) { + return this.lineMap.getLineNumberFromPosition(start) === this.lineMap.getLineNumberFromPosition(end); + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var openStart = this.position + node.openBracketToken.leadingTriviaWidth(); + this.movePast(node.openBracketToken); + + var expressions = this.visitSeparatedSyntaxList(node.expressions); + + var closeStart = this.position + node.closeBracketToken.leadingTriviaWidth(); + this.movePast(node.closeBracketToken); + + TypeScript.Debug.assert(expressions !== null); + result = new TypeScript.UnaryExpression(21 /* ArrayLiteralExpression */, expressions); + + if (this.isOnSingleLine(openStart, closeStart)) { + result.setFlags(result.getFlags() | 2 /* SingleLine */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitOmittedExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + result = new TypeScript.OmittedExpression(); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.openParenToken); + var expr = node.expression.accept(this); + this.movePast(node.closeParenToken); + + result = new TypeScript.ParenthesizedExpression(expr); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getArrowFunctionStatements = function (body) { + if (body.kind() === 145 /* Block */) { + return body.accept(this); + } else { + var statements = new TypeScript.ASTList(); + var expression = body.accept(this); + var returnStatement = new TypeScript.ReturnStatement(expression); + + returnStatement.preComments = expression.preComments; + expression.preComments = null; + + statements.append(returnStatement); + var block = new TypeScript.Block(statements); + block.closeBraceSpan = statements.members[0]; + return block; + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.equalsGreaterThanToken); + + var parameters = new TypeScript.ASTList(); + + var parameter = new TypeScript.Parameter(identifier); + this.setSpanExplicit(parameter, identifier.minChar, identifier.limChar); + + parameters.append(parameter); + + var statements = this.getArrowFunctionStatements(node.body); + + result = new TypeScript.FunctionDeclaration(null, statements, false, null, parameters, 12 /* FunctionDeclaration */); + + result.returnTypeAnnotation = null; + result.setFunctionFlags(result.getFunctionFlags() | 8192 /* IsFunctionExpression */); + result.setFunctionFlags(result.getFunctionFlags() | 2048 /* IsFatArrowFunction */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + this.movePast(node.equalsGreaterThanToken); + + var block = this.getArrowFunctionStatements(node.body); + + result = new TypeScript.FunctionDeclaration(null, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.returnTypeAnnotation = returnType; + result.setFunctionFlags(result.getFunctionFlags() | 8192 /* IsFunctionExpression */); + result.setFunctionFlags(result.getFunctionFlags() | 2048 /* IsFatArrowFunction */); + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitType = function (type) { + this.assertElementAtPosition(type); + + var result; + if (type.isToken()) { + var start = this.position; + result = new TypeScript.TypeReference(type.accept(this), 0); + this.setSpan(result, start, type); + } else { + result = type.accept(this); + } + + TypeScript.Debug.assert(result.nodeType === 11 /* TypeRef */); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitQualifiedName = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var left = this.visitType(node.left).term; + this.movePast(node.dotToken); + var right = this.identifierFromToken(node.right, false, true); + this.movePast(node.right); + + var term = new TypeScript.BinaryExpression(32 /* MemberAccessExpression */, left, right); + this.setSpan(term, start, node); + + result = new TypeScript.TypeReference(term, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeArgumentList = function (node) { + this.assertElementAtPosition(node); + + var result = new TypeScript.ASTList(); + + this.movePast(node.lessThanToken); + + var start = this.position; + + for (var i = 0, n = node.typeArguments.childCount(); i < n; i++) { + if (i % 2 === 1) { + this.movePast(node.typeArguments.childAt(i)); + } else { + result.append(this.visitType(node.typeArguments.childAt(i))); + } + } + this.movePast(node.greaterThanToken); + + this.setSpan(result, start, node.typeArguments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.newKeyword); + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + var parameters = node.parameterList.accept(this); + this.movePast(node.equalsGreaterThanToken); + var returnType = node.type ? this.visitType(node.type) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.returnTypeAnnotation = returnType; + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 128 /* Signature */); + funcDecl.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 1024 /* ConstructMember */); + funcDecl.setFlags(funcDecl.getFlags() | 8 /* TypeReference */); + funcDecl.hint = "_construct"; + funcDecl.classDecl = null; + + result = new TypeScript.TypeReference(funcDecl, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + var parameters = node.parameterList.accept(this); + this.movePast(node.equalsGreaterThanToken); + var returnType = node.type ? this.visitType(node.type) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.returnTypeAnnotation = returnType; + + funcDecl.setFlags(funcDecl.getFunctionFlags() | 128 /* Signature */); + funcDecl.setFlags(funcDecl.getFlags() | 8 /* TypeReference */); + funcDecl.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + + result = new TypeScript.TypeReference(funcDecl, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.openBraceToken); + var typeMembers = this.visitSeparatedSyntaxList(node.typeMembers); + this.movePast(node.closeBraceToken); + + var interfaceDecl = new TypeScript.InterfaceDeclaration(new TypeScript.Identifier("__anonymous"), null, typeMembers, null, null); + this.setSpan(interfaceDecl, start, node); + + interfaceDecl.setFlags(interfaceDecl.getFlags() | 8 /* TypeReference */); + + result = new TypeScript.TypeReference(interfaceDecl, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var underlying = this.visitType(node.type); + this.movePast(node.openBracketToken); + this.movePast(node.closeBracketToken); + + if (underlying.nodeType === 11 /* TypeRef */) { + result = underlying; + result.arrayCount++; + } else { + result = new TypeScript.TypeReference(underlying, 1); + } + + result.setFlags(result.getFlags() | 8 /* TypeReference */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGenericType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var underlying = this.visitType(node.name).term; + var typeArguments = node.typeArgumentList.accept(this); + + var genericType = new TypeScript.GenericType(underlying, typeArguments); + this.setSpan(genericType, start, node); + + genericType.setFlags(genericType.getFlags() | 8 /* TypeReference */); + + result = new TypeScript.TypeReference(genericType, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeAnnotation = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.colonToken); + return this.visitType(node.type); + }; + + SyntaxTreeToAstVisitor.prototype.visitBlock = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.openBraceToken); + var statements = this.visitSyntaxList(node.statements); + var closeBracePosition = this.position; + this.movePast(node.closeBraceToken); + var closeBraceSpan = new TypeScript.ASTSpan(); + this.setSpan(closeBraceSpan, closeBracePosition, node.closeBraceToken); + + result = new TypeScript.Block(statements); + result.closeBraceSpan = closeBraceSpan; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameter = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var identifier = this.identifierFromToken(node.identifier, !!node.questionToken, true); + this.movePast(node.identifier); + this.movePast(node.questionToken); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + result = new TypeScript.Parameter(identifier); + + result.preComments = preComments; + result.postComments = postComments; + result.isOptional = !!node.questionToken; + result.init = init; + result.typeExpr = typeExpr; + + if (node.publicOrPrivateKeyword) { + result.setVarFlags(result.getVarFlags() | 256 /* Property */); + + if (node.publicOrPrivateKeyword.kind() === 57 /* PublicKeyword */) { + result.setVarFlags(result.getVarFlags() | 4 /* Public */); + } else { + result.setVarFlags(result.getVarFlags() | 2 /* Private */); + } + } + + if (node.equalsValueClause || node.dotDotDotToken) { + result.setFlags(result.getFlags() | 4 /* OptionalName */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var expression = node.expression.accept(this); + this.movePast(node.dotToken); + var name = this.identifierFromToken(node.name, false, true); + this.movePast(node.name); + + result = new TypeScript.BinaryExpression(32 /* MemberAccessExpression */, expression, name); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var operand = node.operand.accept(this); + this.movePast(node.operatorToken); + + result = new TypeScript.UnaryExpression(node.kind() === 209 /* PostIncrementExpression */ ? 76 /* PostIncrementExpression */ : 77 /* PostDecrementExpression */, operand); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElementAccessExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var expression = node.expression.accept(this); + this.movePast(node.openBracketToken); + var argumentExpression = node.argumentExpression.accept(this); + this.movePast(node.closeBracketToken); + + result = new TypeScript.BinaryExpression(35 /* ElementAccessExpression */, expression, argumentExpression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.convertArgumentListArguments = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + + this.movePast(node.openParenToken); + + var result = this.visitSeparatedSyntaxList(node.arguments); + + if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { + var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); + this.setSpanExplicit(result, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + } + + this.movePast(node.closeParenToken); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInvocationExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var expression = node.expression.accept(this); + var typeArguments = node.argumentList.typeArgumentList !== null ? node.argumentList.typeArgumentList.accept(this) : null; + var argumentList = this.convertArgumentListArguments(node.argumentList); + + result = new TypeScript.CallExpression(36 /* InvocationExpression */, expression, typeArguments, argumentList); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArgumentList = function (node) { + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxTreeToAstVisitor.prototype.getBinaryExpressionNodeType = function (node) { + switch (node.kind()) { + case 172 /* CommaExpression */: + return 25 /* CommaExpression */; + case 173 /* AssignmentExpression */: + return 38 /* AssignmentExpression */; + case 174 /* AddAssignmentExpression */: + return 39 /* AddAssignmentExpression */; + case 175 /* SubtractAssignmentExpression */: + return 40 /* SubtractAssignmentExpression */; + case 176 /* MultiplyAssignmentExpression */: + return 42 /* MultiplyAssignmentExpression */; + case 177 /* DivideAssignmentExpression */: + return 41 /* DivideAssignmentExpression */; + case 178 /* ModuloAssignmentExpression */: + return 43 /* ModuloAssignmentExpression */; + case 179 /* AndAssignmentExpression */: + return 44 /* AndAssignmentExpression */; + case 180 /* ExclusiveOrAssignmentExpression */: + return 45 /* ExclusiveOrAssignmentExpression */; + case 181 /* OrAssignmentExpression */: + return 46 /* OrAssignmentExpression */; + case 182 /* LeftShiftAssignmentExpression */: + return 47 /* LeftShiftAssignmentExpression */; + case 183 /* SignedRightShiftAssignmentExpression */: + return 48 /* SignedRightShiftAssignmentExpression */; + case 184 /* UnsignedRightShiftAssignmentExpression */: + return 49 /* UnsignedRightShiftAssignmentExpression */; + case 186 /* LogicalOrExpression */: + return 51 /* LogicalOrExpression */; + case 187 /* LogicalAndExpression */: + return 52 /* LogicalAndExpression */; + case 188 /* BitwiseOrExpression */: + return 53 /* BitwiseOrExpression */; + case 189 /* BitwiseExclusiveOrExpression */: + return 54 /* BitwiseExclusiveOrExpression */; + case 190 /* BitwiseAndExpression */: + return 55 /* BitwiseAndExpression */; + case 191 /* EqualsWithTypeConversionExpression */: + return 56 /* EqualsWithTypeConversionExpression */; + case 192 /* NotEqualsWithTypeConversionExpression */: + return 57 /* NotEqualsWithTypeConversionExpression */; + case 193 /* EqualsExpression */: + return 58 /* EqualsExpression */; + case 194 /* NotEqualsExpression */: + return 59 /* NotEqualsExpression */; + case 195 /* LessThanExpression */: + return 60 /* LessThanExpression */; + case 196 /* GreaterThanExpression */: + return 62 /* GreaterThanExpression */; + case 197 /* LessThanOrEqualExpression */: + return 61 /* LessThanOrEqualExpression */; + case 198 /* GreaterThanOrEqualExpression */: + return 63 /* GreaterThanOrEqualExpression */; + case 199 /* InstanceOfExpression */: + return 33 /* InstanceOfExpression */; + case 200 /* InExpression */: + return 31 /* InExpression */; + case 201 /* LeftShiftExpression */: + return 69 /* LeftShiftExpression */; + case 202 /* SignedRightShiftExpression */: + return 70 /* SignedRightShiftExpression */; + case 203 /* UnsignedRightShiftExpression */: + return 71 /* UnsignedRightShiftExpression */; + case 204 /* MultiplyExpression */: + return 66 /* MultiplyExpression */; + case 205 /* DivideExpression */: + return 67 /* DivideExpression */; + case 206 /* ModuloExpression */: + return 68 /* ModuloExpression */; + case 207 /* AddExpression */: + return 64 /* AddExpression */; + case 208 /* SubtractExpression */: + return 65 /* SubtractExpression */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxTreeToAstVisitor.prototype.visitBinaryExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var nodeType = this.getBinaryExpressionNodeType(node); + var left = node.left.accept(this); + this.movePast(node.operatorToken); + var right = node.right.accept(this); + + result = new TypeScript.BinaryExpression(nodeType, left, right); + + if (right.nodeType === 12 /* FunctionDeclaration */) { + var id = left.nodeType === 32 /* MemberAccessExpression */ ? (left).operand2 : left; + var idHint = id.nodeType === 20 /* Name */ ? id.actualText : null; + + var funcDecl = right; + funcDecl.hint = idHint; + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConditionalExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var condition = node.condition.accept(this); + this.movePast(node.questionToken); + var whenTrue = node.whenTrue.accept(this); + this.movePast(node.colonToken); + var whenFalse = node.whenFalse.accept(this); + + result = new TypeScript.ConditionalExpression(condition, whenTrue, whenFalse); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + this.movePast(node.newKeyword); + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.returnTypeAnnotation = returnType; + + result.hint = "_construct"; + result.setFunctionFlags(result.getFunctionFlags() | 1024 /* ConstructMember */); + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMethodSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var name = this.identifierFromToken(node.propertyName, !!node.questionToken, true); + this.movePast(node.propertyName); + this.movePast(node.questionToken); + + var typeParameters = node.callSignature.typeParameterList ? node.callSignature.typeParameterList.accept(this) : null; + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(name, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + this.movePast(node.openBracketToken); + + var parameter = node.parameter.accept(this); + + this.movePast(node.closeBracketToken); + var returnType = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + var name = new TypeScript.Identifier("__item"); + this.setSpanExplicit(name, start, start); + + var parameters = new TypeScript.ASTList(); + parameters.append(parameter); + + result = new TypeScript.FunctionDeclaration(name, null, false, null, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = false; + result.returnTypeAnnotation = returnType; + + result.setFunctionFlags(result.getFunctionFlags() | 4096 /* IndexerMember */); + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPropertySignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var name = this.identifierFromToken(node.propertyName, !!node.questionToken, true); + this.movePast(node.propertyName); + this.movePast(node.questionToken); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + result = new TypeScript.VariableDeclarator(name); + + result.preComments = preComments; + result.typeExpr = typeExpr; + result.setVarFlags(result.getVarFlags() | 256 /* Property */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameterList = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var openParenToken = node.openParenToken; + this.previousTokenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + + this.movePast(node.openParenToken); + var result = this.visitSeparatedSyntaxList(node.parameters); + this.movePast(node.closeParenToken); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCallSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + var parameters = node.parameterList.accept(this); + var returnType = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + result.hint = "_call"; + result.setFunctionFlags(result.getFunctionFlags() | 512 /* CallMember */); + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameterList = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.lessThanToken); + var result = this.visitSeparatedSyntaxList(node.typeParameters); + this.movePast(node.greaterThanToken); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameter = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var constraint = node.constraint ? node.constraint.accept(this) : null; + + result = new TypeScript.TypeParameter(identifier, constraint); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstraint = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.extendsKeyword); + return this.visitType(node.type); + }; + + SyntaxTreeToAstVisitor.prototype.visitIfStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var thenBod = node.statement.accept(this); + var elseBod = node.elseClause ? node.elseClause.accept(this) : null; + + result = new TypeScript.IfStatement(condition, thenBod, elseBod); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElseClause = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.elseKeyword); + return node.statement.accept(this); + }; + + SyntaxTreeToAstVisitor.prototype.visitExpressionStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + result = new TypeScript.ExpressionStatement(expression); + result.preComments = preComments; + result.postComments = postComments; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.parameterList); + var parameters = node.parameterList.accept(this); + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + result = new TypeScript.FunctionDeclaration(null, block, true, null, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + + if (node.semicolonToken) { + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + + this.movePast(node.propertyName); + + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + this.movePast(node.semicolonToken); + + result = new TypeScript.FunctionDeclaration(name, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + if (node.semicolonToken) { + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 55 /* PrivateKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 2 /* Private */); + } else { + result.setFunctionFlags(result.getFunctionFlags() | 4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 58 /* StaticKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 16 /* Static */); + } + + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessorDeclaration = function (node, typeAnnotation) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + this.movePast(node.propertyName); + var parameters = node.parameterList.accept(this); + var returnType = typeAnnotation ? typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + result = new TypeScript.FunctionDeclaration(name, block, false, null, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 55 /* PrivateKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 2 /* Private */); + } else { + result.setFunctionFlags(result.getFunctionFlags() | 4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 58 /* StaticKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 16 /* Static */); + } + + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetMemberAccessorDeclaration = function (node) { + this.assertElementAtPosition(node); + + var result = this.visitMemberAccessorDeclaration(node, node.typeAnnotation); + + result.setFunctionFlags(result.getFunctionFlags() | 32 /* GetAccessor */); + result.hint = "get" + result.name.actualText; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetMemberAccessorDeclaration = function (node) { + this.assertElementAtPosition(node); + + var result = this.visitMemberAccessorDeclaration(node, null); + + result.setFunctionFlags(result.getFunctionFlags() | 64 /* SetAccessor */); + result.hint = "set" + result.name.actualText; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.variableDeclarator); + this.moveTo(node.variableDeclarator, node.variableDeclarator.identifier); + + var name = this.identifierFromToken(node.variableDeclarator.identifier, false, true); + this.movePast(node.variableDeclarator.identifier); + var typeExpr = node.variableDeclarator.typeAnnotation ? node.variableDeclarator.typeAnnotation.accept(this) : null; + var init = node.variableDeclarator.equalsValueClause ? node.variableDeclarator.equalsValueClause.accept(this) : null; + this.movePast(node.semicolonToken); + + result = new TypeScript.VariableDeclarator(name); + + result.preComments = preComments; + result.postComments = postComments; + result.typeExpr = typeExpr; + result.init = init; + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 58 /* StaticKeyword */)) { + result.setVarFlags(result.getVarFlags() | 16 /* Static */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 55 /* PrivateKeyword */)) { + result.setVarFlags(result.getVarFlags() | 2 /* Private */); + } else { + result.setVarFlags(result.getVarFlags() | 4 /* Public */); + } + + result.setVarFlags(result.getVarFlags() | 2048 /* ClassProperty */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitThrowStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.throwKeyword); + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + result = new TypeScript.ThrowStatement(expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitReturnStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.movePast(node.returnKeyword); + var expression = node.expression ? node.expression.accept(this) : null; + this.movePast(node.semicolonToken); + + result = new TypeScript.ReturnStatement(expression); + result.preComments = preComments; + result.postComments = postComments; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectCreationExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.newKeyword); + var expression = node.expression.accept(this); + var typeArgumentList = node.argumentList === null || node.argumentList.typeArgumentList === null ? null : node.argumentList.typeArgumentList.accept(this); + var argumentList = this.convertArgumentListArguments(node.argumentList); + + result = new TypeScript.CallExpression(37 /* ObjectCreationExpression */, expression, typeArgumentList, argumentList); + + if (expression.nodeType === 11 /* TypeRef */) { + var typeRef = expression; + + if (typeRef.arrayCount === 0) { + var term = typeRef.term; + if (term.nodeType === 32 /* MemberAccessExpression */ || term.nodeType === 20 /* Name */) { + expression = term; + } + } + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSwitchStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.switchKeyword); + this.movePast(node.openParenToken); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var closeParenPosition = this.position; + this.movePast(node.openBraceToken); + + result = new TypeScript.SwitchStatement(expression); + + result.statement.minChar = start; + result.statement.limChar = closeParenPosition; + + result.caseList = new TypeScript.ASTList(); + + for (var i = 0, n = node.switchClauses.childCount(); i < n; i++) { + var switchClause = node.switchClauses.childAt(i); + var translated = switchClause.accept(this); + + if (switchClause.kind() === 232 /* DefaultSwitchClause */) { + result.defaultCase = translated; + } + + result.caseList.append(translated); + } + + this.movePast(node.closeBraceToken); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCaseSwitchClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.caseKeyword); + var expression = node.expression.accept(this); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + result = new TypeScript.CaseClause(); + + result.expr = expression; + result.body = statements; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.defaultKeyword); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + result = new TypeScript.CaseClause(); + result.body = statements; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBreakStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.breakKeyword); + this.movePast(node.identifier); + this.movePast(node.semicolonToken); + + result = new TypeScript.Jump(82 /* BreakStatement */); + + if (node.identifier !== null) { + result.target = node.identifier.valueText(); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitContinueStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.continueKeyword); + this.movePast(node.identifier); + this.movePast(node.semicolonToken); + + result = new TypeScript.Jump(83 /* ContinueStatement */); + + if (node.identifier !== null) { + result.target = node.identifier.valueText(); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var init = node.variableDeclaration ? node.variableDeclaration.accept(this) : node.initializer ? node.initializer.accept(this) : null; + this.movePast(node.firstSemicolonToken); + var cond = node.condition ? node.condition.accept(this) : null; + this.movePast(node.secondSemicolonToken); + var incr = node.incrementor ? node.incrementor.accept(this) : null; + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + result = new TypeScript.ForStatement(init, cond, incr, body); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForInStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var init = node.variableDeclaration ? node.variableDeclaration.accept(this) : node.left.accept(this); + this.movePast(node.inKeyword); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + result = new TypeScript.ForInStatement(init, expression, body); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWhileStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + result = new TypeScript.WhileStatement(condition, statement); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWithStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + result = new TypeScript.WithStatement(condition, statement); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCastExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.lessThanToken); + var castTerm = this.visitType(node.type); + this.movePast(node.greaterThanToken); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(78 /* CastExpression */, expression); + result.castTerm = castTerm; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var openStart = this.position + node.openBraceToken.leadingTriviaWidth(); + this.movePast(node.openBraceToken); + + var propertyAssignments = this.visitSeparatedSyntaxList(node.propertyAssignments); + + var closeStart = this.position + node.closeBraceToken.leadingTriviaWidth(); + this.movePast(node.closeBraceToken); + + result = new TypeScript.UnaryExpression(22 /* ObjectLiteralExpression */, propertyAssignments); + result.preComments = preComments; + + if (this.isOnSingleLine(openStart, closeStart)) { + result.setFlags(result.getFlags() | 2 /* SingleLine */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var left = node.propertyName.accept(this); + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(node.colonToken, this.position + node.colonToken.leadingTriviaWidth() + node.colonToken.width()); + + this.movePast(node.colonToken); + var right = node.expression.accept(this); + + result = new TypeScript.BinaryExpression(80 /* Member */, left, right); + result.preComments = preComments; + + if (right.nodeType === 12 /* FunctionDeclaration */) { + var funcDecl = right; + funcDecl.hint = left.text; + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var left = node.propertyName.accept(this); + var functionDeclaration = node.callSignature.accept(this); + var block = node.block.accept(this); + + functionDeclaration.hint = left.text; + functionDeclaration.block = block; + functionDeclaration.setFunctionFlags(16384 /* IsFunctionProperty */); + + result = new TypeScript.BinaryExpression(80 /* Member */, left, functionDeclaration); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetAccessorPropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + var functionName = this.identifierFromToken(node.propertyName, false, true); + this.movePast(node.propertyName); + this.movePast(node.openParenToken); + this.movePast(node.closeParenToken); + var returnType = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(functionName, block, false, null, new TypeScript.ASTList(), 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 32 /* GetAccessor */); + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 8192 /* IsFunctionExpression */); + funcDecl.hint = "get" + node.propertyName.valueText(); + funcDecl.returnTypeAnnotation = returnType; + + result = new TypeScript.BinaryExpression(80 /* Member */, name, funcDecl); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetAccessorPropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + var functionName = this.identifierFromToken(node.propertyName, false, true); + this.movePast(node.propertyName); + this.movePast(node.openParenToken); + var parameter = node.parameter.accept(this); + this.movePast(node.closeParenToken); + + var parameters = new TypeScript.ASTList(); + parameters.append(parameter); + + var block = node.block ? node.block.accept(this) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(functionName, block, false, null, parameters, 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 64 /* SetAccessor */); + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 8192 /* IsFunctionExpression */); + funcDecl.hint = "set" + node.propertyName.valueText(); + + result = new TypeScript.BinaryExpression(80 /* Member */, name, funcDecl); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + this.movePast(node.functionKeyword); + var name = node.identifier === null ? null : this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(name, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + result.setFunctionFlags(result.getFunctionFlags() | 8192 /* IsFunctionExpression */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEmptyStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.semicolonToken); + + result = new TypeScript.EmptyStatement(); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTryStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.tryKeyword); + var tryBody = node.block.accept(this); + + var catchClause = null; + if (node.catchClause !== null) { + catchClause = node.catchClause.accept(this); + } + + var finallyBody = null; + if (node.finallyClause !== null) { + finallyBody = node.finallyClause.accept(this); + } + + result = new TypeScript.TryStatement(tryBody, catchClause, finallyBody); + } + + TypeScript.Debug.assert(result !== null); + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCatchClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.catchKeyword); + this.movePast(node.openParenToken); + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + this.movePast(node.closeParenToken); + var block = node.block.accept(this); + + var varDecl = new TypeScript.VariableDeclarator(identifier); + this.setSpanExplicit(varDecl, identifier.minChar, identifier.limChar); + + varDecl.typeExpr = typeExpr; + + result = new TypeScript.CatchClause(varDecl, block); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFinallyClause = function (node) { + this.movePast(node.finallyKeyword); + return node.block.accept(this); + }; + + SyntaxTreeToAstVisitor.prototype.visitLabeledStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.colonToken); + var statement = node.statement.accept(this); + + result = new TypeScript.LabeledStatement(identifier, statement); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDoStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.doKeyword); + var statement = node.statement.accept(this); + var whileSpan = new TypeScript.ASTSpan(); + this.setSpan(whileSpan, this.position, node.whileKeyword); + + this.movePast(node.whileKeyword); + this.movePast(node.openParenToken); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + this.movePast(node.semicolonToken); + + result = new TypeScript.DoStatement(statement, condition); + result.whileSpan = whileSpan; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeOfExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.typeOfKeyword); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(34 /* TypeOfExpression */, expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDeleteExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.deleteKeyword); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(28 /* DeleteExpression */, expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVoidExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.voidKeyword); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(24 /* VoidExpression */, expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDebuggerStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.debuggerKeyword); + this.movePast(node.semicolonToken); + + result = new TypeScript.DebuggerStatement(); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + SyntaxTreeToAstVisitor.checkPositions = false; + + SyntaxTreeToAstVisitor.protoString = "__proto__"; + SyntaxTreeToAstVisitor.protoSubstitutionString = "#__proto__"; + return SyntaxTreeToAstVisitor; + })(); + TypeScript.SyntaxTreeToAstVisitor = SyntaxTreeToAstVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Document = (function () { + function Document(fileName, compilationSettings, scriptSnapshot, byteOrderMark, version, isOpen, syntaxTree) { + this.fileName = fileName; + this.compilationSettings = compilationSettings; + this.scriptSnapshot = scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this.isOpen = isOpen; + this._diagnostics = null; + this._syntaxTree = null; + this._bloomFilter = null; + if (isOpen) { + this._syntaxTree = syntaxTree; + } else { + this._diagnostics = syntaxTree.diagnostics(); + } + + var identifiers = new TypeScript.BlockIntrinsics(); + + var identifierWalker = new TypeScript.IdentifierWalker(identifiers); + syntaxTree.sourceUnit().accept(identifierWalker); + + var identifierCount = 0; + for (var name in identifiers) { + identifierCount++; + } + this._bloomFilter = new TypeScript.BloomFilter(identifierCount); + this._bloomFilter.addKeys(identifiers); + + this.lineMap = syntaxTree.lineMap(); + this.script = TypeScript.SyntaxTreeToAstVisitor.visit(syntaxTree, fileName, compilationSettings); + } + Document.prototype.diagnostics = function () { + if (this._diagnostics === null) { + this._diagnostics = this._syntaxTree.diagnostics(); + } + + return this._diagnostics; + }; + + Document.prototype.syntaxTree = function () { + if (this._syntaxTree) { + return this._syntaxTree; + } + + return TypeScript.Parser.parse(this.fileName, TypeScript.SimpleText.fromScriptSnapshot(this.scriptSnapshot), TypeScript.isDTSFile(this.fileName), this.compilationSettings.codeGenTarget, TypeScript.getParseOptions(this.compilationSettings)); + }; + + Document.prototype.bloomFilter = function () { + return this._bloomFilter; + }; + + Document.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange, settings) { + var oldScript = this.script; + var oldSyntaxTree = this._syntaxTree; + + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null ? TypeScript.Parser.parse(this.fileName, text, TypeScript.isDTSFile(this.fileName), settings.codeGenTarget, TypeScript.getParseOptions(this.compilationSettings)) : TypeScript.Parser.incrementalParse(oldSyntaxTree, textChangeRange, text); + + return new Document(this.fileName, this.compilationSettings, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree); + }; + + Document.create = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles, compilationSettings) { + var syntaxTree = TypeScript.Parser.parse(fileName, TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot), TypeScript.isDTSFile(fileName), compilationSettings.codeGenTarget, TypeScript.getParseOptions(compilationSettings)); + + var document = new Document(fileName, compilationSettings, scriptSnapshot, byteOrderMark, version, isOpen, syntaxTree); + document.script.referencedFiles = referencedFiles; + + return document; + }; + return Document; + })(); + TypeScript.Document = Document; + + TypeScript.globalSemanticInfoChain = null; + TypeScript.globalBinder = null; + TypeScript.globalLogger = null; + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(logger, settings, diagnosticMessages) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof settings === "undefined") { settings = new TypeScript.CompilationSettings(); } + if (typeof diagnosticMessages === "undefined") { diagnosticMessages = null; } + this.logger = logger; + this.settings = settings; + this.diagnosticMessages = diagnosticMessages; + this.pullTypeChecker = null; + this.semanticInfoChain = null; + this.fileNameToDocument = new TypeScript.StringHashTable(); + this.emitOptions = new TypeScript.EmitOptions(this.settings); + TypeScript.globalLogger = logger; + if (this.diagnosticMessages) { + TypeScript.diagnosticMessages = this.diagnosticMessages; + } + } + TypeScriptCompiler.prototype.getDocument = function (fileName) { + return this.fileNameToDocument.lookup(fileName); + }; + + TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { + return TypeScript.timeFunction(this.logger, funcDescription, func); + }; + + TypeScriptCompiler.prototype.addSourceUnit = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + var _this = this; + return this.timeFunction("addSourceUnit(" + fileName + ")", function () { + var document = Document.create(fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles, _this.emitOptions.compilationSettings); + _this.fileNameToDocument.addOrUpdate(fileName, document); + + return document; + }); + }; + + TypeScriptCompiler.prototype.updateSourceUnit = function (fileName, scriptSnapshot, version, isOpen, textChangeRange) { + var _this = this; + return this.timeFunction("pullUpdateUnit(" + fileName + ")", function () { + var document = _this.getDocument(fileName); + var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange, _this.settings); + + _this.fileNameToDocument.addOrUpdate(fileName, updatedDocument); + + _this.pullUpdateScript(document, updatedDocument); + + return updatedDocument; + }); + }; + + TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { + var fileNames = this.fileNameToDocument.getAllKeys(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + var script = document.script; + if (!script.isDeclareFile && script.topLevelMod !== null) { + return true; + } + } + return false; + }; + + TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { + var commonComponents = []; + var commonComponentsLength = -1; + + var fileNames = this.fileNameToDocument.getAllKeys(); + for (var i = 0, len = fileNames.length; i < len; i++) { + var fileName = fileNames[i]; + var document = this.getDocument(fileNames[i]); + var script = document.script; + + if (!script.isDeclareFile) { + var fileComponents = TypeScript.filePathComponents(fileName); + if (commonComponentsLength === -1) { + commonComponents = fileComponents; + commonComponentsLength = commonComponents.length; + } else { + var updatedPath = false; + for (var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { + if (commonComponents[j] !== fileComponents[j]) { + commonComponentsLength = j; + updatedPath = true; + + if (j === 0) { + return new TypeScript.Diagnostic(null, 0, 0, 273 /* Cannot_find_the_common_subdirectory_path_for_the_input_files */, null); + } + + break; + } + } + + if (!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + + this.emitOptions.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + if (this.emitOptions.compilationSettings.outputOption.charAt(this.emitOptions.compilationSettings.outputOption.length - 1) !== "/") { + this.emitOptions.compilationSettings.outputOption += "/"; + } + + return null; + }; + + TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { + this.emitOptions.ioHost = ioHost; + if (this.emitOptions.compilationSettings.outputOption === "") { + this.emitOptions.outputMany = true; + this.emitOptions.commonDirectoryPath = ""; + return null; + } + + this.emitOptions.compilationSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitOptions.ioHost.resolvePath(this.emitOptions.compilationSettings.outputOption)); + + if (this.emitOptions.ioHost.directoryExists(this.emitOptions.compilationSettings.outputOption)) { + this.emitOptions.outputMany = true; + } else if (this.emitOptions.ioHost.fileExists(this.emitOptions.compilationSettings.outputOption)) { + this.emitOptions.outputMany = false; + } else { + this.emitOptions.outputMany = !TypeScript.isJSFile(this.emitOptions.compilationSettings.outputOption); + } + + if (this.isDynamicModuleCompilation() && !this.emitOptions.outputMany) { + return new TypeScript.Diagnostic(null, 0, 0, 274 /* Cannot_compile_dynamic_modules_when_emitting_into_single_file */, null); + } + + if (this.emitOptions.outputMany) { + return this.updateCommonDirectoryPath(); + } + + return null; + }; + + TypeScriptCompiler.prototype.getScripts = function () { + var result = []; + var fileNames = this.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + result.push(document.script); + } + + return result; + }; + + TypeScriptCompiler.prototype.writeByteOrderMarkForDocument = function (document) { + if (this.emitOptions.outputMany) { + return document.byteOrderMark !== 0 /* None */; + } else { + var fileNames = this.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + if (document.byteOrderMark !== 0 /* None */) { + return true; + } + } + + return false; + } + }; + + TypeScriptCompiler.mapToDTSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + + TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { + if (!this.settings.generateDeclarationFiles) { + return false; + } + + if (!!script && (script.isDeclareFile || script.moduleElements === null)) { + return false; + } + + return true; + }; + + TypeScriptCompiler.prototype.emitDeclarations = function (document, declarationEmitter) { + var script = document.script; + if (this.canEmitDeclarations(script)) { + if (!declarationEmitter) { + var declareFileName = this.emitOptions.mapOutputFileName(document.fileName, TypeScriptCompiler.mapToDTSFileName); + declarationEmitter = new TypeScript.DeclarationEmitter(declareFileName, this.semanticInfoChain, this.emitOptions, document.byteOrderMark !== 0 /* None */); + } + + declarationEmitter.fileName = document.fileName; + declarationEmitter.emitDeclarations(script); + } + + return declarationEmitter; + }; + + TypeScriptCompiler.prototype.emitAllDeclarations = function () { + if (this.canEmitDeclarations()) { + var sharedEmitter = null; + var fileNames = this.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + try { + var document = this.getDocument(fileNames[i]); + + if (this.emitOptions.outputMany) { + var singleEmitter = this.emitDeclarations(document); + if (singleEmitter) { + singleEmitter.close(); + } + } else { + sharedEmitter = this.emitDeclarations(document, sharedEmitter); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + } + + if (sharedEmitter) { + try { + sharedEmitter.close(); + } catch (ex2) { + return TypeScript.Emitter.handleEmitterError(sharedEmitter.fileName, ex2); + } + } + } + + return []; + }; + + TypeScriptCompiler.prototype.emitUnitDeclarations = function (fileName) { + if (this.canEmitDeclarations()) { + if (this.emitOptions.outputMany) { + try { + var document = this.getDocument(fileName); + var emitter = this.emitDeclarations(document); + if (emitter) { + emitter.close(); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + } else { + return this.emitAllDeclarations(); + } + } + + return []; + }; + + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { + if (wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + + TypeScriptCompiler.mapToJSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + + TypeScriptCompiler.prototype.emit = function (document, inputOutputMapper, emitter) { + var script = document.script; + if (!script.isDeclareFile) { + var typeScriptFileName = document.fileName; + if (!emitter) { + var javaScriptFileName = this.emitOptions.mapOutputFileName(typeScriptFileName, TypeScriptCompiler.mapToJSFileName); + var outFile = this.createFile(javaScriptFileName, this.writeByteOrderMarkForDocument(document)); + + emitter = new TypeScript.Emitter(javaScriptFileName, outFile, this.emitOptions, this.semanticInfoChain); + + if (this.settings.mapSourceFiles) { + var sourceMapFileName = javaScriptFileName + TypeScript.SourceMapper.MapFileExtension; + emitter.setSourceMappings(new TypeScript.SourceMapper(typeScriptFileName, javaScriptFileName, sourceMapFileName, outFile, this.createFile(sourceMapFileName, false), this.settings.emitFullSourceMapPath)); + } + + if (inputOutputMapper) { + inputOutputMapper(typeScriptFileName, javaScriptFileName); + } + } else if (this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(typeScriptFileName, emitter.emittingFileName, emitter.sourceMapper.sourceMapFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.settings.emitFullSourceMapPath)); + } + + emitter.setDocument(document); + emitter.emitJavascript(script, false); + } + + return emitter; + }; + + TypeScriptCompiler.prototype.emitAll = function (ioHost, inputOutputMapper) { + var optionsDiagnostic = this.parseEmitOption(ioHost); + if (optionsDiagnostic) { + return [optionsDiagnostic]; + } + + var startEmitTime = (new Date()).getTime(); + + var fileNames = this.fileNameToDocument.getAllKeys(); + var sharedEmitter = null; + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileName); + + try { + if (this.emitOptions.outputMany) { + var singleEmitter = this.emit(document, inputOutputMapper); + + if (singleEmitter) { + singleEmitter.emitSourceMapsAndClose(); + } + } else { + sharedEmitter = this.emit(document, inputOutputMapper, sharedEmitter); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + } + + this.logger.log("Emit: " + ((new Date()).getTime() - startEmitTime)); + + if (sharedEmitter) { + try { + sharedEmitter.emitSourceMapsAndClose(); + } catch (ex2) { + return TypeScript.Emitter.handleEmitterError(sharedEmitter.document.fileName, ex2); + } + } + + return []; + }; + + TypeScriptCompiler.prototype.emitUnit = function (fileName, ioHost, inputOutputMapper) { + var optionsDiagnostic = this.parseEmitOption(ioHost); + if (optionsDiagnostic) { + return [optionsDiagnostic]; + } + + if (this.emitOptions.outputMany) { + var document = this.getDocument(fileName); + try { + var emitter = this.emit(document, inputOutputMapper); + + if (emitter) { + emitter.emitSourceMapsAndClose(); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + + return []; + } else { + return this.emitAll(ioHost, inputOutputMapper); + } + }; + + TypeScriptCompiler.prototype.createFile = function (fileName, writeByteOrderMark) { + return new TypeScript.TextWriter(this.emitOptions.ioHost, fileName, writeByteOrderMark); + }; + + TypeScriptCompiler.prototype.getSyntacticDiagnostics = function (fileName) { + return this.getDocument(fileName).diagnostics(); + }; + + TypeScriptCompiler.prototype.getSyntaxTree = function (fileName) { + return this.getDocument(fileName).syntaxTree(); + }; + TypeScriptCompiler.prototype.getScript = function (fileName) { + return this.getDocument(fileName).script; + }; + + TypeScriptCompiler.prototype.getSemanticDiagnostics = function (fileName) { + var errors = []; + var unit = this.semanticInfoChain.getUnit(fileName); + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + if (unit) { + var document = this.getDocument(fileName); + var script = document.script; + + if (script) { + this.pullTypeChecker.typeCheckScript(script, fileName, this); + + unit.getDiagnostics(errors); + } + } + + return errors; + }; + + TypeScriptCompiler.prototype.pullTypeCheck = function () { + var _this = this; + return this.timeFunction("pullTypeCheck()", function () { + _this.semanticInfoChain = new TypeScript.SemanticInfoChain(); + TypeScript.globalSemanticInfoChain = _this.semanticInfoChain; + _this.pullTypeChecker = new TypeScript.PullTypeChecker(_this.settings, _this.semanticInfoChain); + + var declCollectionContext = null; + var i, n; + + var createDeclsStartTime = new Date().getTime(); + + var fileNames = _this.fileNameToDocument.getAllKeys(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + var document = _this.getDocument(fileName); + var semanticInfo = new TypeScript.SemanticInfo(fileName); + + declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + declCollectionContext.scriptName = fileName; + + TypeScript.getAstWalkerFactory().walk(document.script, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + semanticInfo.addTopLevelDecl(declCollectionContext.getParent()); + + _this.semanticInfoChain.addUnit(semanticInfo); + } + + var createDeclsEndTime = new Date().getTime(); + + var bindStartTime = new Date().getTime(); + + var binder = new TypeScript.PullSymbolBinder(_this.semanticInfoChain); + TypeScript.globalBinder = binder; + + var bindEndTime = new Date().getTime(); + + _this.logger.log("Decl creation: " + (createDeclsEndTime - createDeclsStartTime)); + _this.logger.log("Binding: " + (bindEndTime - bindStartTime)); + _this.logger.log(" Time in findSymbol: " + TypeScript.time_in_findSymbol); + _this.logger.log("Number of symbols created: " + TypeScript.pullSymbolID); + _this.logger.log("Number of specialized types created: " + TypeScript.nSpecializationsCreated); + _this.logger.log("Number of specialized signatures created: " + TypeScript.nSpecializedSignaturesCreated); + }); + }; + + TypeScriptCompiler.prototype.pullUpdateScript = function (oldDocument, newDocument) { + var _this = this; + this.timeFunction("pullUpdateScript: ", function () { + var oldScript = oldDocument.script; + var newScript = newDocument.script; + + var newScriptSemanticInfo = new TypeScript.SemanticInfo(oldDocument.fileName); + var oldScriptSemanticInfo = _this.semanticInfoChain.getUnit(oldDocument.fileName); + + TypeScript.lastBoundPullDeclId = TypeScript.pullDeclID; + TypeScript.lastBoundPullSymbolID = TypeScript.pullSymbolID; + + var declCollectionContext = new TypeScript.DeclCollectionContext(newScriptSemanticInfo); + + declCollectionContext.scriptName = oldDocument.fileName; + + TypeScript.getAstWalkerFactory().walk(newScript, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var oldTopLevelDecl = oldScriptSemanticInfo.getTopLevelDecls()[0]; + var newTopLevelDecl = declCollectionContext.getParent(); + + newScriptSemanticInfo.addTopLevelDecl(newTopLevelDecl); + + if (_this.pullTypeChecker && _this.pullTypeChecker.resolver) { + _this.pullTypeChecker.resolver.cleanCachedGlobals(); + } + + _this.semanticInfoChain.updateUnit(oldScriptSemanticInfo, newScriptSemanticInfo); + + _this.logger.log("Cleaning symbols..."); + var cleanStart = new Date().getTime(); + _this.semanticInfoChain.update(); + var cleanEnd = new Date().getTime(); + _this.logger.log(" time to clean: " + (cleanEnd - cleanStart)); + + if (_this.pullTypeChecker && _this.pullTypeChecker.resolver) { + _this.pullTypeChecker.resolver.setUnitPath(oldDocument.fileName); + } + }); + }; + + TypeScriptCompiler.prototype.getSymbolOfDeclaration = function (decl) { + if (!decl) { + return null; + } + var ast = this.pullTypeChecker.resolver.getASTForDecl(decl); + if (!ast) { + return null; + } + var enlosingDecl = this.pullTypeChecker.resolver.getEnclosingDecl(decl); + if (ast.nodeType === 80 /* Member */) { + return this.getSymbolOfDeclaration(enlosingDecl); + } + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + return this.pullTypeChecker.resolver.resolveAST(ast, false, enlosingDecl, resolutionContext).symbol; + }; + + TypeScriptCompiler.prototype.resolvePosition = function (pos, document) { + var declStack = []; + var resultASTs = []; + var script = document.script; + var scriptName = document.fileName; + + var semanticInfo = this.semanticInfoChain.getUnit(scriptName); + var lastDeclAST = null; + var foundAST = null; + var symbol = null; + var candidateSignature = null; + var callSignatures = null; + + var lambdaAST = null; + var declarationInitASTs = []; + var objectLitAST = null; + var asgAST = null; + var typeAssertionASTs = []; + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var inTypeReference = false; + var enclosingDecl = null; + var isConstructorCall = false; + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var pre = function (cur, parent) { + if (TypeScript.isValidAstNode(cur)) { + if (pos >= cur.minChar && pos <= cur.limChar) { + var previous = resultASTs[resultASTs.length - 1]; + + if (previous === undefined || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + var decl = semanticInfo.getDeclForAST(cur); + + if (decl) { + declStack[declStack.length] = decl; + lastDeclAST = cur; + } + + if (cur.nodeType === 12 /* FunctionDeclaration */ && TypeScript.hasFlag((cur).getFunctionFlags(), 8192 /* IsFunctionExpression */)) { + lambdaAST = cur; + } else if (cur.nodeType === 17 /* VariableDeclarator */) { + declarationInitASTs[declarationInitASTs.length] = cur; + } else if (cur.nodeType === 22 /* ObjectLiteralExpression */) { + objectLitAST = cur; + } else if (cur.nodeType === 78 /* CastExpression */) { + typeAssertionASTs[typeAssertionASTs.length] = cur; + } else if (cur.nodeType === 38 /* AssignmentExpression */) { + asgAST = cur; + } else if (cur.nodeType === 11 /* TypeRef */) { + inTypeReference = true; + } + + resultASTs[resultASTs.length] = cur; + } + } + } + return cur; + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + + if (resultASTs.length) { + this.pullTypeChecker.setUnit(scriptName); + + foundAST = resultASTs[resultASTs.length - 1]; + + if (foundAST.nodeType === 20 /* Name */ && resultASTs.length > 1) { + var previousAST = resultASTs[resultASTs.length - 2]; + switch (previousAST.nodeType) { + case 14 /* InterfaceDeclaration */: + case 13 /* ClassDeclaration */: + case 15 /* ModuleDeclaration */: + if (foundAST === (previousAST).name) { + foundAST = previousAST; + } + break; + + case 17 /* VariableDeclarator */: + if (foundAST === (previousAST).id) { + foundAST = previousAST; + } + break; + + case 12 /* FunctionDeclaration */: + if (foundAST === (previousAST).name) { + foundAST = previousAST; + } + break; + } + } + + var funcDecl = null; + if (lastDeclAST === foundAST) { + symbol = declStack[declStack.length - 1].getSymbol(); + this.pullTypeChecker.resolver.resolveDeclaredSymbol(symbol, null, resolutionContext); + symbol.setUnresolved(); + enclosingDecl = declStack[declStack.length - 1].getParentDecl(); + if (foundAST.nodeType === 12 /* FunctionDeclaration */) { + funcDecl = foundAST; + } + } else { + for (var i = declStack.length - 1; i >= 0; i--) { + if (!(declStack[i].getKind() & (1024 /* Variable */ | 2048 /* Parameter */))) { + enclosingDecl = declStack[i]; + break; + } + } + + var callExpression = null; + if ((foundAST.nodeType === 30 /* SuperExpression */ || foundAST.nodeType === 29 /* ThisExpression */ || foundAST.nodeType === 20 /* Name */) && resultASTs.length > 1) { + for (var i = resultASTs.length - 2; i >= 0; i--) { + if (resultASTs[i].nodeType === 32 /* MemberAccessExpression */ && (resultASTs[i]).operand2 === resultASTs[i + 1]) { + foundAST = resultASTs[i]; + } else if ((resultASTs[i].nodeType === 36 /* InvocationExpression */ || resultASTs[i].nodeType === 37 /* ObjectCreationExpression */) && (resultASTs[i]).target === resultASTs[i + 1]) { + callExpression = resultASTs[i]; + break; + } else if (resultASTs[i].nodeType === 12 /* FunctionDeclaration */ && (resultASTs[i]).name === resultASTs[i + 1]) { + funcDecl = resultASTs[i]; + break; + } else { + break; + } + } + } + + if (foundAST.nodeType === 1 /* List */) { + for (var i = 0; i < (foundAST).members.length; i++) { + if ((foundAST).members[i].minChar > pos) { + foundAST = (foundAST).members[i]; + break; + } + } + } + + resolutionContext.resolvingTypeReference = inTypeReference; + + var inContextuallyTypedAssignment = false; + + if (declarationInitASTs.length) { + var assigningAST; + + for (var i = 0; i < declarationInitASTs.length; i++) { + assigningAST = declarationInitASTs[i]; + inContextuallyTypedAssignment = (assigningAST !== null) && (assigningAST.typeExpr !== null); + + this.pullTypeChecker.resolver.resolveAST(assigningAST, false, null, resolutionContext); + var varSymbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(assigningAST, scriptName); + var varSymbol = varSymbolAndDiagnostics && varSymbolAndDiagnostics.symbol; + + if (varSymbol && inContextuallyTypedAssignment) { + var contextualType = varSymbol.getType(); + resolutionContext.pushContextualType(contextualType, false, null); + } + + if (assigningAST.init) { + this.pullTypeChecker.resolver.resolveAST(assigningAST.init, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + } + } + + if (typeAssertionASTs.length) { + for (var i = 0; i < typeAssertionASTs.length; i++) { + this.pullTypeChecker.resolver.resolveAST(typeAssertionASTs[i], inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + } + + if (asgAST) { + this.pullTypeChecker.resolver.resolveAST(asgAST, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + + if (objectLitAST) { + this.pullTypeChecker.resolver.resolveAST(objectLitAST, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + + if (lambdaAST) { + this.pullTypeChecker.resolver.resolveAST(lambdaAST, true, enclosingDecl, resolutionContext); + enclosingDecl = semanticInfo.getDeclForAST(lambdaAST); + } + + symbol = this.pullTypeChecker.resolver.resolveAST(foundAST, inContextuallyTypedAssignment, enclosingDecl, resolutionContext).symbol; + if (callExpression) { + var isPropertyOrVar = symbol.getKind() === 4096 /* Property */ || symbol.getKind() === 1024 /* Variable */; + var typeSymbol = symbol.getType(); + if (isPropertyOrVar) { + isPropertyOrVar = (typeSymbol.getKind() !== 16 /* Interface */ && typeSymbol.getKind() !== 8388608 /* ObjectType */) || typeSymbol.getName() === ""; + } + + if (!isPropertyOrVar) { + isConstructorCall = foundAST.nodeType === 30 /* SuperExpression */ || callExpression.nodeType === 37 /* ObjectCreationExpression */; + + if (foundAST.nodeType === 30 /* SuperExpression */) { + if (symbol.getKind() === 8 /* Class */) { + callSignatures = (symbol).getConstructorMethod().getType().getConstructSignatures(); + } + } else { + callSignatures = callExpression.nodeType === 36 /* InvocationExpression */ ? typeSymbol.getCallSignatures() : typeSymbol.getConstructSignatures(); + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (callExpression.nodeType === 36 /* InvocationExpression */) { + this.pullTypeChecker.resolver.resolveCallExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } else { + this.pullTypeChecker.resolver.resolveNewExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.candidateSignature) { + candidateSignature = callResolutionResults.candidateSignature; + } + if (callResolutionResults.targetSymbol && callResolutionResults.targetSymbol.getName() !== "") { + symbol = callResolutionResults.targetSymbol; + } + foundAST = callExpression; + } + } + } + + if (funcDecl) { + if (symbol && symbol.getKind() !== 4096 /* Property */) { + var signatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(funcDecl, this.semanticInfoChain.getUnit(scriptName)); + candidateSignature = signatureInfo.signature; + callSignatures = signatureInfo.allSignatures; + } + } else if (!callSignatures && symbol && (symbol.getKind() === 65536 /* Method */ || symbol.getKind() === 16384 /* Function */)) { + var typeSym = symbol.getType(); + if (typeSym) { + callSignatures = typeSym.getCallSignatures(); + } + } + } + + var enclosingScopeSymbol = this.getSymbolOfDeclaration(enclosingDecl); + + return { + symbol: symbol, + ast: foundAST, + enclosingScopeSymbol: enclosingScopeSymbol, + candidateSignature: candidateSignature, + callSignatures: callSignatures, + isConstructorCall: isConstructorCall + }; + }; + + TypeScriptCompiler.prototype.extractResolutionContextFromPath = function (path, document) { + var script = document.script; + var scriptName = document.fileName; + + var semanticInfo = this.semanticInfoChain.getUnit(scriptName); + var enclosingDecl = null; + var enclosingDeclAST = null; + var inContextuallyTypedAssignment = false; + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + resolutionContext.resolveAggressively = true; + + if (path.count() === 0) { + return null; + } + + this.pullTypeChecker.setUnit(semanticInfo.getPath()); + + for (var i = 0, n = path.count(); i < n; i++) { + var current = path.asts[i]; + + switch (current.nodeType) { + case 12 /* FunctionDeclaration */: + if (TypeScript.hasFlag((current).getFunctionFlags(), 8192 /* IsFunctionExpression */)) { + this.pullTypeChecker.resolver.resolveAST((current), true, enclosingDecl, resolutionContext); + } + + break; + + case 17 /* VariableDeclarator */: + var assigningAST = current; + inContextuallyTypedAssignment = (assigningAST.typeExpr !== null); + + this.pullTypeChecker.resolver.resolveAST(assigningAST, false, null, resolutionContext); + var varSymbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(assigningAST, scriptName); + var varSymbol = varSymbolAndDiagnostics && varSymbolAndDiagnostics.symbol; + + var contextualType = null; + if (varSymbol && inContextuallyTypedAssignment) { + contextualType = varSymbol.getType(); + } + + resolutionContext.pushContextualType(contextualType, false, null); + + if (assigningAST.init) { + this.pullTypeChecker.resolver.resolveAST(assigningAST.init, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + + break; + + case 36 /* InvocationExpression */: + case 37 /* ObjectCreationExpression */: + var isNew = current.nodeType === 37 /* ObjectCreationExpression */; + var callExpression = current; + var contextualType = null; + + if ((i + 1 < n) && callExpression.arguments === path.asts[i + 1]) { + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (isNew) { + this.pullTypeChecker.resolver.resolveNewExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } else { + this.pullTypeChecker.resolver.resolveCallExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.actualParametersContextTypeSymbols) { + var argExpression = (path.asts[i + 1] && path.asts[i + 1].nodeType === 1 /* List */) ? path.asts[i + 2] : path.asts[i + 1]; + if (argExpression) { + for (var j = 0, m = callExpression.arguments.members.length; j < m; j++) { + if (callExpression.arguments.members[j] === argExpression) { + var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j]; + if (callContextualType) { + contextualType = callContextualType; + break; + } + } + } + } + } + } else { + if (isNew) { + this.pullTypeChecker.resolver.resolveNewExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } else { + this.pullTypeChecker.resolver.resolveCallExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 21 /* ArrayLiteralExpression */: + this.pullTypeChecker.resolver.resolveAST(current, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + + var contextualType = null; + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isArray()) { + contextualType = currentContextualType.getElementType(); + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 22 /* ObjectLiteralExpression */: + var objectLiteralExpression = current; + var objectLiteralResolutionContext = new TypeScript.PullAdditionalObjectLiteralResolutionData(); + this.pullTypeChecker.resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, objectLiteralResolutionContext); + + var memeberAST = (path.asts[i + 1] && path.asts[i + 1].nodeType === 1 /* List */) ? path.asts[i + 2] : path.asts[i + 1]; + if (memeberAST) { + var contextualType = null; + var memberDecls = objectLiteralExpression.operand; + if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) { + for (var j = 0, m = memberDecls.members.length; j < m; j++) { + if (memberDecls.members[j] === memeberAST) { + var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j]; + if (memberContextualType) { + contextualType = memberContextualType; + break; + } + } + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + } + + break; + + case 38 /* AssignmentExpression */: + var assignmentExpression = current; + var contextualType = null; + + if (path.asts[i + 1] && path.asts[i + 1] === assignmentExpression.operand2) { + var leftType = this.pullTypeChecker.resolver.resolveAST(assignmentExpression.operand1, inContextuallyTypedAssignment, enclosingDecl, resolutionContext).symbol.getType(); + if (leftType) { + inContextuallyTypedAssignment = true; + contextualType = leftType; + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 78 /* CastExpression */: + var castExpression = current; + var contextualType = null; + + if (i + 1 < n && path.asts[i + 1] === castExpression.castTerm) { + resolutionContext.resolvingTypeReference = true; + } + + var typeSymbol = this.pullTypeChecker.resolver.resolveTypeAssertionExpression(castExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext).symbol; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 93 /* ReturnStatement */: + var returnStatement = current; + var contextualType = null; + + if (enclosingDecl && (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction)) { + var functionDeclaration = enclosingDeclAST; + if (functionDeclaration.returnTypeAnnotation) { + var currentResolvingTypeReference = resolutionContext.resolvingTypeReference; + resolutionContext.resolvingTypeReference = true; + var returnTypeSymbol = this.pullTypeChecker.resolver.resolveTypeReference(functionDeclaration.returnTypeAnnotation, enclosingDecl, resolutionContext).symbol; + resolutionContext.resolvingTypeReference = currentResolvingTypeReference; + if (returnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = returnTypeSymbol; + } + } else { + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var currentContextualTypeSignatureSymbol = currentContextualType.getDeclarations()[0].getSignatureSymbol(); + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.getReturnType(); + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = currentContextualTypeReturnTypeSymbol; + } + } + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 11 /* TypeRef */: + case 9 /* TypeParameter */: + resolutionContext.resolvingTypeReference = true; + break; + } + + var decl = semanticInfo.getDeclForAST(current); + if (decl && !(decl.getKind() & (1024 /* Variable */ | 2048 /* Parameter */ | 8192 /* TypeParameter */))) { + enclosingDecl = decl; + enclosingDeclAST = current; + } + } + + if (path.isNameOfInterface() || path.isInClassImplementsList() || path.isInInterfaceExtendsList()) { + resolutionContext.resolvingTypeReference = true; + } + + if (path.ast().nodeType === 20 /* Name */ && path.count() > 1) { + for (var i = path.count() - 1; i >= 0; i--) { + if (path.asts[path.top - 1].nodeType === 32 /* MemberAccessExpression */ && (path.asts[path.top - 1]).operand2 === path.asts[path.top]) { + path.pop(); + } else { + break; + } + } + } + + return { + ast: path.ast(), + enclosingDecl: enclosingDecl, + resolutionContext: resolutionContext, + inContextuallyTypedAssignment: inContextuallyTypedAssignment + }; + }; + + TypeScriptCompiler.prototype.pullGetSymbolInformationFromPath = function (path, document) { + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var symbolAndDiagnostics = this.pullTypeChecker.resolver.resolveAST(path.ast(), context.inContextuallyTypedAssignment, context.enclosingDecl, context.resolutionContext); + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + + return { + symbol: symbol, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclarationSymbolInformation = function (path, document) { + var script = document.script; + var scriptName = document.fileName; + + var ast = path.ast(); + + if (ast.nodeType !== 13 /* ClassDeclaration */ && ast.nodeType !== 14 /* InterfaceDeclaration */ && ast.nodeType !== 15 /* ModuleDeclaration */ && ast.nodeType !== 12 /* FunctionDeclaration */ && ast.nodeType !== 17 /* VariableDeclarator */) { + return null; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var semanticInfo = this.semanticInfoChain.getUnit(scriptName); + var decl = semanticInfo.getDeclForAST(ast); + var symbol = (decl.getKind() & TypeScript.PullElementKind.SomeSignature) ? decl.getSignatureSymbol() : decl.getSymbol(); + this.pullTypeChecker.resolver.resolveDeclaredSymbol(symbol, null, context.resolutionContext); + + symbol.setUnresolved(); + + return { + symbol: symbol, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetCallInformationFromPath = function (path, document) { + if (path.ast().nodeType !== 36 /* InvocationExpression */ && path.ast().nodeType !== 37 /* ObjectCreationExpression */) { + return null; + } + + var isNew = (path.ast().nodeType === 37 /* ObjectCreationExpression */); + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + + if (isNew) { + this.pullTypeChecker.resolver.resolveNewExpression(path.ast(), context.inContextuallyTypedAssignment, context.enclosingDecl, context.resolutionContext, callResolutionResults); + } else { + this.pullTypeChecker.resolver.resolveCallExpression(path.ast(), context.inContextuallyTypedAssignment, context.enclosingDecl, context.resolutionContext, callResolutionResults); + } + + return { + targetSymbol: callResolutionResults.targetSymbol, + resolvedSignatures: callResolutionResults.resolvedSignatures, + candidateSignature: callResolutionResults.candidateSignature, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl), + isConstructorCall: isNew + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleMemberSymbolsFromPath = function (path, document) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + var symbols = this.pullTypeChecker.resolver.getVisibleMembersFromExpression(path.ast(), context.enclosingDecl, context.resolutionContext); + if (!symbols) { + return null; + } + + return { + symbols: symbols, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleDeclsFromPath = function (path, document) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + var symbols = null; + + return this.pullTypeChecker.resolver.getVisibleDecls(context.enclosingDecl, context.resolutionContext); + }; + + TypeScriptCompiler.prototype.pullGetContextualMembersFromPath = function (path, document) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + if (path.ast().nodeType !== 22 /* ObjectLiteralExpression */) { + return null; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + var members = this.pullTypeChecker.resolver.getVisibleContextSymbols(context.enclosingDecl, context.resolutionContext); + + return { + symbols: members, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclInformation = function (decl, path, document) { + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var symbol = decl.getSymbol(); + this.pullTypeChecker.resolver.resolveDeclaredSymbol(symbol, context.enclosingDecl, context.resolutionContext); + symbol.setUnresolved(); + + return { + symbol: symbol, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetTypeInfoAtPosition = function (pos, document) { + var _this = this; + return this.timeFunction("pullGetTypeInfoAtPosition for pos " + pos + ":", function () { + return _this.resolvePosition(pos, document); + }); + }; + + TypeScriptCompiler.prototype.getTopLevelDeclarations = function (scriptName) { + var unit = this.semanticInfoChain.getUnit(scriptName); + + if (!unit) { + return null; + } + + return unit.getTopLevelDecls(); + }; + + TypeScriptCompiler.prototype.reportDiagnostics = function (errors, errorReporter) { + for (var i = 0; i < errors.length; i++) { + errorReporter.addDiagnostic(errors[i]); + } + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + + CompilerDiagnostics.diagnosticWriter = null; + + CompilerDiagnostics.analysisPass = 0; + + function Alert(output) { + if (CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + + function debugPrint(s) { + if (CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + + function assert(condition, s) { + if (CompilerDiagnostics.debug) { + if (!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var CompilerDiagnostics = TypeScript.CompilerDiagnostics; + + var NullLogger = (function () { + function NullLogger() { + } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if (ioHost.directoryExists(dirName)) { + return; + } + + var parentDirectory = ioHost.dirName(dirName); + if (parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + + function writeFileAndFolderStructure(ioHost, fileName, contents, writeByteOrderMark) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.writeFile(path, contents, writeByteOrderMark); + } + IOUtils.writeFileAndFolderStructure = writeFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; + + var BufferedTextWriter = (function () { + function BufferedTextWriter(writer, capacity) { + if (typeof capacity === "undefined") { capacity = 1024; } + this.writer = writer; + this.capacity = capacity; + this.buffer = ""; + } + BufferedTextWriter.prototype.Write = function (str) { + this.buffer += str; + if (this.buffer.length >= this.capacity) { + this.writer.Write(this.buffer); + this.buffer = ""; + } + }; + BufferedTextWriter.prototype.WriteLine = function (str) { + this.Write(str + '\r\n'); + }; + BufferedTextWriter.prototype.Close = function () { + this.writer.Write(this.buffer); + this.writer.Close(); + this.buffer = null; + }; + return BufferedTextWriter; + })(); + IOUtils.BufferedTextWriter = BufferedTextWriter; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + readFile: function (path) { + return Environment.readFile(path); + }, + writeFile: function (path, contents, writeByteOrderMark) { + Environment.writeFile(path, contents, writeByteOrderMark); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + + while (true) { + if (fso.FileExists(path)) { + return { fileInformation: this.readFile(path), path: path }; + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + + if (rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, fileName) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + fileName + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + readFile: function (file) { + return Environment.readFile(file); + }, + writeFile: function (path, contents, writeByteOrderMark) { + Environment.writeFile(path, contents, writeByteOrderMark); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder) { + var paths = []; + + try { + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if (options.recursive && stat.isDirectory()) { + paths = paths.concat(filesInFolder(folder + "/" + files[i])); + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + } catch (err) { + } + + return paths; + } + + return filesInFolder(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + return { fileInformation: this.readFile(path), path: path }; + } else { + var parentPath = _path.resolve(rootPath, ".."); + + if (rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (fileName, callback) { + var firstRun = true; + var processingChange = false; + + var fileChanged = function (curr, prev) { + if (!firstRun) { + if (curr.mtime < prev.mtime) { + return; + } + + _fs.unwatchFile(fileName, fileChanged); + if (!processingChange) { + processingChange = true; + callback(fileName); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(fileName, { persistent: true, interval: 500 }, fileChanged); + }; + + fileChanged(); + return { + fileName: fileName, + close: function () { + _fs.unwatchFile(fileName, fileChanged); + } + }; + }, + run: function (source, fileName) { + require.main.fileName = fileName; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(fileName))); + require.main._compile(source, fileName); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + + if (typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); else if (typeof module !== 'undefined' && module.exports) + return getNodeIO(); else + return null; +})(); +var OptionsParser = (function () { + function OptionsParser(host) { + this.host = host; + this.DEFAULT_SHORT_FLAG = "-"; + this.DEFAULT_LONG_FLAG = "--"; + this.unnamed = []; + this.options = []; + } + OptionsParser.prototype.findOption = function (arg) { + for (var i = 0; i < this.options.length; i++) { + if (arg === this.options[i].short || arg === this.options[i].name) { + return this.options[i]; + } + } + + return null; + }; + + OptionsParser.prototype.printUsage = function () { + this.host.printLine("Syntax: tsc [options] [file ..]"); + this.host.printLine(""); + this.host.printLine("Examples: tsc hello.ts"); + this.host.printLine(" tsc --out foo.js foo.ts"); + this.host.printLine(" tsc @args.txt"); + this.host.printLine(""); + this.host.printLine("Options:"); + + var output = []; + var maxLength = 0; + var i = 0; + + this.options = this.options.sort(function (a, b) { + var aName = a.name.toLowerCase(); + var bName = b.name.toLowerCase(); + + if (aName > bName) { + return 1; + } else if (aName < bName) { + return -1; + } else { + return 0; + } + }); + + for (i = 0; i < this.options.length; i++) { + var option = this.options[i]; + + if (option.experimental) { + continue; + } + + if (!option.usage) { + break; + } + + var usageString = " "; + var type = option.type ? " " + option.type.toUpperCase() : ""; + + if (option.short) { + usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; + } + + usageString += this.DEFAULT_LONG_FLAG + option.name + type; + + output.push([usageString, option.usage]); + + if (usageString.length > maxLength) { + maxLength = usageString.length; + } + } + + output.push([" @", "Insert command line options and files from a file."]); + + for (i = 0; i < output.length; i++) { + this.host.printLine(output[i][0] + (new Array(maxLength - output[i][0].length + 3)).join(" ") + output[i][1]); + } + }; + + OptionsParser.prototype.option = function (name, config, short) { + if (!config) { + config = short; + short = null; + } + + config.name = name; + config.short = short; + config.flag = false; + + this.options.push(config); + }; + + OptionsParser.prototype.flag = function (name, config, short) { + if (!config) { + config = short; + short = null; + } + + config.name = name; + config.short = short; + config.flag = true; + + this.options.push(config); + }; + + OptionsParser.prototype.parseString = function (argString) { + var position = 0; + var tokens = argString.match(/\s+|"|[^\s"]+/g); + + function peek() { + return tokens[position]; + } + + function consume() { + return tokens[position++]; + } + + function consumeQuotedString() { + var value = ''; + consume(); + + var token = peek(); + + while (token && token !== '"') { + consume(); + + value += token; + + token = peek(); + } + + consume(); + + return value; + } + + var args = []; + var currentArg = ''; + + while (position < tokens.length) { + var token = peek(); + + if (token === '"') { + currentArg += consumeQuotedString(); + } else if (token.match(/\s/)) { + if (currentArg.length > 0) { + args.push(currentArg); + currentArg = ''; + } + + consume(); + } else { + consume(); + currentArg += token; + } + } + + if (currentArg.length > 0) { + args.push(currentArg); + } + + this.parse(args); + }; + + OptionsParser.prototype.parse = function (args) { + var position = 0; + + function consume() { + return args[position++]; + } + + while (position < args.length) { + var current = consume(); + var match = current.match(/^(--?|@)(.*)/); + var value = null; + + if (match) { + if (match[1] === '@') { + this.parseString(this.host.readFile(match[2]).contents()); + } else { + var arg = match[2]; + var option = this.findOption(arg); + + if (option === null) { + this.host.printLine("Unknown option '" + arg + "'"); + this.host.printLine("Use the '--help' flag to see options"); + } else { + if (!option.flag) + value = consume(); + + option.set(value); + } + } + } else { + this.unnamed.push(current); + } + } + }; + return OptionsParser; +})(); +var DiagnosticsLogger = (function () { + function DiagnosticsLogger(ioHost) { + this.ioHost = ioHost; + } + DiagnosticsLogger.prototype.information = function () { + return false; + }; + DiagnosticsLogger.prototype.debug = function () { + return false; + }; + DiagnosticsLogger.prototype.warning = function () { + return false; + }; + DiagnosticsLogger.prototype.error = function () { + return false; + }; + DiagnosticsLogger.prototype.fatal = function () { + return false; + }; + DiagnosticsLogger.prototype.log = function (s) { + this.ioHost.stdout.WriteLine(s); + }; + return DiagnosticsLogger; +})(); + +var ErrorReporter = (function () { + function ErrorReporter(ioHost, compilationEnvironment) { + this.ioHost = ioHost; + this.hasErrors = false; + this.setCompilationEnvironment(compilationEnvironment); + } + ErrorReporter.prototype.addDiagnostic = function (diagnostic) { + this.hasErrors = true; + + if (diagnostic.fileName()) { + var soruceUnit = this.compilationEnvironment.getSourceUnit(diagnostic.fileName()); + if (!soruceUnit) { + soruceUnit = new TypeScript.SourceUnit(diagnostic.fileName(), this.ioHost.readFile(diagnostic.fileName())); + } + var lineMap = new TypeScript.LineMap(soruceUnit.getLineStartPositions(), soruceUnit.getLength()); + var lineCol = { line: -1, character: -1 }; + lineMap.fillLineAndCharacterFromPosition(diagnostic.start(), lineCol); + + this.ioHost.stderr.Write(diagnostic.fileName() + "(" + (lineCol.line + 1) + "," + (lineCol.character + 1) + "): "); + } + + this.ioHost.stderr.WriteLine(diagnostic.message()); + }; + + ErrorReporter.prototype.setCompilationEnvironment = function (compilationEnvironment) { + this.compilationEnvironment = compilationEnvironment; + }; + + ErrorReporter.prototype.reset = function () { + this.hasErrors = false; + }; + return ErrorReporter; +})(); + +var CommandLineHost = (function () { + function CommandLineHost(compilationSettings, errorReporter) { + this.compilationSettings = compilationSettings; + this.errorReporter = errorReporter; + this.pathMap = {}; + this.resolvedPaths = {}; + } + CommandLineHost.prototype.getPathIdentifier = function (path) { + return this.compilationSettings.useCaseSensitiveFileResolution ? path : path.toLocaleUpperCase(); + }; + + CommandLineHost.prototype.isResolved = function (path) { + return this.resolvedPaths[this.getPathIdentifier(this.pathMap[path])] != undefined; + }; + + CommandLineHost.prototype.resolveCompilationEnvironment = function (preEnv, resolver, traceDependencies) { + var _this = this; + var resolvedEnv = new TypeScript.CompilationEnvironment(preEnv.compilationSettings, preEnv.ioHost); + + var nCode = preEnv.code.length; + var path = ""; + + this.errorReporter.setCompilationEnvironment(resolvedEnv); + + var resolutionDispatcher = { + errorReporter: this.errorReporter, + postResolution: function (path, code) { + var pathId = _this.getPathIdentifier(path); + if (!_this.resolvedPaths[pathId]) { + resolvedEnv.code.push(code); + _this.resolvedPaths[pathId] = true; + } + } + }; + + for (var i = 0; i < nCode; i++) { + path = TypeScript.switchToForwardSlashes(preEnv.ioHost.resolvePath(preEnv.code[i].path)); + this.pathMap[preEnv.code[i].path] = path; + resolver.resolveCode(path, "", false, resolutionDispatcher); + } + + return resolvedEnv; + }; + return CommandLineHost; +})(); + +var BatchCompiler = (function () { + function BatchCompiler(ioHost) { + this.ioHost = ioHost; + this.resolvedEnvironment = null; + this.hasResolveErrors = false; + this.compilerVersion = "0.9.0.0"; + this.printedVersion = false; + this.errorReporter = null; + this.compilationSettings = new TypeScript.CompilationSettings(); + this.compilationEnvironment = new TypeScript.CompilationEnvironment(this.compilationSettings, this.ioHost); + this.errorReporter = new ErrorReporter(this.ioHost, this.compilationEnvironment); + } + BatchCompiler.prototype.resolve = function () { + var resolver = new TypeScript.CodeResolver(this.compilationEnvironment); + var commandLineHost = new CommandLineHost(this.compilationSettings, this.errorReporter); + var ret = commandLineHost.resolveCompilationEnvironment(this.compilationEnvironment, resolver, true); + + for (var i = 0; i < this.compilationEnvironment.code.length; i++) { + if (!commandLineHost.isResolved(this.compilationEnvironment.code[i].path)) { + var path = this.compilationEnvironment.code[i].path; + if (!TypeScript.isTSFile(path) && !TypeScript.isDTSFile(path)) { + this.errorReporter.addDiagnostic(new TypeScript.Diagnostic(null, 0, 0, 269 /* Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed */, [path])); + } else { + this.errorReporter.addDiagnostic(new TypeScript.Diagnostic(null, 0, 0, 268 /* Could_not_find_file___0_ */, [path])); + } + } + } + + return ret; + }; + + BatchCompiler.prototype.compile = function () { + var _this = this; + if (typeof localizedDiagnosticMessages === "undefined") { + localizedDiagnosticMessages = null; + } + + var logger = this.compilationSettings.gatherDiagnostics ? new DiagnosticsLogger(this.ioHost) : new TypeScript.NullLogger(); + var compiler = new TypeScript.TypeScriptCompiler(logger, this.compilationSettings, localizedDiagnosticMessages); + + var anySyntacticErrors = false; + var anySemanticErrors = false; + + for (var iCode = 0; iCode < this.resolvedEnvironment.code.length; iCode++) { + var code = this.resolvedEnvironment.code[iCode]; + + if (!this.compilationSettings.resolve) { + code.fileInformation = this.ioHost.readFile(code.path); + + if (this.compilationSettings.generateDeclarationFiles) { + TypeScript.CompilerDiagnostics.assert(code.referencedFiles === null, "With no resolve option, referenced files need to null"); + code.referencedFiles = TypeScript.getReferencedFiles(code.path, code); + } + } + + if (code.fileInformation != null) { + compiler.addSourceUnit(code.path, TypeScript.ScriptSnapshot.fromString(code.fileInformation.contents()), code.fileInformation.byteOrderMark(), 0, false, code.referencedFiles); + + var syntacticDiagnostics = compiler.getSyntacticDiagnostics(code.path); + compiler.reportDiagnostics(syntacticDiagnostics, this.errorReporter); + + if (syntacticDiagnostics.length > 0) { + anySyntacticErrors = true; + } + } + } + + if (anySyntacticErrors) { + return true; + } + + compiler.pullTypeCheck(); + var fileNames = compiler.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + var semanticDiagnostics = compiler.getSemanticDiagnostics(fileName); + if (semanticDiagnostics.length > 0) { + anySemanticErrors = true; + compiler.reportDiagnostics(semanticDiagnostics, this.errorReporter); + } + } + + var emitterIOHost = { + writeFile: function (fileName, contents, writeByteOrderMark) { + return IOUtils.writeFileAndFolderStructure(_this.ioHost, fileName, contents, writeByteOrderMark); + }, + directoryExists: this.ioHost.directoryExists, + fileExists: this.ioHost.fileExists, + resolvePath: this.ioHost.resolvePath + }; + + var mapInputToOutput = function (inputFile, outputFile) { + _this.resolvedEnvironment.inputFileNameToOutputFileName.addOrUpdate(inputFile, outputFile); + }; + + var emitDiagnostics = compiler.emitAll(emitterIOHost, mapInputToOutput); + compiler.reportDiagnostics(emitDiagnostics, this.errorReporter); + if (emitDiagnostics.length > 0) { + return true; + } + + if (anySemanticErrors) { + return true; + } + + var emitDeclarationsDiagnostics = compiler.emitAllDeclarations(); + compiler.reportDiagnostics(emitDeclarationsDiagnostics, this.errorReporter); + if (emitDeclarationsDiagnostics.length > 0) { + return true; + } + + return false; + }; + + BatchCompiler.prototype.updateCompile = function () { + if (typeof localizedDiagnosticMessages === "undefined") { + localizedDiagnosticMessages = null; + } + + var logger = this.compilationSettings.gatherDiagnostics ? new DiagnosticsLogger(this.ioHost) : new TypeScript.NullLogger(); + var compiler = new TypeScript.TypeScriptCompiler(logger, this.compilationSettings, localizedDiagnosticMessages); + + var anySyntacticErrors = false; + var foundLib = false; + + for (var iCode = 0; iCode <= this.resolvedEnvironment.code.length; iCode++) { + var code = this.resolvedEnvironment.code[iCode]; + + if (code.path.indexOf("lib.d.ts") != -1) { + foundLib = true; + } else if ((foundLib && iCode > 1) || (!foundLib && iCode > 0)) { + break; + } + + this.ioHost.stdout.WriteLine("Consuming " + this.resolvedEnvironment.code[iCode].path + "..."); + + if (!this.compilationSettings.resolve) { + code.fileInformation = this.ioHost.readFile(code.path); + + if (this.compilationSettings.generateDeclarationFiles) { + TypeScript.CompilerDiagnostics.assert(code.referencedFiles === null, "With no resolve option, referenced files need to null"); + code.referencedFiles = TypeScript.getReferencedFiles(code.path, code); + } + } + + if (code.fileInformation != null) { + compiler.addSourceUnit(code.path, TypeScript.ScriptSnapshot.fromString(code.fileInformation.contents()), code.fileInformation.byteOrderMark(), 0, true, code.referencedFiles); + + var syntacticDiagnostics = compiler.getSyntacticDiagnostics(code.path); + compiler.reportDiagnostics(syntacticDiagnostics, this.errorReporter); + + if (syntacticDiagnostics.length > 0) { + anySyntacticErrors = true; + } + } + } + + this.ioHost.stdout.WriteLine("**** Initial type check errors:"); + compiler.pullTypeCheck(); + + var semanticDiagnostics; + + for (var i = 0; i < iCode; i++) { + semanticDiagnostics = compiler.getSemanticDiagnostics(this.resolvedEnvironment.code[i].path); + compiler.reportDiagnostics(semanticDiagnostics, this.errorReporter); + } + + if (iCode && iCode <= this.resolvedEnvironment.code.length - 1) { + var lastTypecheckedFileName = this.resolvedEnvironment.code[iCode - 1].path; + var snapshot; + + for (; iCode < this.resolvedEnvironment.code.length; iCode++) { + this.ioHost.stdout.WriteLine("**** Update type check and errors for " + this.resolvedEnvironment.code[iCode].path + ":"); + var text = this.resolvedEnvironment.code[iCode].getText(0, this.resolvedEnvironment.code[iCode].getLength()); + snapshot = TypeScript.ScriptSnapshot.fromString(text); + compiler.updateSourceUnit(lastTypecheckedFileName, snapshot, 0, true, null); + + semanticDiagnostics = compiler.getSemanticDiagnostics(lastTypecheckedFileName); + compiler.reportDiagnostics(semanticDiagnostics, this.errorReporter); + } + } + + return false; + }; + + BatchCompiler.prototype.run = function () { + for (var i in this.resolvedEnvironment.code) { + var outputFileName = this.resolvedEnvironment.inputFileNameToOutputFileName.lookup(this.resolvedEnvironment.code[i].path) || undefined; + if (this.ioHost.fileExists(outputFileName)) { + var unitRes = this.ioHost.readFile(outputFileName); + this.ioHost.run(unitRes.contents(), outputFileName); + } + } + }; + + BatchCompiler.prototype.batchCompile = function () { + var _this = this; + TypeScript.CompilerDiagnostics.diagnosticWriter = { Alert: function (s) { + _this.ioHost.printLine(s); + } }; + + var code; + + var opts = new OptionsParser(this.ioHost); + + opts.option('out', { + usage: 'Concatenate and emit output to single file | Redirect output structure to the directory', + type: 'file|directory', + set: function (str) { + _this.compilationSettings.outputOption = str; + } + }); + + opts.flag('sourcemap', { + usage: 'Generates corresponding .map file', + set: function () { + _this.compilationSettings.mapSourceFiles = true; + } + }); + + opts.flag('fullSourceMapPath', { + usage: 'Writes the full path of map file in the generated js file', + experimental: true, + set: function () { + _this.compilationSettings.emitFullSourceMapPath = true; + } + }); + + opts.flag('declaration', { + usage: 'Generates corresponding .d.ts file', + set: function () { + _this.compilationSettings.generateDeclarationFiles = true; + } + }, 'd'); + + if (this.ioHost.watchFile) { + opts.flag('watch', { + usage: 'Watch input files', + set: function () { + _this.compilationSettings.watch = true; + } + }, 'w'); + } + + opts.flag('exec', { + usage: 'Execute the script after compilation', + set: function () { + _this.compilationSettings.exec = true; + } + }, 'e'); + + opts.flag('minw', { + usage: 'Minimize whitespace', + experimental: true, + set: function () { + _this.compilationSettings.minWhitespace = true; + } + }, 'mw'); + + opts.flag('const', { + usage: 'Propagate constants to emitted code', + experimental: true, + set: function () { + _this.compilationSettings.propagateConstants = true; + } + }); + + opts.flag('comments', { + usage: 'Emit comments to output', + set: function () { + _this.compilationSettings.emitComments = true; + } + }, 'c'); + + opts.flag('noresolve', { + usage: 'Skip resolution and preprocessing', + experimental: true, + set: function () { + _this.compilationSettings.resolve = false; + } + }); + + opts.flag('debug', { + usage: 'Print debug output', + experimental: true, + set: function () { + TypeScript.CompilerDiagnostics.debug = true; + } + }); + + opts.flag('nolib', { + usage: 'Do not include a default lib.d.ts with global declarations', + set: function () { + _this.compilationSettings.useDefaultLib = false; + } + }); + + opts.flag('diagnostics', { + usage: 'gather diagnostic info about the compilation process', + experimental: true, + set: function () { + _this.compilationSettings.gatherDiagnostics = true; + } + }); + + opts.flag('update', { + usage: 'Typecheck each file as an update on the first', + experimental: true, + set: function () { + _this.compilationSettings.updateTC = true; + } + }); + + opts.option('target', { + usage: 'Specify ECMAScript target version: "ES3" (default), or "ES5"', + type: 'VER', + set: function (type) { + type = type.toLowerCase(); + + if (type === 'es3') { + _this.compilationSettings.codeGenTarget = 0 /* EcmaScript3 */; + } else if (type === 'es5') { + _this.compilationSettings.codeGenTarget = 1 /* EcmaScript5 */; + } else { + _this.errorReporter.addDiagnostic(new TypeScript.Diagnostic(null, 0, 0, 266 /* ECMAScript_target_version__0__not_supported___Using_default__1__code_generation */, [type, "ES3"])); + } + } + }); + + opts.option('module', { + usage: 'Specify module code generation: "commonjs" (default) or "amd"', + type: 'kind', + set: function (type) { + type = type.toLowerCase(); + + if (type === 'commonjs' || type === 'node') { + _this.compilationSettings.moduleGenTarget = 0 /* Synchronous */; + } else if (type === 'amd') { + _this.compilationSettings.moduleGenTarget = 1 /* Asynchronous */; + } else { + _this.errorReporter.addDiagnostic(new TypeScript.Diagnostic(null, 0, 0, 267 /* Module_code_generation__0__not_supported___Using_default__1__code_generation */, [type, "commonjs"])); + } + } + }); + + var printedUsage = false; + + opts.flag('help', { + usage: 'Print this message', + set: function () { + _this.printVersion(); + opts.printUsage(); + printedUsage = true; + } + }, 'h'); + + opts.flag('useCaseSensitiveFileResolution', { + usage: 'Force file resolution to be case sensitive', + experimental: true, + set: function () { + _this.compilationSettings.useCaseSensitiveFileResolution = true; + } + }); + + opts.flag('version', { + usage: 'Print the compiler\'s version: ' + this.compilerVersion, + set: function () { + _this.printVersion(); + } + }, 'v'); + + opts.flag('disallowbool', { + usage: 'Throw error for use of deprecated "bool" type', + set: function () { + _this.compilationSettings.disallowBool = true; + } + }, 'b'); + + opts.flag('disallowimportmodule', { + usage: 'Throw error for use of deprecated "module" keyword when referencing an external module. Only allow "require" keyword.', + set: function () { + _this.compilationSettings.allowModuleKeywordInExternalModuleReference = false; + } + }, 'm'); + + opts.parse(this.ioHost.arguments); + + if (this.compilationSettings.useDefaultLib) { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var binDirPath = this.ioHost.dirName(compilerFilePath); + var libStrPath = this.ioHost.resolvePath(binDirPath + "/lib.d.ts"); + code = new TypeScript.SourceUnit(libStrPath, null); + this.compilationEnvironment.code.push(code); + } + + for (var i = 0; i < opts.unnamed.length; i++) { + code = new TypeScript.SourceUnit(opts.unnamed[i], null); + this.compilationEnvironment.code.push(code); + } + + if (this.compilationEnvironment.code.length === (this.compilationSettings.useDefaultLib ? 1 : 0)) { + if (!printedUsage && !this.printedVersion) { + this.printVersion(); + opts.printUsage(); + this.ioHost.quit(1); + } + return; + } + + if (this.compilationSettings.watch) { + this.watchFiles(this.compilationEnvironment.code.slice(0)); + } else { + this.resolvedEnvironment = this.compilationSettings.resolve ? this.resolve() : this.compilationEnvironment; + + if (!this.compilationSettings.updateTC) { + this.compile(); + } else { + this.updateCompile(); + } + + if (!this.errorReporter.hasErrors) { + if (this.compilationSettings.exec) { + this.run(); + } + } + + this.ioHost.quit(this.errorReporter.hasErrors ? 1 : 0); + } + }; + + BatchCompiler.prototype.printVersion = function () { + if (!this.printedVersion) { + this.ioHost.printLine("Version " + this.compilerVersion); + this.printedVersion = true; + } + }; + + BatchCompiler.prototype.watchFiles = function (sourceFiles) { + var _this = this; + if (!this.ioHost.watchFile) { + this.errorReporter.addDiagnostic(new TypeScript.SemanticDiagnostic(null, 0, 0, 265 /* Current_host_does_not_support__w_atch_option */, null)); + return; + } + + var resolvedFiles = []; + var watchers = {}; + var firstTime = true; + + var addWatcher = function (fileName) { + if (!watchers[fileName]) { + var watcher = _this.ioHost.watchFile(fileName, onWatchedFileChange); + watchers[fileName] = watcher; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Cannot watch file, it is already watched."); + } + }; + + var removeWatcher = function (fileName) { + if (watchers[fileName]) { + watchers[fileName].close(); + delete watchers[fileName]; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Cannot stop watching file, it is not being watched."); + } + }; + + var onWatchedFileChange = function () { + _this.compilationEnvironment.code = sourceFiles; + + _this.errorReporter.reset(); + + _this.resolvedEnvironment = _this.compilationSettings.resolve ? _this.resolve() : _this.compilationEnvironment; + + var oldFiles = resolvedFiles; + var newFiles = []; + _this.resolvedEnvironment.code.forEach(function (sf) { + return newFiles.push(sf.path); + }); + newFiles = newFiles.sort(); + + var i = 0, j = 0; + while (i < oldFiles.length && j < newFiles.length) { + var compareResult = oldFiles[i].localeCompare(newFiles[j]); + if (compareResult === 0) { + i++; + j++; + } else if (compareResult < 0) { + removeWatcher(oldFiles[i]); + i++; + } else { + addWatcher(newFiles[j]); + j++; + } + } + + for (var k = i; k < oldFiles.length; k++) { + removeWatcher(oldFiles[k]); + } + + for (k = j; k < newFiles.length; k++) { + addWatcher(newFiles[k]); + } + + resolvedFiles = newFiles; + + if (!firstTime) { + _this.ioHost.printLine(""); + _this.ioHost.printLine("Recompiling (" + new Date() + "): "); + resolvedFiles.forEach(function (f) { + return _this.ioHost.printLine(" " + f); + }); + } + + _this.compile(); + + if (!_this.errorReporter.hasErrors && _this.compilationSettings.exec) { + try { + _this.run(); + } catch (e) { + if (e.stack) { + _this.ioHost.stderr.WriteLine('\n' + e.stack); + } + } + } + + firstTime = false; + }; + + this.ioHost.stderr = this.ioHost.stdout; + onWatchedFileChange(); + }; + return BatchCompiler; +})(); + +var batch = new BatchCompiler(IO); +batch.batchCompile(); diff --git a/_infrastructure/tests/typescript/typescript.js b/_infrastructure/tests/typescript/typescript.js new file mode 100644 index 000000000..0fdb51331 --- /dev/null +++ b/_infrastructure/tests/typescript/typescript.js @@ -0,0 +1,55609 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.isArray = function (value) { + return Object.prototype.toString.apply(value, []) === '[object Array]'; + }; + + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + + if (array1 === null || array2 === null) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + + return false; + }; + + ArrayUtilities.groupBy = function (array, func) { + var result = {}; + + for (var i = 0, n = array.length; i < n; i++) { + var v = array[i]; + var k = func(v); + + var list = result[k] || []; + list.push(v); + result[k] = list; + } + + return result; + }; + + ArrayUtilities.min = function (array, func) { + var min = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next < min) { + min = next; + } + } + + return min; + }; + + ArrayUtilities.max = function (array, func) { + var max = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next > max) { + max = next; + } + } + + return max; + }; + + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + + return array[array.length - 1]; + }; + + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value)) { + return value; + } + } + + return null; + }; + + ArrayUtilities.sum = function (array, func) { + var result = 0; + + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + + return result; + }; + + ArrayUtilities.whereNotNull = function (array) { + var result = []; + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (value !== null) { + result.push(value); + } + } + + return result; + }; + + ArrayUtilities.select = function (values, func) { + var result = []; + + for (var i = 0; i < values.length; i++) { + result.push(func(values[i])); + } + + return result; + }; + + ArrayUtilities.where = function (values, func) { + var result = []; + + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + + return result; + }; + + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + + return false; + }; + + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + + if (midValue === value) { + return middle; + } else if (midValue > value) { + high = middle - 1; + } else { + low = middle + 1; + } + } + + return ~low; + }; + + ArrayUtilities.createArray = function (length, defaultvalue) { + var result = []; + for (var i = 0; i < length; i++) { + result.push(defaultvalue); + } + + return result; + }; + + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Constants) { + Constants[Constants["Max31BitInteger"] = 1073741823] = "Max31BitInteger"; + Constants[Constants["Min31BitInteger"] = -1073741824] = "Min31BitInteger"; + })(TypeScript.Constants || (TypeScript.Constants = {})); + var Constants = TypeScript.Constants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Contract = (function () { + function Contract() { + } + Contract.requires = function (expression) { + if (!expression) { + throw new Error("Contract violated. False expression."); + } + }; + + Contract.throwIfFalse = function (expression) { + if (!expression) { + throw new Error("Contract violated. False expression."); + } + }; + + Contract.throwIfNull = function (value) { + if (value === null) { + throw new Error("Contract violated. Null value."); + } + }; + return Contract; + })(); + TypeScript.Contract = Contract; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Debug = (function () { + function Debug() { + } + Debug.assert = function (expression, message) { + if (!expression) { + throw new Error("Debug Failure. False expression: " + (message ? message : "")); + } + }; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCode) { + DiagnosticCode[DiagnosticCode["error_TS_0__1"] = 0] = "error_TS_0__1"; + DiagnosticCode[DiagnosticCode["warning_TS_0__1"] = 1] = "warning_TS_0__1"; + + DiagnosticCode[DiagnosticCode["_0__NL__1_TB__2"] = 2] = "_0__NL__1_TB__2"; + DiagnosticCode[DiagnosticCode["_0_TB__1"] = 3] = "_0_TB__1"; + + DiagnosticCode[DiagnosticCode["Unrecognized_escape_sequence"] = 4] = "Unrecognized_escape_sequence"; + DiagnosticCode[DiagnosticCode["Unexpected_character_0"] = 5] = "Unexpected_character_0"; + DiagnosticCode[DiagnosticCode["Missing_closing_quote_character"] = 6] = "Missing_closing_quote_character"; + DiagnosticCode[DiagnosticCode["Identifier_expected"] = 7] = "Identifier_expected"; + DiagnosticCode[DiagnosticCode["_0_keyword_expected"] = 8] = "_0_keyword_expected"; + DiagnosticCode[DiagnosticCode["_0_expected"] = 9] = "_0_expected"; + DiagnosticCode[DiagnosticCode["Identifier_expected__0__is_a_keyword"] = 10] = "Identifier_expected__0__is_a_keyword"; + DiagnosticCode[DiagnosticCode["Automatic_semicolon_insertion_not_allowed"] = 11] = "Automatic_semicolon_insertion_not_allowed"; + DiagnosticCode[DiagnosticCode["Unexpected_token__0_expected"] = 12] = "Unexpected_token__0_expected"; + DiagnosticCode[DiagnosticCode["Trailing_separator_not_allowed"] = 13] = "Trailing_separator_not_allowed"; + DiagnosticCode[DiagnosticCode["_StarSlash__expected"] = 14] = "_StarSlash__expected"; + DiagnosticCode[DiagnosticCode["_public_or_private_modifier_must_precede__static_"] = 15] = "_public_or_private_modifier_must_precede__static_"; + DiagnosticCode[DiagnosticCode["Unexpected_token_"] = 16] = "Unexpected_token_"; + DiagnosticCode[DiagnosticCode["A_catch_clause_variable_cannot_have_a_type_annotation"] = 17] = "A_catch_clause_variable_cannot_have_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Rest_parameter_must_be_last_in_list"] = 18] = "Rest_parameter_must_be_last_in_list"; + DiagnosticCode[DiagnosticCode["Parameter_cannot_have_question_mark_and_initializer"] = 19] = "Parameter_cannot_have_question_mark_and_initializer"; + DiagnosticCode[DiagnosticCode["Required_parameter_cannot_follow_optional_parameter"] = 20] = "Required_parameter_cannot_follow_optional_parameter"; + DiagnosticCode[DiagnosticCode["Index_signatures_cannot_have_rest_parameters"] = 21] = "Index_signatures_cannot_have_rest_parameters"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_cannot_have_accessibility_modifiers"] = 22] = "Index_signature_parameter_cannot_have_accessibility_modifiers"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_cannot_have_a_question_mark"] = 23] = "Index_signature_parameter_cannot_have_a_question_mark"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_cannot_have_an_initializer"] = 24] = "Index_signature_parameter_cannot_have_an_initializer"; + DiagnosticCode[DiagnosticCode["Index_signature_must_have_a_type_annotation"] = 25] = "Index_signature_must_have_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_must_have_a_type_annotation"] = 26] = "Index_signature_parameter_must_have_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Index_signature_parameter_type_must_be__string__or__number_"] = 27] = "Index_signature_parameter_type_must_be__string__or__number_"; + DiagnosticCode[DiagnosticCode["_extends__clause_already_seen"] = 28] = "_extends__clause_already_seen"; + DiagnosticCode[DiagnosticCode["_extends__clause_must_precede__implements__clause"] = 29] = "_extends__clause_must_precede__implements__clause"; + DiagnosticCode[DiagnosticCode["Class_can_only_extend_single_type"] = 30] = "Class_can_only_extend_single_type"; + DiagnosticCode[DiagnosticCode["_implements__clause_already_seen"] = 31] = "_implements__clause_already_seen"; + DiagnosticCode[DiagnosticCode["Accessibility_modifier_already_seen"] = 32] = "Accessibility_modifier_already_seen"; + DiagnosticCode[DiagnosticCode["_0__modifier_must_precede__1__modifier"] = 33] = "_0__modifier_must_precede__1__modifier"; + DiagnosticCode[DiagnosticCode["_0__modifier_already_seen"] = 34] = "_0__modifier_already_seen"; + DiagnosticCode[DiagnosticCode["_0__modifier_cannot_appear_on_a_class_element"] = 35] = "_0__modifier_cannot_appear_on_a_class_element"; + DiagnosticCode[DiagnosticCode["Interface_declaration_cannot_have__implements__clause"] = 36] = "Interface_declaration_cannot_have__implements__clause"; + DiagnosticCode[DiagnosticCode["_super__invocation_cannot_have_type_arguments"] = 37] = "_super__invocation_cannot_have_type_arguments"; + DiagnosticCode[DiagnosticCode["Non_ambient_modules_cannot_use_quoted_names"] = 38] = "Non_ambient_modules_cannot_use_quoted_names"; + DiagnosticCode[DiagnosticCode["Statements_are_not_allowed_in_ambient_contexts"] = 39] = "Statements_are_not_allowed_in_ambient_contexts"; + DiagnosticCode[DiagnosticCode["Implementations_are_not_allowed_in_ambient_contexts"] = 40] = "Implementations_are_not_allowed_in_ambient_contexts"; + DiagnosticCode[DiagnosticCode["_declare__modifier_not_allowed_for_code_already_in_an_ambient_context"] = 41] = "_declare__modifier_not_allowed_for_code_already_in_an_ambient_context"; + DiagnosticCode[DiagnosticCode["Initializers_are_not_allowed_in_ambient_contexts"] = 42] = "Initializers_are_not_allowed_in_ambient_contexts"; + DiagnosticCode[DiagnosticCode["Overload_and_ambient_signatures_cannot_specify_parameter_properties"] = 43] = "Overload_and_ambient_signatures_cannot_specify_parameter_properties"; + DiagnosticCode[DiagnosticCode["Function_implementation_expected"] = 44] = "Function_implementation_expected"; + DiagnosticCode[DiagnosticCode["Constructor_implementation_expected"] = 45] = "Constructor_implementation_expected"; + DiagnosticCode[DiagnosticCode["Function_overload_name_must_be__0_"] = 46] = "Function_overload_name_must_be__0_"; + DiagnosticCode[DiagnosticCode["_0__modifier_cannot_appear_on_a_module_element"] = 47] = "_0__modifier_cannot_appear_on_a_module_element"; + DiagnosticCode[DiagnosticCode["_declare__modifier_cannot_appear_on_an_interface_declaration"] = 48] = "_declare__modifier_cannot_appear_on_an_interface_declaration"; + DiagnosticCode[DiagnosticCode["_declare__modifier_required_for_top_level_element"] = 49] = "_declare__modifier_required_for_top_level_element"; + DiagnosticCode[DiagnosticCode["_set__accessor_must_have_only_one_parameter"] = 50] = "_set__accessor_must_have_only_one_parameter"; + DiagnosticCode[DiagnosticCode["_set__accessor_parameter_cannot_have_accessibility_modifier"] = 51] = "_set__accessor_parameter_cannot_have_accessibility_modifier"; + DiagnosticCode[DiagnosticCode["_set__accessor_parameter_cannot_be_optional"] = 52] = "_set__accessor_parameter_cannot_be_optional"; + DiagnosticCode[DiagnosticCode["_set__accessor_parameter_cannot_have_initializer"] = 53] = "_set__accessor_parameter_cannot_have_initializer"; + DiagnosticCode[DiagnosticCode["_set__accessor_cannot_have_rest_parameter"] = 54] = "_set__accessor_cannot_have_rest_parameter"; + DiagnosticCode[DiagnosticCode["_get__accessor_cannot_have_parameters"] = 55] = "_get__accessor_cannot_have_parameters"; + DiagnosticCode[DiagnosticCode["Rest_parameter_cannot_be_optional"] = 56] = "Rest_parameter_cannot_be_optional"; + DiagnosticCode[DiagnosticCode["Rest_parameter_cannot_have_initializer"] = 57] = "Rest_parameter_cannot_have_initializer"; + DiagnosticCode[DiagnosticCode["Modifiers_cannot_appear_here"] = 58] = "Modifiers_cannot_appear_here"; + DiagnosticCode[DiagnosticCode["Accessors_are_only_available_when_targeting_EcmaScript5_and_higher"] = 59] = "Accessors_are_only_available_when_targeting_EcmaScript5_and_higher"; + DiagnosticCode[DiagnosticCode["Class_name_cannot_be__0_"] = 60] = "Class_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Interface_name_cannot_be__0_"] = 61] = "Interface_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Enum_name_cannot_be__0_"] = 62] = "Enum_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Module_name_cannot_be__0_"] = 63] = "Module_name_cannot_be__0_"; + DiagnosticCode[DiagnosticCode["Enum_member_must_have_initializer"] = 64] = "Enum_member_must_have_initializer"; + DiagnosticCode[DiagnosticCode["_module_______is_deprecated__Use__require_______instead"] = 65] = "_module_______is_deprecated__Use__require_______instead"; + DiagnosticCode[DiagnosticCode["Export_assignments_cannot_be_used_in_internal_modules"] = 66] = "Export_assignments_cannot_be_used_in_internal_modules"; + DiagnosticCode[DiagnosticCode["Export_assignment_not_allowed_in_module_with_exported_element"] = 67] = "Export_assignment_not_allowed_in_module_with_exported_element"; + DiagnosticCode[DiagnosticCode["Module_cannot_have_multiple_export_assignments"] = 68] = "Module_cannot_have_multiple_export_assignments"; + + DiagnosticCode[DiagnosticCode["Duplicate_identifier__0_"] = 69] = "Duplicate_identifier__0_"; + DiagnosticCode[DiagnosticCode["The_name__0__does_not_exist_in_the_current_scope"] = 70] = "The_name__0__does_not_exist_in_the_current_scope"; + DiagnosticCode[DiagnosticCode["The_name__0__does_not_refer_to_a_value"] = 71] = "The_name__0__does_not_refer_to_a_value"; + DiagnosticCode[DiagnosticCode["Keyword__super__can_only_be_used_inside_a_class_instance_method"] = 72] = "Keyword__super__can_only_be_used_inside_a_class_instance_method"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an_assignment_expression_must_be_a_variable__property_or_indexer"] = 73] = "The_left_hand_side_of_an_assignment_expression_must_be_a_variable__property_or_indexer"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_callable__Did_you_mean_to_include__new__"] = 74] = "Value_of_type__0__is_not_callable__Did_you_mean_to_include__new__"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_callable"] = 75] = "Value_of_type__0__is_not_callable"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_newable"] = 76] = "Value_of_type__0__is_not_newable"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_indexable_by_type__1_"] = 77] = "Value_of_type__0__is_not_indexable_by_type__1_"; + DiagnosticCode[DiagnosticCode["Operator__0__cannot_be_applied_to_types__1__and__2_"] = 78] = "Operator__0__cannot_be_applied_to_types__1__and__2_"; + DiagnosticCode[DiagnosticCode["Operator__0__cannot_be_applied_to_types__1__and__2__3"] = 79] = "Operator__0__cannot_be_applied_to_types__1__and__2__3"; + DiagnosticCode[DiagnosticCode["Cannot_convert__0__to__1_"] = 80] = "Cannot_convert__0__to__1_"; + DiagnosticCode[DiagnosticCode["Cannot_convert__0__to__1__NL__2"] = 81] = "Cannot_convert__0__to__1__NL__2"; + DiagnosticCode[DiagnosticCode["Expected_var__class__interface__or_module"] = 82] = "Expected_var__class__interface__or_module"; + DiagnosticCode[DiagnosticCode["Operator__0__cannot_be_applied_to_type__1_"] = 83] = "Operator__0__cannot_be_applied_to_type__1_"; + DiagnosticCode[DiagnosticCode["Getter__0__already_declared"] = 84] = "Getter__0__already_declared"; + DiagnosticCode[DiagnosticCode["Setter__0__already_declared"] = 85] = "Setter__0__already_declared"; + DiagnosticCode[DiagnosticCode["Accessor_cannot_have_type_parameters"] = 86] = "Accessor_cannot_have_type_parameters"; + DiagnosticCode[DiagnosticCode["Exported_class__0__extends_private_class__1_"] = 87] = "Exported_class__0__extends_private_class__1_"; + DiagnosticCode[DiagnosticCode["Exported_class__0__implements_private_interface__1_"] = 88] = "Exported_class__0__implements_private_interface__1_"; + DiagnosticCode[DiagnosticCode["Exported_interface__0__extends_private_interface__1_"] = 89] = "Exported_interface__0__extends_private_interface__1_"; + DiagnosticCode[DiagnosticCode["Exported_class__0__extends_class_from_inaccessible_module__1_"] = 90] = "Exported_class__0__extends_class_from_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Exported_class__0__implements_interface_from_inaccessible_module__1_"] = 91] = "Exported_class__0__implements_interface_from_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Exported_interface__0__extends_interface_from_inaccessible_module__1_"] = 92] = "Exported_interface__0__extends_interface_from_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_"] = 93] = "Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Public_property__0__of__exported_class_has_or_is_using_private_type__1_"] = 94] = "Public_property__0__of__exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Property__0__of__exported_interface_has_or_is_using_private_type__1_"] = 95] = "Property__0__of__exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Exported_variable__0__has_or_is_using_private_type__1_"] = 96] = "Exported_variable__0__has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_"] = 97] = "Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Public_property__0__of__exported_class_is_using_inaccessible_module__1_"] = 98] = "Public_property__0__of__exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Property__0__of__exported_interface_is_using_inaccessible_module__1_"] = 99] = "Property__0__of__exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Exported_variable__0__is_using_inaccessible_module__1_"] = 100] = "Exported_variable__0__is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_"] = 101] = "Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_"] = 102] = "Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_"] = 103] = "Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_"] = 104] = "Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_"] = 105] = "Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_"] = 106] = "Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_"] = 107] = "Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_"] = 108] = "Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_exported_function_has_or_is_using_private_type__1_"] = 109] = "Parameter__0__of_exported_function_has_or_is_using_private_type__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_"] = 110] = "Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_"] = 111] = "Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_"] = 112] = "Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_"] = 113] = "Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_"] = 114] = "Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_"] = 115] = "Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_"] = 116] = "Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_"] = 117] = "Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Parameter__0__of_exported_function_is_using_inaccessible_module__1_"] = 118] = "Parameter__0__of_exported_function_is_using_inaccessible_module__1_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_"] = 119] = "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_"] = 120] = "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_"] = 121] = "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_"] = 122] = "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_"] = 123] = "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_"] = 124] = "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_"] = 125] = "Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_"] = 126] = "Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_exported_function_has_or_is_using_private_type__0_"] = 127] = "Return_type_of_exported_function_has_or_is_using_private_type__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_"] = 128] = "Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_"] = 129] = "Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_"] = 130] = "Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_"] = 131] = "Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_"] = 132] = "Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_"] = 133] = "Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_"] = 134] = "Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_"] = 135] = "Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["Return_type_of_exported_function_is_using_inaccessible_module__0_"] = 136] = "Return_type_of_exported_function_is_using_inaccessible_module__0_"; + DiagnosticCode[DiagnosticCode["_new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead"] = 137] = "_new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead"; + DiagnosticCode[DiagnosticCode["A_parameter_list_must_follow_a_generic_type_argument_list______expected"] = 138] = "A_parameter_list_must_follow_a_generic_type_argument_list______expected"; + DiagnosticCode[DiagnosticCode["Multiple_constructor_implementations_are_not_allowed"] = 139] = "Multiple_constructor_implementations_are_not_allowed"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_external_module__0_"] = 140] = "Unable_to_resolve_external_module__0_"; + DiagnosticCode[DiagnosticCode["Module_cannot_be_aliased_to_a_non_module_type"] = 141] = "Module_cannot_be_aliased_to_a_non_module_type"; + DiagnosticCode[DiagnosticCode["A_class_may_only_extend_another_class"] = 142] = "A_class_may_only_extend_another_class"; + DiagnosticCode[DiagnosticCode["A_class_may_only_implement_another_class_or_interface"] = 143] = "A_class_may_only_implement_another_class_or_interface"; + DiagnosticCode[DiagnosticCode["An_interface_may_only_extend_another_class_or_interface"] = 144] = "An_interface_may_only_extend_another_class_or_interface"; + DiagnosticCode[DiagnosticCode["An_interface_cannot_implement_another_type"] = 145] = "An_interface_cannot_implement_another_type"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_type"] = 146] = "Unable_to_resolve_type"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_type_of__0_"] = 147] = "Unable_to_resolve_type_of__0_"; + DiagnosticCode[DiagnosticCode["Unable_to_resolve_type_parameter_constraint"] = 148] = "Unable_to_resolve_type_parameter_constraint"; + DiagnosticCode[DiagnosticCode["Type_parameter_constraint_cannot_be_a_primitive_type"] = 149] = "Type_parameter_constraint_cannot_be_a_primitive_type"; + DiagnosticCode[DiagnosticCode["Supplied_parameters_do_not_match_any_signature_of_call_target"] = 150] = "Supplied_parameters_do_not_match_any_signature_of_call_target"; + DiagnosticCode[DiagnosticCode["Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0"] = 151] = "Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0"; + DiagnosticCode[DiagnosticCode["Invalid__new__expression"] = 152] = "Invalid__new__expression"; + DiagnosticCode[DiagnosticCode["Call_signatures_used_in_a__new__expression_must_have_a__void__return_type"] = 153] = "Call_signatures_used_in_a__new__expression_must_have_a__void__return_type"; + DiagnosticCode[DiagnosticCode["Could_not_select_overload_for__new__expression"] = 154] = "Could_not_select_overload_for__new__expression"; + DiagnosticCode[DiagnosticCode["Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_"] = 155] = "Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_"; + DiagnosticCode[DiagnosticCode["Could_not_select_overload_for__call__expression"] = 156] = "Could_not_select_overload_for__call__expression"; + DiagnosticCode[DiagnosticCode["Unable_to_invoke_type_with_no_call_signatures"] = 157] = "Unable_to_invoke_type_with_no_call_signatures"; + DiagnosticCode[DiagnosticCode["Calls_to__super__are_only_valid_inside_a_class"] = 158] = "Calls_to__super__are_only_valid_inside_a_class"; + DiagnosticCode[DiagnosticCode["Generic_type__0__requires_1_type_argument_s_"] = 159] = "Generic_type__0__requires_1_type_argument_s_"; + DiagnosticCode[DiagnosticCode["Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_"] = 160] = "Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_"; + DiagnosticCode[DiagnosticCode["Type_of_array_literal_cannot_be_determined__Best_common_type_could_not_be_found_for_array_elements"] = 161] = "Type_of_array_literal_cannot_be_determined__Best_common_type_could_not_be_found_for_array_elements"; + DiagnosticCode[DiagnosticCode["Could_not_find_enclosing_symbol_for_dotted_name__0_"] = 162] = "Could_not_find_enclosing_symbol_for_dotted_name__0_"; + DiagnosticCode[DiagnosticCode["The_property__0__does_not_exist_on_value_of_type__1__"] = 163] = "The_property__0__does_not_exist_on_value_of_type__1__"; + DiagnosticCode[DiagnosticCode["Could_not_find_symbol__0_"] = 164] = "Could_not_find_symbol__0_"; + DiagnosticCode[DiagnosticCode["_get__and__set__accessor_must_have_the_same_type"] = 165] = "_get__and__set__accessor_must_have_the_same_type"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_in_current_location"] = 166] = "_this__cannot_be_referenced_in_current_location"; + DiagnosticCode[DiagnosticCode["Use_of_deprecated__bool__type__Use__boolean__instead"] = 167] = "Use_of_deprecated__bool__type__Use__boolean__instead"; + + DiagnosticCode[DiagnosticCode["Class__0__is_recursively_referenced_as_a_base_type_of_itself"] = 168] = "Class__0__is_recursively_referenced_as_a_base_type_of_itself"; + DiagnosticCode[DiagnosticCode["Interface__0__is_recursively_referenced_as_a_base_type_of_itself"] = 169] = "Interface__0__is_recursively_referenced_as_a_base_type_of_itself"; + DiagnosticCode[DiagnosticCode["_super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class"] = 170] = "_super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class"; + DiagnosticCode[DiagnosticCode["_super__cannot_be_referenced_in_non_derived_classes"] = 171] = "_super__cannot_be_referenced_in_non_derived_classes"; + DiagnosticCode[DiagnosticCode["A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties"] = 172] = "A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties"; + DiagnosticCode[DiagnosticCode["Constructors_for_derived_classes_must_contain_a__super__call"] = 173] = "Constructors_for_derived_classes_must_contain_a__super__call"; + DiagnosticCode[DiagnosticCode["Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors"] = 174] = "Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors"; + DiagnosticCode[DiagnosticCode["_0_1__is_inaccessible"] = 175] = "_0_1__is_inaccessible"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_within_module_bodies"] = 176] = "_this__cannot_be_referenced_within_module_bodies"; + DiagnosticCode[DiagnosticCode["_this__must_only_be_used_inside_a_function_or_script_context"] = 177] = "_this__must_only_be_used_inside_a_function_or_script_context"; + DiagnosticCode[DiagnosticCode["Invalid__addition__expression___types_do_not_agree"] = 178] = "Invalid__addition__expression___types_do_not_agree"; + DiagnosticCode[DiagnosticCode["The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"] = 179] = "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"] = 180] = "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type"; + DiagnosticCode[DiagnosticCode["The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type"] = 181] = "The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type"; + DiagnosticCode[DiagnosticCode["Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation"] = 182] = "Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation"; + DiagnosticCode[DiagnosticCode["Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_"] = 183] = "Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_"; + DiagnosticCode[DiagnosticCode["The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter"] = 184] = "The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_"] = 185] = "The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_"; + DiagnosticCode[DiagnosticCode["The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"] = 186] = "The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"; + DiagnosticCode[DiagnosticCode["The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"] = 187] = "The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter"; + DiagnosticCode[DiagnosticCode["The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type"] = 188] = "The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type"; + DiagnosticCode[DiagnosticCode["Setters_cannot_return_a_value"] = 189] = "Setters_cannot_return_a_value"; + DiagnosticCode[DiagnosticCode["Tried_to_set_variable_type_to_module_type__0__"] = 190] = "Tried_to_set_variable_type_to_module_type__0__"; + DiagnosticCode[DiagnosticCode["Tried_to_set_variable_type_to_uninitialized_module_type__0__"] = 191] = "Tried_to_set_variable_type_to_uninitialized_module_type__0__"; + DiagnosticCode[DiagnosticCode["Function__0__declared_a_non_void_return_type__but_has_no_return_expression"] = 192] = "Function__0__declared_a_non_void_return_type__but_has_no_return_expression"; + DiagnosticCode[DiagnosticCode["Getters_must_return_a_value"] = 193] = "Getters_must_return_a_value"; + DiagnosticCode[DiagnosticCode["Getter_and_setter_accessors_do_not_agree_in_visibility"] = 194] = "Getter_and_setter_accessors_do_not_agree_in_visibility"; + DiagnosticCode[DiagnosticCode["Invalid_left_hand_side_of_assignment_expression"] = 195] = "Invalid_left_hand_side_of_assignment_expression"; + DiagnosticCode[DiagnosticCode["Function_declared_a_non_void_return_type__but_has_no_return_expression"] = 196] = "Function_declared_a_non_void_return_type__but_has_no_return_expression"; + DiagnosticCode[DiagnosticCode["Cannot_resolve_return_type_reference"] = 197] = "Cannot_resolve_return_type_reference"; + DiagnosticCode[DiagnosticCode["Constructors_cannot_have_a_return_type_of__void_"] = 198] = "Constructors_cannot_have_a_return_type_of__void_"; + DiagnosticCode[DiagnosticCode["Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_"] = 199] = "Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_"; + DiagnosticCode[DiagnosticCode["All_symbols_within_a__with__block_will_be_resolved_to__any__"] = 200] = "All_symbols_within_a__with__block_will_be_resolved_to__any__"; + DiagnosticCode[DiagnosticCode["Import_declarations_in_an_internal_module_cannot_reference_an_external_module"] = 201] = "Import_declarations_in_an_internal_module_cannot_reference_an_external_module"; + DiagnosticCode[DiagnosticCode["Class__0__declares_interface__1__but_does_not_implement_it__NL__2"] = 202] = "Class__0__declares_interface__1__but_does_not_implement_it__NL__2"; + DiagnosticCode[DiagnosticCode["Class__0__declares_class__1__but_does_not_implement_it__NL__2"] = 203] = "Class__0__declares_class__1__but_does_not_implement_it__NL__2"; + DiagnosticCode[DiagnosticCode["The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer"] = 204] = "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_in_initializers_in_a_class_body"] = 205] = "_this__cannot_be_referenced_in_initializers_in_a_class_body"; + DiagnosticCode[DiagnosticCode["Class__0__cannot_extend_class__1__NL__2"] = 206] = "Class__0__cannot_extend_class__1__NL__2"; + DiagnosticCode[DiagnosticCode["Interface__0__cannot_extend_class__1__NL__2"] = 207] = "Interface__0__cannot_extend_class__1__NL__2"; + DiagnosticCode[DiagnosticCode["Interface__0__cannot_extend_interface__1__NL__2"] = 208] = "Interface__0__cannot_extend_interface__1__NL__2"; + DiagnosticCode[DiagnosticCode["Duplicate_overload_signature_for__0_"] = 209] = "Duplicate_overload_signature_for__0_"; + DiagnosticCode[DiagnosticCode["Duplicate_constructor_overload_signature"] = 210] = "Duplicate_constructor_overload_signature"; + DiagnosticCode[DiagnosticCode["Duplicate_overload_call_signature"] = 211] = "Duplicate_overload_call_signature"; + DiagnosticCode[DiagnosticCode["Duplicate_overload_construct_signature"] = 212] = "Duplicate_overload_construct_signature"; + DiagnosticCode[DiagnosticCode["Overload_signature_is_not_compatible_with_function_definition"] = 213] = "Overload_signature_is_not_compatible_with_function_definition"; + DiagnosticCode[DiagnosticCode["Overload_signature_is_not_compatible_with_function_definition__NL__0"] = 214] = "Overload_signature_is_not_compatible_with_function_definition__NL__0"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_public_or_private"] = 215] = "Overload_signatures_must_all_be_public_or_private"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_exported_or_local"] = 216] = "Overload_signatures_must_all_be_exported_or_local"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_ambient_or_non_ambient"] = 217] = "Overload_signatures_must_all_be_ambient_or_non_ambient"; + DiagnosticCode[DiagnosticCode["Overload_signatures_must_all_be_optional_or_required"] = 218] = "Overload_signatures_must_all_be_optional_or_required"; + DiagnosticCode[DiagnosticCode["Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature"] = 219] = "Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature"; + DiagnosticCode[DiagnosticCode["_this__cannot_be_referenced_in_constructor_arguments"] = 220] = "_this__cannot_be_referenced_in_constructor_arguments"; + DiagnosticCode[DiagnosticCode["Static_member_cannot_be_accessed_off_an_instance_variable"] = 221] = "Static_member_cannot_be_accessed_off_an_instance_variable"; + DiagnosticCode[DiagnosticCode["Instance_member_cannot_be_accessed_off_a_class"] = 222] = "Instance_member_cannot_be_accessed_off_a_class"; + DiagnosticCode[DiagnosticCode["Untyped_function_calls_may_not_accept_type_arguments"] = 223] = "Untyped_function_calls_may_not_accept_type_arguments"; + DiagnosticCode[DiagnosticCode["Non_generic_functions_may_not_accept_type_arguments"] = 224] = "Non_generic_functions_may_not_accept_type_arguments"; + DiagnosticCode[DiagnosticCode["A_generic_type_may_not_reference_itself_with_its_own_type_parameters"] = 225] = "A_generic_type_may_not_reference_itself_with_its_own_type_parameters"; + DiagnosticCode[DiagnosticCode["Static_methods_cannot_reference_class_type_parameters"] = 226] = "Static_methods_cannot_reference_class_type_parameters"; + DiagnosticCode[DiagnosticCode["Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___"] = 227] = "Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___"; + DiagnosticCode[DiagnosticCode["Rest_parameters_must_be_array_types"] = 228] = "Rest_parameters_must_be_array_types"; + DiagnosticCode[DiagnosticCode["Overload_signature_implementation_cannot_use_specialized_type"] = 229] = "Overload_signature_implementation_cannot_use_specialized_type"; + DiagnosticCode[DiagnosticCode["Export_assignments_may_only_be_used_in_External_modules"] = 230] = "Export_assignments_may_only_be_used_in_External_modules"; + DiagnosticCode[DiagnosticCode["Export_assignments_may_only_be_made_with_acceptable_kinds"] = 231] = "Export_assignments_may_only_be_made_with_acceptable_kinds"; + DiagnosticCode[DiagnosticCode["Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword"] = 232] = "Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword"; + DiagnosticCode[DiagnosticCode["Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__"] = 233] = "Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__"; + DiagnosticCode[DiagnosticCode["Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2"] = 234] = "Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2"; + DiagnosticCode[DiagnosticCode["All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__"] = 235] = "All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__"; + DiagnosticCode[DiagnosticCode["All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1"] = 236] = "All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1"; + DiagnosticCode[DiagnosticCode["All_named_properties_must_be_subtypes_of_string_indexer_type___0__"] = 237] = "All_named_properties_must_be_subtypes_of_string_indexer_type___0__"; + DiagnosticCode[DiagnosticCode["All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1"] = 238] = "All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1"; + DiagnosticCode[DiagnosticCode["Generic_type_references_must_include_all_type_arguments"] = 239] = "Generic_type_references_must_include_all_type_arguments"; + + DiagnosticCode[DiagnosticCode["Type__0__is_missing_property__1__from_type__2_"] = 240] = "Type__0__is_missing_property__1__from_type__2_"; + DiagnosticCode[DiagnosticCode["Types_of_property__0__of_types__1__and__2__are_incompatible"] = 241] = "Types_of_property__0__of_types__1__and__2__are_incompatible"; + DiagnosticCode[DiagnosticCode["Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3"] = 242] = "Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3"; + DiagnosticCode[DiagnosticCode["Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_"] = 243] = "Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_"; + DiagnosticCode[DiagnosticCode["Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_"] = 244] = "Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_"; + DiagnosticCode[DiagnosticCode["Types__0__and__1__define_property__2__as_private"] = 245] = "Types__0__and__1__define_property__2__as_private"; + DiagnosticCode[DiagnosticCode["Call_signatures_of_types__0__and__1__are_incompatible"] = 246] = "Call_signatures_of_types__0__and__1__are_incompatible"; + DiagnosticCode[DiagnosticCode["Call_signatures_of_types__0__and__1__are_incompatible__NL__2"] = 247] = "Call_signatures_of_types__0__and__1__are_incompatible__NL__2"; + DiagnosticCode[DiagnosticCode["Type__0__requires_a_call_signature__but_Type__1__lacks_one"] = 248] = "Type__0__requires_a_call_signature__but_Type__1__lacks_one"; + DiagnosticCode[DiagnosticCode["Construct_signatures_of_types__0__and__1__are_incompatible"] = 249] = "Construct_signatures_of_types__0__and__1__are_incompatible"; + DiagnosticCode[DiagnosticCode["Construct_signatures_of_types__0__and__1__are_incompatible__NL__2"] = 250] = "Construct_signatures_of_types__0__and__1__are_incompatible__NL__2"; + DiagnosticCode[DiagnosticCode["Type__0__requires_a_construct_signature__but_Type__1__lacks_one"] = 251] = "Type__0__requires_a_construct_signature__but_Type__1__lacks_one"; + DiagnosticCode[DiagnosticCode["Index_signatures_of_types__0__and__1__are_incompatible"] = 252] = "Index_signatures_of_types__0__and__1__are_incompatible"; + DiagnosticCode[DiagnosticCode["Index_signatures_of_types__0__and__1__are_incompatible__NL__2"] = 253] = "Index_signatures_of_types__0__and__1__are_incompatible__NL__2"; + DiagnosticCode[DiagnosticCode["Call_signature_expects__0__or_fewer_parameters"] = 254] = "Call_signature_expects__0__or_fewer_parameters"; + DiagnosticCode[DiagnosticCode["Could_not_apply_type__0__to_argument__1__which_is_of_type__2_"] = 255] = "Could_not_apply_type__0__to_argument__1__which_is_of_type__2_"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function"] = 256] = "Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function"] = 257] = "Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor"] = 258] = "Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor"; + DiagnosticCode[DiagnosticCode["Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property"] = 259] = "Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property"; + DiagnosticCode[DiagnosticCode["Types_of_static_property__0__of_class__1__and_class__2__are_incompatible"] = 260] = "Types_of_static_property__0__of_class__1__and_class__2__are_incompatible"; + DiagnosticCode[DiagnosticCode["Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3"] = 261] = "Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3"; + DiagnosticCode[DiagnosticCode["Type_reference_cannot_refer_to_container__0_"] = 262] = "Type_reference_cannot_refer_to_container__0_"; + DiagnosticCode[DiagnosticCode["Type_reference_must_refer_to_type"] = 263] = "Type_reference_must_refer_to_type"; + DiagnosticCode[DiagnosticCode["Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element"] = 264] = "Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element"; + + DiagnosticCode[DiagnosticCode["Current_host_does_not_support__w_atch_option"] = 265] = "Current_host_does_not_support__w_atch_option"; + DiagnosticCode[DiagnosticCode["ECMAScript_target_version__0__not_supported___Using_default__1__code_generation"] = 266] = "ECMAScript_target_version__0__not_supported___Using_default__1__code_generation"; + DiagnosticCode[DiagnosticCode["Module_code_generation__0__not_supported___Using_default__1__code_generation"] = 267] = "Module_code_generation__0__not_supported___Using_default__1__code_generation"; + DiagnosticCode[DiagnosticCode["Could_not_find_file___0_"] = 268] = "Could_not_find_file___0_"; + DiagnosticCode[DiagnosticCode["Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed"] = 269] = "Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed"; + DiagnosticCode[DiagnosticCode["A_file_cannot_have_a_reference_itself"] = 270] = "A_file_cannot_have_a_reference_itself"; + DiagnosticCode[DiagnosticCode["Cannot_resolve_referenced_file___0_"] = 271] = "Cannot_resolve_referenced_file___0_"; + DiagnosticCode[DiagnosticCode["Cannot_resolve_imported_file___0_"] = 272] = "Cannot_resolve_imported_file___0_"; + DiagnosticCode[DiagnosticCode["Cannot_find_the_common_subdirectory_path_for_the_input_files"] = 273] = "Cannot_find_the_common_subdirectory_path_for_the_input_files"; + DiagnosticCode[DiagnosticCode["Cannot_compile_dynamic_modules_when_emitting_into_single_file"] = 274] = "Cannot_compile_dynamic_modules_when_emitting_into_single_file"; + DiagnosticCode[DiagnosticCode["Emit_Error__0"] = 275] = "Emit_Error__0"; + })(TypeScript.DiagnosticCode || (TypeScript.DiagnosticCode = {})); + var DiagnosticCode = TypeScript.DiagnosticCode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticMessages = { + error_TS_0__1: { + category: 3 /* NoPrefix */, + message: "error TS{0}: {1}", + code: 0 + }, + warning_TS_0__1: { + category: 3 /* NoPrefix */, + message: "warning TS{0}: {1}", + code: 1 + }, + _0__NL__1_TB__2: { + category: 3 /* NoPrefix */, + message: "{0}{NL}{{1}TB}{2}", + code: 21 + }, + _0_TB__1: { + category: 3 /* NoPrefix */, + message: "{{0}TB}{1}", + code: 22 + }, + Unrecognized_escape_sequence: { + category: 1 /* Error */, + message: "Unrecognized escape sequence.", + code: 1000 + }, + Unexpected_character_0: { + category: 1 /* Error */, + message: "Unexpected character {0}.", + code: 1001 + }, + Missing_closing_quote_character: { + category: 1 /* Error */, + message: "Missing close quote character.", + code: 1002 + }, + Identifier_expected: { + category: 1 /* Error */, + message: "Identifier expected.", + code: 1003 + }, + _0_keyword_expected: { + category: 1 /* Error */, + message: "'{0}' keyword expected.", + code: 1004 + }, + _0_expected: { + category: 1 /* Error */, + message: "'{0}' expected.", + code: 1005 + }, + Identifier_expected__0__is_a_keyword: { + category: 1 /* Error */, + message: "Identifier expected; '{0}' is a keyword.", + code: 1006 + }, + Automatic_semicolon_insertion_not_allowed: { + category: 1 /* Error */, + message: "Automatic semicolon insertion not allowed.", + code: 1007 + }, + Unexpected_token__0_expected: { + category: 1 /* Error */, + message: "Unexpected token; '{0}' expected.", + code: 1008 + }, + Trailing_separator_not_allowed: { + category: 1 /* Error */, + message: "Trailing separator not allowed.", + code: 1009 + }, + _StarSlash__expected: { + category: 1 /* Error */, + message: "'*/' expected.", + code: 1010 + }, + _public_or_private_modifier_must_precede__static_: { + category: 1 /* Error */, + message: "'public' or 'private' modifier must precede 'static'.", + code: 1011 + }, + Unexpected_token_: { + category: 1 /* Error */, + message: "Unexpected token.", + code: 1012 + }, + A_catch_clause_variable_cannot_have_a_type_annotation: { + category: 1 /* Error */, + message: "A catch clause variable cannot have a type annotation.", + code: 1013 + }, + Rest_parameter_must_be_last_in_list: { + category: 1 /* Error */, + message: "Rest parameter must be last in list.", + code: 1014 + }, + Parameter_cannot_have_question_mark_and_initializer: { + category: 1 /* Error */, + message: "Parameter cannot have question mark and initializer.", + code: 1015 + }, + Required_parameter_cannot_follow_optional_parameter: { + category: 1 /* Error */, + message: "Required parameter cannot follow optional parameter.", + code: 1016 + }, + Index_signatures_cannot_have_rest_parameters: { + category: 1 /* Error */, + message: "Index signatures cannot have rest parameters.", + code: 1017 + }, + Index_signature_parameter_cannot_have_accessibility_modifiers: { + category: 1 /* Error */, + message: "Index signature parameter cannot have accessibility modifiers.", + code: 1018 + }, + Index_signature_parameter_cannot_have_a_question_mark: { + category: 1 /* Error */, + message: "Index signature parameter cannot have a question mark.", + code: 1019 + }, + Index_signature_parameter_cannot_have_an_initializer: { + category: 1 /* Error */, + message: "Index signature parameter cannot have an initializer.", + code: 1020 + }, + Index_signature_must_have_a_type_annotation: { + category: 1 /* Error */, + message: "Index signature must have a type annotation.", + code: 1021 + }, + Index_signature_parameter_must_have_a_type_annotation: { + category: 1 /* Error */, + message: "Index signature parameter must have a type annotation.", + code: 1022 + }, + Index_signature_parameter_type_must_be__string__or__number_: { + category: 1 /* Error */, + message: "Index signature parameter type must be 'string' or 'number'.", + code: 1023 + }, + _extends__clause_already_seen: { + category: 1 /* Error */, + message: "'extends' clause already seen.", + code: 1024 + }, + _extends__clause_must_precede__implements__clause: { + category: 1 /* Error */, + message: "'extends' clause must precede 'implements' clause.", + code: 1025 + }, + Class_can_only_extend_single_type: { + category: 1 /* Error */, + message: "Class can only extend single type.", + code: 1026 + }, + _implements__clause_already_seen: { + category: 1 /* Error */, + message: "'implements' clause already seen.", + code: 1027 + }, + Accessibility_modifier_already_seen: { + category: 1 /* Error */, + message: "Accessibility modifier already seen.", + code: 1028 + }, + _0__modifier_must_precede__1__modifier: { + category: 1 /* Error */, + message: "'{0}' modifier must precede '{1}' modifier.", + code: 1029 + }, + _0__modifier_already_seen: { + category: 1 /* Error */, + message: "'{0}' modifier already seen.", + code: 1030 + }, + _0__modifier_cannot_appear_on_a_class_element: { + category: 1 /* Error */, + message: "'{0}' modifier cannot appear on a class element.", + code: 1031 + }, + Interface_declaration_cannot_have__implements__clause: { + category: 1 /* Error */, + message: "Interface declaration cannot have 'implements' clause.", + code: 1032 + }, + _super__invocation_cannot_have_type_arguments: { + category: 1 /* Error */, + message: "'super' invocation cannot have type arguments.", + code: 1034 + }, + Non_ambient_modules_cannot_use_quoted_names: { + category: 1 /* Error */, + message: "Non ambient modules cannot use quoted names.", + code: 1035 + }, + Statements_are_not_allowed_in_ambient_contexts: { + category: 1 /* Error */, + message: "Statements are not allowed in ambient contexts.", + code: 1036 + }, + Implementations_are_not_allowed_in_ambient_contexts: { + category: 1 /* Error */, + message: "Implementations are not allowed in ambient contexts.", + code: 1037 + }, + _declare__modifier_not_allowed_for_code_already_in_an_ambient_context: { + category: 1 /* Error */, + message: "'declare' modifier not allowed for code already in an ambient context.", + code: 1038 + }, + Initializers_are_not_allowed_in_ambient_contexts: { + category: 1 /* Error */, + message: "Initializers are not allowed in ambient contexts.", + code: 1039 + }, + Overload_and_ambient_signatures_cannot_specify_parameter_properties: { + category: 1 /* Error */, + message: "Overload and ambient signatures cannot specify parameter properties.", + code: 1040 + }, + Function_implementation_expected: { + category: 1 /* Error */, + message: "Function implementation expected.", + code: 1041 + }, + Constructor_implementation_expected: { + category: 1 /* Error */, + message: "Constructor implementation expected.", + code: 1042 + }, + Function_overload_name_must_be__0_: { + category: 1 /* Error */, + message: "Function overload name must be '{0}'.", + code: 1043 + }, + _0__modifier_cannot_appear_on_a_module_element: { + category: 1 /* Error */, + message: "'{0}' modifier cannot appear on a module element.", + code: 1044 + }, + _declare__modifier_cannot_appear_on_an_interface_declaration: { + category: 1 /* Error */, + message: "'declare' modifier cannot appear on an interface declaration.", + code: 1045 + }, + _declare__modifier_required_for_top_level_element: { + category: 1 /* Error */, + message: "'declare' modifier required for top level element.", + code: 1046 + }, + Rest_parameter_cannot_be_optional: { + category: 1 /* Error */, + message: "Rest parameter cannot be optional.", + code: 1047 + }, + Rest_parameter_cannot_have_initializer: { + category: 1 /* Error */, + message: "Rest parameter cannot have initializer.", + code: 1048 + }, + _set__accessor_must_have_only_one_parameter: { + category: 1 /* Error */, + message: "'set' accessor must have one and only one parameter.", + code: 1049 + }, + _set__accessor_parameter_cannot_have_accessibility_modifier: { + category: 1 /* Error */, + message: "'set' accessor parameter cannot have accessibility modifier.", + code: 1050 + }, + _set__accessor_parameter_cannot_be_optional: { + category: 1 /* Error */, + message: "'set' accessor parameter cannot be optional.", + code: 1051 + }, + _set__accessor_parameter_cannot_have_initializer: { + category: 1 /* Error */, + message: "'set' accessor parameter cannot have initializer.", + code: 1052 + }, + _set__accessor_cannot_have_rest_parameter: { + category: 1 /* Error */, + message: "'set' accessor cannot have rest parameter.", + code: 1053 + }, + _get__accessor_cannot_have_parameters: { + category: 1 /* Error */, + message: "'get' accessor cannot have parameters.", + code: 1054 + }, + Modifiers_cannot_appear_here: { + category: 1 /* Error */, + message: "Modifiers cannot appear here.", + code: 1055 + }, + Accessors_are_only_available_when_targeting_EcmaScript5_and_higher: { + category: 1 /* Error */, + message: "Accessors are only when targeting EcmaScript5 and higher.", + code: 1056 + }, + Class_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Class name cannot be '{0}'.", + code: 1057 + }, + Interface_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Interface name cannot be '{0}'.", + code: 1058 + }, + Enum_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Enum name cannot be '{0}'.", + code: 1059 + }, + Module_name_cannot_be__0_: { + category: 1 /* Error */, + message: "Module name cannot be '{0}'.", + code: 1060 + }, + Enum_member_must_have_initializer: { + category: 1 /* Error */, + message: "Enum member must have initializer.", + code: 1061 + }, + _module_______is_deprecated__Use__require_______instead: { + category: 0 /* Warning */, + message: "'module(...)' is deprecated. Use 'require(...)' instead.", + code: 1062 + }, + Export_assignments_cannot_be_used_in_internal_modules: { + category: 1 /* Error */, + message: "Export assignments cannot be used in internal modules.", + code: 1063 + }, + Export_assignment_not_allowed_in_module_with_exported_element: { + category: 1 /* Error */, + message: "Export assignment not allowed in module with exported element.", + code: 1064 + }, + Module_cannot_have_multiple_export_assignments: { + category: 1 /* Error */, + message: "Module cannot have multiple export assignments.", + code: 1065 + }, + Duplicate_identifier__0_: { + category: 1 /* Error */, + message: "Duplicate identifier '{0}'.", + code: 2000 + }, + The_name__0__does_not_exist_in_the_current_scope: { + category: 1 /* Error */, + message: "The name '{0}' does not exist in the current scope.", + code: 2001 + }, + The_name__0__does_not_refer_to_a_value: { + category: 1 /* Error */, + message: "The name '{0}' does not refer to a value.", + code: 2002 + }, + Keyword__super__can_only_be_used_inside_a_class_instance_method: { + category: 1 /* Error */, + message: "Keyword 'super' can only be used inside a class instance method.", + code: 2003 + }, + The_left_hand_side_of_an_assignment_expression_must_be_a_variable__property_or_indexer: { + category: 1 /* Error */, + message: "The left-hand side of an assignment expression must be a variable, property or indexer.", + code: 2004 + }, + Value_of_type__0__is_not_callable__Did_you_mean_to_include__new__: { + category: 1 /* Error */, + message: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + code: 2005 + }, + Value_of_type__0__is_not_callable: { + category: 1 /* Error */, + message: "Value of type '{0}' is not callable.", + code: 2006 + }, + Value_of_type__0__is_not_newable: { + category: 1 /* Error */, + message: "Value of type '{0}' is not newable.", + code: 2007 + }, + Value_of_type__0__is_not_indexable_by_type__1_: { + category: 1 /* Error */, + message: "Value of type '{0}' is not indexable by type '{1}'.", + code: 2008 + }, + Operator__0__cannot_be_applied_to_types__1__and__2_: { + category: 1 /* Error */, + message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + code: 2009 + }, + Operator__0__cannot_be_applied_to_types__1__and__2__3: { + category: 1 /* Error */, + message: "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}", + code: 2010 + }, + Cannot_convert__0__to__1_: { + category: 1 /* Error */, + message: "Cannot convert '{0}' to '{1}'.", + code: 2011 + }, + Cannot_convert__0__to__1__NL__2: { + category: 1 /* Error */, + message: "Cannot convert '{0}' to '{1}':{NL}{2}", + code: 2012 + }, + Expected_var__class__interface__or_module: { + category: 1 /* Error */, + message: "Expected var, class, interface, or module.", + code: 2013 + }, + Operator__0__cannot_be_applied_to_type__1_: { + category: 1 /* Error */, + message: "Operator '{0}' cannot be applied to type '{1}'.", + code: 2014 + }, + Getter__0__already_declared: { + category: 1 /* Error */, + message: "Getter '{0}' already declared.", + code: 2015 + }, + Setter__0__already_declared: { + category: 1 /* Error */, + message: "Setter '{0}' already declared.", + code: 2016 + }, + Accessor_cannot_have_type_parameters: { + category: 1 /* Error */, + message: "Accessors cannot have type parameters.", + code: 2017 + }, + Exported_class__0__extends_private_class__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' extends private class '{1}'.", + code: 2018 + }, + Exported_class__0__implements_private_interface__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' implements private interface '{1}'.", + code: 2019 + }, + Exported_interface__0__extends_private_interface__1_: { + category: 1 /* Error */, + message: "Exported interface '{0}' extends private interface '{1}'.", + code: 2020 + }, + Exported_class__0__extends_class_from_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' extends class from inaccessible module {1}.", + code: 2021 + }, + Exported_class__0__implements_interface_from_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported class '{0}' implements interface from inaccessible module {1}.", + code: 2022 + }, + Exported_interface__0__extends_interface_from_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported interface '{0}' extends interface from inaccessible module {1}.", + code: 2023 + }, + Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Public static property '{0}' of exported class has or is using private type '{1}'.", + code: 2024 + }, + Public_property__0__of__exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Public property '{0}' of exported class has or is using private type '{1}'.", + code: 2025 + }, + Property__0__of__exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Property '{0}' of exported interface has or is using private type '{1}'.", + code: 2026 + }, + Exported_variable__0__has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Exported variable '{0}' has or is using private type '{1}'.", + code: 2027 + }, + Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Public static property '{0}' of exported class is using inaccessible module {1}.", + code: 2028 + }, + Public_property__0__of__exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Public property '{0}' of exported class is using inaccessible module {1}.", + code: 2029 + }, + Property__0__of__exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Property '{0}' of exported interface is using inaccessible module {1}.", + code: 2030 + }, + Exported_variable__0__is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Exported variable '{0}' is using inaccessible module {1}.", + code: 2031 + }, + Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + code: 2032 + }, + Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + code: 2033 + }, + Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + code: 2034 + }, + Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + code: 2035 + }, + Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + code: 2036 + }, + Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + code: 2037 + }, + Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + code: 2038 + }, + Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + code: 2039 + }, + Parameter__0__of_exported_function_has_or_is_using_private_type__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of exported function has or is using private type '{1}'.", + code: 2040 + }, + Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + code: 2041 + }, + Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + code: 2042 + }, + Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + code: 2043 + }, + Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + code: 2044 + }, + Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + code: 2045 + }, + Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + code: 2046 + }, + Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + code: 2047 + }, + Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + code: 2048 + }, + Parameter__0__of_exported_function_is_using_inaccessible_module__1_: { + category: 1 /* Error */, + message: "Parameter '{0}' of exported function is using inaccessible module {1}.", + code: 2049 + }, + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public static property getter from exported class has or is using private type '{0}'.", + code: 2050 + }, + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public property getter from exported class has or is using private type '{0}'.", + code: 2051 + }, + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + code: 2052 + }, + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of call signature from exported interface has or is using private type '{0}'.", + code: 2053 + }, + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of index signature from exported interface has or is using private type '{0}'.", + code: 2054 + }, + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public static method from exported class has or is using private type '{0}'.", + code: 2055 + }, + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of public method from exported class has or is using private type '{0}'.", + code: 2056 + }, + Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of method from exported interface has or is using private type '{0}'.", + code: 2057 + }, + Return_type_of_exported_function_has_or_is_using_private_type__0_: { + category: 1 /* Error */, + message: "Return type of exported function has or is using private type '{0}'.", + code: 2058 + }, + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public static property getter from exported class is using inaccessible module {0}.", + code: 2059 + }, + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public property getter from exported class is using inaccessible module {0}.", + code: 2060 + }, + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + code: 2061 + }, + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of call signature from exported interface is using inaccessible module {0}.", + code: 2062 + }, + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of index signature from exported interface is using inaccessible module {0}.", + code: 2063 + }, + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public static method from exported class is using inaccessible module {0}.", + code: 2064 + }, + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of public method from exported class is using inaccessible module {0}.", + code: 2065 + }, + Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of method from exported interface is using inaccessible module {0}.", + code: 2066 + }, + Return_type_of_exported_function_is_using_inaccessible_module__0_: { + category: 1 /* Error */, + message: "Return type of exported function is using inaccessible module {0}.", + code: 2067 + }, + _new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead: { + category: 1 /* Error */, + message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + code: 2068 + }, + A_parameter_list_must_follow_a_generic_type_argument_list______expected: { + category: 1 /* Error */, + message: "A parameter list must follow a generic type argument list. '(' expected.", + code: 2069 + }, + Multiple_constructor_implementations_are_not_allowed: { + category: 1 /* Error */, + message: "Multiple constructor implementations are not allowed.", + code: 2070 + }, + Unable_to_resolve_external_module__0_: { + category: 1 /* Error */, + message: "Unable to resolve external module '{0}'.", + code: 2071 + }, + Module_cannot_be_aliased_to_a_non_module_type: { + category: 1 /* Error */, + message: "Module cannot be aliased to a non-module type.", + code: 2072 + }, + A_class_may_only_extend_another_class: { + category: 1 /* Error */, + message: "A class may only extend another class.", + code: 2073 + }, + A_class_may_only_implement_another_class_or_interface: { + category: 1 /* Error */, + message: "A class may only implement another class or interface.", + code: 2074 + }, + An_interface_may_only_extend_another_class_or_interface: { + category: 1 /* Error */, + message: "An interface may only extend another class or interface.", + code: 2075 + }, + An_interface_cannot_implement_another_type: { + category: 1 /* Error */, + message: "An interface cannot implement another type.", + code: 2076 + }, + Unable_to_resolve_type: { + category: 1 /* Error */, + message: "Unable to resolve type.", + code: 2077 + }, + Unable_to_resolve_type_of__0_: { + category: 1 /* Error */, + message: "Unable to resolve type of '{0}'.", + code: 2078 + }, + Unable_to_resolve_type_parameter_constraint: { + category: 1 /* Error */, + message: "Unable to resolve type parameter constraint.", + code: 2079 + }, + Type_parameter_constraint_cannot_be_a_primitive_type: { + category: 1 /* Error */, + message: "Type parameter constraint cannot be a primitive type.", + code: 2080 + }, + Supplied_parameters_do_not_match_any_signature_of_call_target: { + category: 1 /* Error */, + message: "Supplied parameters do not match any signature of call target.", + code: 2081 + }, + Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0: { + category: 1 /* Error */, + message: "Supplied parameters do not match any signature of call target:{NL}{0}", + code: 2082 + }, + Invalid__new__expression: { + category: 1 /* Error */, + message: "Invalid 'new' expression.", + code: 2083 + }, + Call_signatures_used_in_a__new__expression_must_have_a__void__return_type: { + category: 1 /* Error */, + message: "Call signatures used in a 'new' expression must have a 'void' return type.", + code: 2084 + }, + Could_not_select_overload_for__new__expression: { + category: 1 /* Error */, + message: "Could not select overload for 'new' expression.", + code: 2085 + }, + Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_: { + category: 1 /* Error */, + message: "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.", + code: 2086 + }, + Could_not_select_overload_for__call__expression: { + category: 1 /* Error */, + message: "Could not select overload for 'call' expression.", + code: 2087 + }, + Unable_to_invoke_type_with_no_call_signatures: { + category: 1 /* Error */, + message: "Unable to invoke type with no call signatures.", + code: 2088 + }, + Calls_to__super__are_only_valid_inside_a_class: { + category: 1 /* Error */, + message: "Calls to 'super' are only valid inside a class.", + code: 2089 + }, + Generic_type__0__requires_1_type_argument_s_: { + category: 1 /* Error */, + message: "Generic type '{0}' requires {1} type argument(s).", + code: 2090 + }, + Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_: { + category: 1 /* Error */, + message: "Type of conditional expression cannot be determined. Best common type could not be found between '{0}' and '{1}'.", + code: 2091 + }, + Type_of_array_literal_cannot_be_determined__Best_common_type_could_not_be_found_for_array_elements: { + category: 1 /* Error */, + message: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + code: 2092 + }, + Could_not_find_enclosing_symbol_for_dotted_name__0_: { + category: 1 /* Error */, + message: "Could not find enclosing symbol for dotted name '{0}'.", + code: 2093 + }, + The_property__0__does_not_exist_on_value_of_type__1__: { + category: 1 /* Error */, + message: "The property '{0}' does not exist on value of type '{1}'.", + code: 2094 + }, + Could_not_find_symbol__0_: { + category: 1 /* Error */, + message: "Could not find symbol '{0}'.", + code: 2095 + }, + _get__and__set__accessor_must_have_the_same_type: { + category: 1 /* Error */, + message: "'get' and 'set' accessor must have the same type.", + code: 2096 + }, + _this__cannot_be_referenced_in_current_location: { + category: 1 /* Error */, + message: "'this' cannot be referenced in current location.", + code: 2097 + }, + Use_of_deprecated__bool__type__Use__boolean__instead: { + category: 0 /* Warning */, + message: "Use of deprecated type 'bool'. Use 'boolean' instead.", + code: 2098 + }, + Static_methods_cannot_reference_class_type_parameters: { + category: 1 /* Error */, + message: "Static methods cannot reference class type parameters.", + code: 2099 + }, + Class__0__is_recursively_referenced_as_a_base_type_of_itself: { + category: 1 /* Error */, + message: "Class '{0}' is recursively referenced as a base type of itself.", + code: 2100 + }, + Interface__0__is_recursively_referenced_as_a_base_type_of_itself: { + category: 1 /* Error */, + message: "Interface '{0}' is recursively referenced as a base type of itself.", + code: 2101 + }, + _super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class: { + category: 1 /* Error */, + message: "'super' property access is permitted only in a constructor, instance member function, or instance member accessor of a derived class.", + code: 2102 + }, + _super__cannot_be_referenced_in_non_derived_classes: { + category: 1 /* Error */, + message: "'super' cannot be referenced in non-derived classes.", + code: 2103 + }, + A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties: { + category: 1 /* Error */, + message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + code: 2104 + }, + Constructors_for_derived_classes_must_contain_a__super__call: { + category: 1 /* Error */, + message: "Constructors for derived classes must contain a 'super' call.", + code: 2105 + }, + Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors: { + category: 1 /* Error */, + message: "Super calls are not permitted outside constructors or in local functions inside constructors.", + code: 2106 + }, + _0_1__is_inaccessible: { + category: 1 /* Error */, + message: "'{0}.{1}' is inaccessible.", + code: 2107 + }, + _this__cannot_be_referenced_within_module_bodies: { + category: 1 /* Error */, + message: "'this' cannot be referenced within module bodies.", + code: 2108 + }, + _this__must_only_be_used_inside_a_function_or_script_context: { + category: 1 /* Error */, + message: "'this' must only be used inside a function or script context.", + code: 2109 + }, + Invalid__addition__expression___types_do_not_agree: { + category: 1 /* Error */, + message: "Invalid '+' expression - types not known to support the addition operator.", + code: 2111 + }, + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type: { + category: 1 /* Error */, + message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + code: 2112 + }, + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type: { + category: 1 /* Error */, + message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + code: 2113 + }, + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type: { + category: 1 /* Error */, + message: "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.", + code: 2114 + }, + Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation: { + category: 1 /* Error */, + message: "Variable declarations for for/in expressions cannot contain a type annotation.", + code: 2115 + }, + Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_: { + category: 1 /* Error */, + message: "Variable declarations for for/in expressions must be of types 'string' or 'any'.", + code: 2116 + }, + The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter: { + category: 1 /* Error */, + message: "The right operand of a for/in expression must be of type 'any', an object type or a type parameter.", + code: 2117 + }, + The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_: { + category: 1 /* Error */, + message: "The left-hand side of an 'in' expression must be of types 'string' or 'any'.", + code: 2118 + }, + The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter: { + category: 1 /* Error */, + message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + code: 2119 + }, + The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter: { + category: 1 /* Error */, + message: "The left-hand side of an 'instanceOf' expression must be of type 'any', an object type or a type parameter.", + code: 2120 + }, + The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type: { + category: 1 /* Error */, + message: "The right-hand side of an 'instanceOf' expression must be of type 'any' or a subtype of the 'Function' interface type.", + code: 2121 + }, + Setters_cannot_return_a_value: { + category: 1 /* Error */, + message: "Setters cannot return a value.", + code: 2122 + }, + Tried_to_set_variable_type_to_module_type__0__: { + category: 1 /* Error */, + message: "Tried to set variable type to container type '{0}'.", + code: 2123 + }, + Tried_to_set_variable_type_to_uninitialized_module_type__0__: { + category: 1 /* Error */, + message: "Tried to set variable type to uninitialized module type '{0}'.", + code: 2124 + }, + Function__0__declared_a_non_void_return_type__but_has_no_return_expression: { + category: 1 /* Error */, + message: "Function {0} declared a non-void return type, but has no return expression.", + code: 2125 + }, + Getters_must_return_a_value: { + category: 1 /* Error */, + message: "Getters must return a value.", + code: 2126 + }, + Getter_and_setter_accessors_do_not_agree_in_visibility: { + category: 1 /* Error */, + message: "Getter and setter accessors do not agree in visibility.", + code: 2127 + }, + Invalid_left_hand_side_of_assignment_expression: { + category: 1 /* Error */, + message: "Invalid left-hand side of assignment expression.", + code: 2130 + }, + Function_declared_a_non_void_return_type__but_has_no_return_expression: { + category: 1 /* Error */, + message: "Function declared a non-void return type, but has no return expression.", + code: 2131 + }, + Cannot_resolve_return_type_reference: { + category: 1 /* Error */, + message: "Cannot resolve return type reference.", + code: 2132 + }, + Constructors_cannot_have_a_return_type_of__void_: { + category: 1 /* Error */, + message: "Constructors cannot have a return type of 'void'.", + code: 2133 + }, + Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_: { + category: 1 /* Error */, + message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'", + code: 2134 + }, + All_symbols_within_a__with__block_will_be_resolved_to__any__: { + category: 1 /* Error */, + message: "All symbols within a with block will be resolved to 'any'.", + code: 2135 + }, + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { + category: 1 /* Error */, + message: "Import declarations in an internal module cannot reference an external module.", + code: 2136 + }, + Class__0__declares_interface__1__but_does_not_implement_it__NL__2: { + category: 1 /* Error */, + message: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + code: 2137 + }, + Class__0__declares_class__1__but_does_not_implement_it__NL__2: { + category: 1 /* Error */, + message: "Class {0} declares class {1} as an implemented interface but does not implement it:{NL}{2}", + code: 2138 + }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer: { + category: 1 /* Error */, + message: "The operand of an increment or decrement operator must be a variable, property or indexer.", + code: 2139 + }, + _this__cannot_be_referenced_in_initializers_in_a_class_body: { + category: 1 /* Error */, + message: "'this' cannot be referenced in initializers in a class body.", + code: 2140 + }, + Class__0__cannot_extend_class__1__NL__2: { + category: 1 /* Error */, + message: "Class '{0}' cannot extend class '{1}':{NL}{2}", + code: 2141 + }, + Interface__0__cannot_extend_class__1__NL__2: { + category: 1 /* Error */, + message: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + code: 2142 + }, + Interface__0__cannot_extend_interface__1__NL__2: { + category: 1 /* Error */, + message: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + code: 2143 + }, + Duplicate_overload_signature_for__0_: { + category: 1 /* Error */, + message: "Duplicate overload signature for '{0}'.", + code: 2144 + }, + Duplicate_constructor_overload_signature: { + category: 1 /* Error */, + message: "Duplicate constructor overload signature.", + code: 2145 + }, + Duplicate_overload_call_signature: { + category: 1 /* Error */, + message: "Duplicate overload call signature.", + code: 2146 + }, + Duplicate_overload_construct_signature: { + category: 1 /* Error */, + message: "Duplicate overload construct signature.", + code: 2147 + }, + Overload_signature_is_not_compatible_with_function_definition: { + category: 1 /* Error */, + message: "Overload signature is not compatible with function definition.", + code: 2148 + }, + Overload_signature_is_not_compatible_with_function_definition__NL__0: { + category: 1 /* Error */, + message: "Overload signature is not compatible with function definition:{NL}{0}", + code: 2149 + }, + Overload_signatures_must_all_be_public_or_private: { + category: 1 /* Error */, + message: "Overload signatures must all be public or private.", + code: 2150 + }, + Overload_signatures_must_all_be_exported_or_local: { + category: 1 /* Error */, + message: "Overload signatures must all be exported or local.", + code: 2151 + }, + Overload_signatures_must_all_be_ambient_or_non_ambient: { + category: 1 /* Error */, + message: "Overload signatures must all be ambient or non-ambient.", + code: 2152 + }, + Overload_signatures_must_all_be_optional_or_required: { + category: 1 /* Error */, + message: "Overload signatures must all be optional or required.", + code: 2153 + }, + Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature: { + category: 1 /* Error */, + message: "Specialized overload signature is not subtype of any non-specialized signature.", + code: 2154 + }, + _this__cannot_be_referenced_in_constructor_arguments: { + category: 1 /* Error */, + message: "'this' cannot be referenced in constructor arguments.", + code: 2155 + }, + Static_member_cannot_be_accessed_off_an_instance_variable: { + category: 1 /* Error */, + message: "Static member cannot be accessed off an instance variable.", + code: 2156 + }, + Instance_member_cannot_be_accessed_off_a_class: { + category: 1 /* Error */, + message: "Instance member cannot be accessed off a class.", + code: 2157 + }, + Untyped_function_calls_may_not_accept_type_arguments: { + category: 1 /* Error */, + message: "Untyped function calls may not accept type arguments.", + code: 2158 + }, + Non_generic_functions_may_not_accept_type_arguments: { + category: 1 /* Error */, + message: "Non-generic functions may not accept type arguments.", + code: 2159 + }, + A_generic_type_may_not_reference_itself_with_its_own_type_parameters: { + category: 1 /* Error */, + message: "A generic type may not reference itself with a wrapped form of its own type parameters.", + code: 2160 + }, + Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___: { + category: 1 /* Error */, + message: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + code: 2161 + }, + Rest_parameters_must_be_array_types: { + category: 1 /* Error */, + message: "Rest parameters must be array types.", + code: 2162 + }, + Overload_signature_implementation_cannot_use_specialized_type: { + category: 1 /* Error */, + message: "Overload signature implementation cannot use specialized type.", + code: 2163 + }, + Export_assignments_may_only_be_used_in_External_modules: { + category: 1 /* Error */, + message: "Export assignments may only be used at the top-level of external modules", + code: 2164 + }, + Export_assignments_may_only_be_made_with_acceptable_kinds: { + category: 1 /* Error */, + message: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules", + code: 2165 + }, + Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword: { + category: 1 /* Error */, + message: "Only public instance methods of the base class are accessible via the super keyword", + code: 2166 + }, + Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__: { + category: 1 /* Error */, + message: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}'", + code: 2167 + }, + Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2: { + category: 1 /* Error */, + message: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}':{NL}{2}", + code: 2168 + }, + All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__: { + category: 1 /* Error */, + message: "All numerically named properties must be subtypes of numeric indexer type '{0}'", + code: 2169 + }, + All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1: { + category: 1 /* Error */, + message: "All numerically named properties must be subtypes of numeric indexer type '{0}':{NL}{1}", + code: 2170 + }, + All_named_properties_must_be_subtypes_of_string_indexer_type___0__: { + category: 1 /* Error */, + message: "All named properties must be subtypes of string indexer type '{0}'", + code: 2171 + }, + All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1: { + category: 1 /* Error */, + message: "All named properties must be subtypes of string indexer type '{0}':{NL}{1}", + code: 2172 + }, + Generic_type_references_must_include_all_type_arguments: { + category: 1 /* Error */, + message: "Generic type references must include all type arguments", + code: 2173 + }, + Type__0__is_missing_property__1__from_type__2_: { + category: 3 /* NoPrefix */, + message: "Type '{0}' is missing property '{1}' from type '{2}'.", + code: 4000 + }, + Types_of_property__0__of_types__1__and__2__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + code: 4001 + }, + Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3: { + category: 3 /* NoPrefix */, + message: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + code: 4002 + }, + Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_: { + category: 3 /* NoPrefix */, + message: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + code: 4003 + }, + Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_: { + category: 3 /* NoPrefix */, + message: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + code: 4004 + }, + Types__0__and__1__define_property__2__as_private: { + category: 3 /* NoPrefix */, + message: "Types '{0}' and '{1}' define property '{2}' as private.", + code: 4005 + }, + Call_signatures_of_types__0__and__1__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Call signatures of types '{0}' and '{1}' are incompatible.", + code: 4006 + }, + Call_signatures_of_types__0__and__1__are_incompatible__NL__2: { + category: 3 /* NoPrefix */, + message: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + code: 4007 + }, + Type__0__requires_a_call_signature__but_Type__1__lacks_one: { + category: 3 /* NoPrefix */, + message: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + code: 4008 + }, + Construct_signatures_of_types__0__and__1__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Construct signatures of types '{0}' and '{1}' are incompatible.", + code: 4009 + }, + Construct_signatures_of_types__0__and__1__are_incompatible__NL__2: { + category: 3 /* NoPrefix */, + message: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + code: 40010 + }, + Type__0__requires_a_construct_signature__but_Type__1__lacks_one: { + category: 3 /* NoPrefix */, + message: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + code: 4011 + }, + Index_signatures_of_types__0__and__1__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Index signatures of types '{0}' and '{1}' are incompatible.", + code: 4012 + }, + Index_signatures_of_types__0__and__1__are_incompatible__NL__2: { + category: 3 /* NoPrefix */, + message: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + code: 4013 + }, + Call_signature_expects__0__or_fewer_parameters: { + category: 3 /* NoPrefix */, + message: "Call signature expects {0} or fewer parameters.", + code: 4014 + }, + Could_not_apply_type__0__to_argument__1__which_is_of_type__2_: { + category: 3 /* NoPrefix */, + message: "Could not apply type'{0}' to argument {1} which is of type '{2}'.", + code: 4015 + }, + Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + code: 4016 + }, + Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + code: 4017 + }, + Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + code: 4018 + }, + Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property: { + category: 3 /* NoPrefix */, + message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + code: 4019 + }, + Types_of_static_property__0__of_class__1__and_class__2__are_incompatible: { + category: 3 /* NoPrefix */, + message: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + code: 4020 + }, + Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3: { + category: 3 /* NoPrefix */, + message: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + code: 4021 + }, + Type_reference_cannot_refer_to_container__0_: { + category: 1 /* Error */, + message: "Type reference cannot refer to container '{0}'.", + code: 4022 + }, + Type_reference_must_refer_to_type: { + category: 1 /* Error */, + message: "Type reference cannot must refer to type.", + code: 4023 + }, + Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element: { + category: 1 /* Error */, + message: "Enums with multiple declarations must provide an initializer for the first enum element.", + code: 4024 + }, + Current_host_does_not_support__w_atch_option: { + category: 1 /* Error */, + message: "Current host does not support -w[atch] option.", + code: 5001 + }, + ECMAScript_target_version__0__not_supported___Using_default__1__code_generation: { + category: 0 /* Warning */, + message: "ECMAScript target version '{0}' not supported. Using default '{1}' code generation.", + code: 5002 + }, + Module_code_generation__0__not_supported___Using_default__1__code_generation: { + category: 0 /* Warning */, + message: "Module code generation '{0}' not supported. Using default '{1}' code generation.", + code: 5003 + }, + Could_not_find_file___0_: { + category: 1 /* Error */, + message: "Could not find file: '{0}'.", + code: 5004 + }, + Unknown_extension_for_file___0__Only__ts_and_d_ts_extensions_are_allowed: { + category: 1 /* Error */, + message: "Unknown extension for file: '{0}'. Only .ts and .d.ts extensions are allowed.", + code: 5005 + }, + A_file_cannot_have_a_reference_itself: { + category: 1 /* Error */, + message: "A file cannot have a reference itself.", + code: 5006 + }, + Cannot_resolve_referenced_file___0_: { + category: 1 /* Error */, + message: "Cannot resolve referenced file: '{0}'.", + code: 5007 + }, + Cannot_resolve_imported_file___0_: { + category: 1 /* Error */, + message: "Cannot resolve imported file: '{0}'.", + code: 5008 + }, + Cannot_find_the_common_subdirectory_path_for_the_input_files: { + category: 1 /* Error */, + message: "Cannot find the common subdirectory path for the input files", + code: 5009 + }, + Cannot_compile_dynamic_modules_when_emitting_into_single_file: { + category: 1 /* Error */, + message: "Cannot compile dynamic modules when emitting into single file", + code: 5010 + }, + Emit_Error__0: { + category: 1 /* Error */, + message: "Emit Error: {0}.", + code: 5011 + } + }; + + var seenCodes = []; + for (var name in TypeScript.diagnosticMessages) { + if (TypeScript.diagnosticMessages.hasOwnProperty(name)) { + var diagnosticMessage = TypeScript.diagnosticMessages[name]; + var value = seenCodes[diagnosticMessage.code]; + if (value) { + throw new Error("Duplicate diagnostic code: " + diagnosticMessage.code); + } + + seenCodes[diagnosticMessage.code] = diagnosticMessage; + } + } +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + "." + (message ? (" " + message) : "")); + }; + + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument + "."); + }; + + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument + "."); + }; + + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + + Errors.invalidOperation = function (message) { + return new Error(message ? ("Invalid operation: " + message) : "Invalid operation."); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + + for (var i = start; i < end; i++) { + hashCode = (hashCode ^ text[i]) * Hash.FNV_PRIME; + } + + return hashCode; + }; + + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + + hash = (((hash << 5) + hash) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + + var start = 0; + var len = key.length; + + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + + hash = (((hash << 5) + hash) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeMurmur2CharArrayHashCode = function (key, start, len) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = len; + var h = (0 ^ numberOfCharsLeft); + + var index = start; + while (numberOfCharsLeft >= 2) { + var c1 = key[index]; + var c2 = key[index + 1]; + + var k = c1 | (c2 << 16); + + k *= m; + k ^= k >> r; + k *= m; + + h *= m; + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key[index]; + h *= m; + } + + h ^= h >> 13; + h *= m; + h ^= h >> 15; + + return h; + }; + + Hash.computeMurmur2StringHashCode = function (key) { + var m = 0x5bd1e995; + var r = 24; + + var start = 0; + var len = key.length; + var numberOfCharsLeft = len; + + var h = (0 ^ numberOfCharsLeft); + + var index = start; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + + var k = c1 | (c2 << 16); + + k *= m; + k ^= k >> r; + k *= m; + + h *= m; + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h *= m; + } + + h ^= h >> 13; + h *= m; + h ^= h >> 15; + + return h; + }; + + Hash.getPrime = function (min) { + for (var i = 0; i < Hash.primes.length; i++) { + var num = Hash.primes[i]; + if (num >= min) { + return num; + } + } + + throw TypeScript.Errors.notYetImplemented(); + }; + + Hash.expandPrime = function (oldSize) { + var num = oldSize << 1; + if (num > 2146435069 && 2146435069 > oldSize) { + return 2146435069; + } + return Hash.getPrime(num); + }; + + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + + Hash.primes = [ + 3, + 7, + 11, + 17, + 23, + 29, + 37, + 47, + 59, + 71, + 89, + 107, + 131, + 163, + 197, + 239, + 293, + 353, + 431, + 521, + 631, + 761, + 919, + 1103, + 1327, + 1597, + 1931, + 2333, + 2801, + 3371, + 4049, + 4861, + 5839, + 7013, + 8419, + 10103, + 12143, + 14591, + 17519, + 21023, + 25229, + 30293, + 36353, + 43627, + 52361, + 62851, + 75431, + 90523, + 108631, + 130363, + 156437, + 187751, + 225307, + 270371, + 324449, + 389357, + 467237, + 560689, + 672827, + 807403, + 968897, + 1162687, + 1395263, + 1674319, + 2009191, + 2411033, + 2893249, + 3471899, + 4166287, + 4999559, + 5999471, + 7199369 + ]; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultHashTableCapacity = 256; + + var HashTableEntry = (function () { + function HashTableEntry(Key, Value, HashCode, Next) { + this.Key = Key; + this.Value = Value; + this.HashCode = HashCode; + this.Next = Next; + } + return HashTableEntry; + })(); + + var HashTable = (function () { + function HashTable(capacity, hash, equals) { + this.hash = hash; + this.equals = equals; + this.entries = []; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.hash = hash; + this.equals = equals; + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + HashTable.prototype.set = function (key, value) { + this.addOrSet(key, value, false); + }; + + HashTable.prototype.add = function (key, value) { + this.addOrSet(key, value, true); + }; + + HashTable.prototype.containsKey = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + return entry !== null; + }; + + HashTable.prototype.get = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + + return entry === null ? null : entry.Value; + }; + + HashTable.prototype.computeHashCode = function (key) { + var hashCode = this.hash === null ? key.hashCode() : this.hash(key); + + hashCode = hashCode & 0x7FFFFFFF; + TypeScript.Debug.assert(hashCode > 0); + + return hashCode; + }; + + HashTable.prototype.addOrSet = function (key, value, throwOnExistingEntry) { + var hashCode = this.computeHashCode(key); + + var entry = this.findEntry(key, hashCode); + if (entry !== null) { + if (throwOnExistingEntry) { + throw TypeScript.Errors.argument('key', 'Key was already in table.'); + } + + entry.Key = key; + entry.Value = value; + return; + } + + return this.addEntry(key, value, hashCode); + }; + + HashTable.prototype.findEntry = function (key, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode) { + var equals = this.equals === null ? key === e.Key : this.equals(key, e.Key); + + if (equals) { + return e; + } + } + } + + return null; + }; + + HashTable.prototype.addEntry = function (key, value, hashCode) { + var index = hashCode % this.entries.length; + + var e = new HashTableEntry(key, value, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Key; + }; + + HashTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + return HashTable; + })(); + Collections.HashTable = HashTable; + + function createHashTable(capacity, hash, equals) { + if (typeof capacity === "undefined") { capacity = Collections.DefaultHashTableCapacity; } + if (typeof hash === "undefined") { hash = null; } + if (typeof equals === "undefined") { equals = null; } + return new HashTable(capacity, hash, equals); + } + Collections.createHashTable = createHashTable; + + var currentHashCode = 1; + function identityHashCode(value) { + if (value.__hash === undefined) { + value.__hash = currentHashCode; + currentHashCode++; + } + + return value.__hash; + } + Collections.identityHashCode = identityHashCode; + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Diagnostic = (function () { + function Diagnostic(fileName, start, length, diagnosticCode, arguments) { + if (typeof arguments === "undefined") { arguments = null; } + this._diagnosticCode = diagnosticCode; + this._arguments = (arguments && arguments.length > 0) ? arguments : null; + this._fileName = fileName; + this._originalStart = this._start = start; + this._length = length; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + + result.diagnosticCode = TypeScript.DiagnosticCode[this.diagnosticCode()]; + + var arguments = (this).arguments(); + if (arguments && arguments.length > 0) { + result.arguments = arguments; + } + + return result; + }; + + Diagnostic.prototype.fileName = function () { + return this._fileName; + }; + + Diagnostic.prototype.start = function () { + return this._start; + }; + + Diagnostic.prototype.length = function () { + return this._length; + }; + + Diagnostic.prototype.diagnosticCode = function () { + return this._diagnosticCode; + }; + + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + + Diagnostic.prototype.text = function () { + return TypeScript.getDiagnosticText(this._diagnosticCode, this._arguments); + }; + + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticCode, this._arguments); + }; + + Diagnostic.prototype.adjustOffset = function (pos) { + this._start = this._originalStart + pos; + }; + + Diagnostic.prototype.additionalLocations = function () { + return []; + }; + + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return diagnostic1._fileName === diagnostic2._fileName && diagnostic1._start === diagnostic2._start && diagnostic1._length === diagnostic2._length && diagnostic1._diagnosticCode === diagnostic2._diagnosticCode && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return v1 === v2; + }); + }; + return Diagnostic; + })(); + TypeScript.Diagnostic = Diagnostic; + + function getLargestIndex(diagnostic) { + var largest = -1; + var stringComponents = diagnostic.split("_"); + + for (var i = 0; i < stringComponents.length; i++) { + var val = parseInt(stringComponents[i]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + + return largest; + } + + function getDiagnosticInfoFromCode(diagnosticCode) { + var diagnosticName = TypeScript.DiagnosticCode[diagnosticCode]; + return TypeScript.diagnosticMessages[diagnosticName]; + } + TypeScript.getDiagnosticInfoFromCode = getDiagnosticInfoFromCode; + + function getDiagnosticText(diagnosticCode, args) { + var diagnosticName = TypeScript.DiagnosticCode[diagnosticCode]; + + var diagnostic = TypeScript.diagnosticMessages[diagnosticName]; + + var actualCount = args ? args.length : 0; + if (!diagnostic) { + throw new Error("Invalid diagnostic"); + } else { + var expectedCount = 1 + getLargestIndex(diagnosticName); + + if (expectedCount !== actualCount) { + throw new Error("Expected " + expectedCount + " arguments to diagnostic, got " + actualCount + " instead"); + } + } + + var diagnosticMessageText = diagnostic.message.replace(/{({(\d+)})?TB}/g, function (match, p1, num) { + var tabChar = "\t"; + var result = tabChar; + if (num && args[num]) { + for (var i = 1; i < args[num]; i++) { + result += tabChar; + } + } + + return result; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return "\r\n"; + }); + + return diagnosticMessageText; + } + TypeScript.getDiagnosticText = getDiagnosticText; + + function getDiagnosticMessage(diagnosticCode, args) { + var diagnostic = getDiagnosticInfoFromCode(diagnosticCode); + var diagnosticMessageText = getDiagnosticText(diagnosticCode, args); + + var message; + if (diagnostic.category === 1 /* Error */) { + message = getDiagnosticText(0 /* error_TS_0__1 */, [diagnostic.code, diagnosticMessageText]); + } else if (diagnostic.category === 0 /* Warning */) { + message = getDiagnosticText(1 /* warning_TS_0__1 */, [diagnostic.code, diagnosticMessageText]); + } else { + message = diagnosticMessageText; + } + + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var ByteOrderMark; +(function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; +})(ByteOrderMark || (ByteOrderMark = {})); + +var FileInformation = (function () { + function FileInformation(contents, byteOrderMark) { + this._contents = contents; + this._byteOrderMark = byteOrderMark; + } + FileInformation.prototype.contents = function () { + return this._contents; + }; + + FileInformation.prototype.byteOrderMark = function () { + return this._byteOrderMark; + }; + return FileInformation; +})(); + +var Environment = (function () { + function getWindowsScriptHostEnvironment() { + try { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + } catch (e) { + return null; + } + + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + currentDirectory: function () { + return (WScript).CreateObject("WScript.Shell").CurrentDirectory; + }, + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + + streamObj.Charset = 'x-ansi'; + + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + + streamObj.Position = 0; + + var byteOrderMark = 0 /* None */; + + if (bomChar.charCodeAt(0) === 0xFE && bomChar.charCodeAt(1) === 0xFF) { + streamObj.Charset = 'unicode'; + byteOrderMark = 2 /* Utf16BigEndian */; + } else if (bomChar.charCodeAt(0) === 0xFF && bomChar.charCodeAt(1) === 0xFE) { + streamObj.Charset = 'unicode'; + byteOrderMark = 3 /* Utf16LittleEndian */; + } else if (bomChar.charCodeAt(0) === 0xEF && bomChar.charCodeAt(1) === 0xBB) { + streamObj.Charset = 'utf-8'; + byteOrderMark = 1 /* Utf8 */; + } else { + streamObj.Charset = 'utf-8'; + } + + var contents = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return new FileInformation(contents, byteOrderMark); + } catch (err) { + throw new Error("Error reading file \"" + path + "\": " + err.message); + } + }, + writeFile: function (path, contents, writeByteOrderMark) { + var textStream = getStreamObject(); + textStream.Charset = 'utf-8'; + textStream.Open(); + textStream.WriteText(contents, 0); + + if (!writeByteOrderMark) { + textStream.Position = 3; + } else { + textStream.Position = 0; + } + + var fileStream = getStreamObject(); + fileStream.Type = 1; + fileStream.Open(); + + textStream.CopyTo(fileStream); + + fileStream.Flush(); + fileStream.SaveToFile(path, 2); + fileStream.Close(); + + textStream.Flush(); + textStream.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + deleteFile: function (path) { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + listFiles: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "\\" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "\\" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + arguments: args, + standardOut: WScript.StdOut + }; + } + ; + + function getNodeEnvironment() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + currentDirectory: function () { + return (process).cwd(); + }, + readFile: function (file) { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] === 0xFF) { + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return new FileInformation(buffer.toString("ucs2", 2), 2 /* Utf16BigEndian */); + } + break; + case 0xFF: + if (buffer[1] === 0xFE) { + return new FileInformation(buffer.toString("ucs2", 2), 3 /* Utf16LittleEndian */); + } + break; + case 0xEF: + if (buffer[1] === 0xBB) { + return new FileInformation(buffer.toString("utf8", 3), 1 /* Utf8 */); + } + } + + return new FileInformation(buffer.toString("utf8", 0), 0 /* None */); + }, + writeFile: function (path, contents, writeByteOrderMark) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + throw "\"" + path + "\" exists but isn't a directory."; + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + mkdirRecursiveSync(_path.dirname(path)); + + if (writeByteOrderMark) { + contents = '\uFEFF' + contents; + } + _fs.writeFileSync(path, contents, "utf8"); + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + listFiles: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder) { + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "\\" + files[i]); + if (options.recursive && stat.isDirectory()) { + paths = paths.concat(filesInFolder(folder + "\\" + files[i])); + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "\\" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path); + }, + arguments: process.argv.slice(2), + standardOut: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWindowsScriptHostEnvironment(); + } else if (typeof module !== 'undefined' && module.exports) { + return getNodeEnvironment(); + } else { + return null; + } +})(); +var TypeScript; +(function (TypeScript) { + var IntegerUtilities = (function () { + function IntegerUtilities() { + } + IntegerUtilities.integerDivide = function (numerator, denominator) { + return (numerator / denominator) >> 0; + }; + + IntegerUtilities.integerMultiplyLow32Bits = function (n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + }; + + IntegerUtilities.integerMultiplyHigh32Bits = function (n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultHigh32 = n1High16 * n2High16 + ((((n1Low16 * n2Low16) >>> 17) + n1Low16 * n2High16) >>> 15); + return resultHigh32; + }; + return IntegerUtilities; + })(); + TypeScript.IntegerUtilities = IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MathPrototype = (function () { + function MathPrototype() { + } + MathPrototype.max = function (a, b) { + return a >= b ? a : b; + }; + + MathPrototype.min = function (a, b) { + return a <= b ? a : b; + }; + return MathPrototype; + })(); + TypeScript.MathPrototype = MathPrototype; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultStringTableCapacity = 256; + + var StringTableEntry = (function () { + function StringTableEntry(Text, HashCode, Next) { + this.Text = Text; + this.HashCode = HashCode; + this.Next = Next; + } + return StringTableEntry; + })(); + + var StringTable = (function () { + function StringTable(capacity) { + this.entries = []; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + StringTable.prototype.addCharArray = function (key, start, len) { + var hashCode = TypeScript.Hash.computeSimple31BitCharArrayHashCode(key, start, len) & 0x7FFFFFFF; + + var entry = this.findCharArrayEntry(key, start, len, hashCode); + if (entry !== null) { + return entry.Text; + } + + var slice = key.slice(start, start + len); + return this.addEntry(TypeScript.StringUtilities.fromCharCodeArray(slice), hashCode); + }; + + StringTable.prototype.findCharArrayEntry = function (key, start, len, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && StringTable.textCharArrayEquals(e.Text, key, start, len)) { + return e; + } + } + + return null; + }; + + StringTable.prototype.addEntry = function (text, hashCode) { + var index = hashCode % this.entries.length; + + var e = new StringTableEntry(text, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Text; + }; + + StringTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + + StringTable.textCharArrayEquals = function (text, array, start, length) { + if (text.length !== length) { + return false; + } + + var s = start; + for (var i = 0; i < length; i++) { + if (text.charCodeAt(i) !== array[s]) { + return false; + } + + s++; + } + + return true; + }; + return StringTable; + })(); + Collections.StringTable = StringTable; + + Collections.DefaultStringTable = new StringTable(Collections.DefaultStringTableCapacity); + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + + StringUtilities.fromCharCodeArray = function (array) { + return String.fromCharCode.apply(null, array); + }; + + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + + StringUtilities.copyTo = function (source, sourceIndex, destination, destinationIndex, count) { + for (var i = 0; i < count; i++) { + destination[destinationIndex + i] = source.charCodeAt(sourceIndex + i); + } + }; + + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + + StringUtilities.stringEquals = function (val1, val2) { + return val1 === val2; + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var global = Function("return this").call(null); + +var TypeScript; +(function (TypeScript) { + var Clock; + (function (Clock) { + Clock.now; + Clock.resolution; + + if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { + global['WScript'].InitializeProjection(); + + Clock.now = function () { + return TestUtilities.QueryPerformanceCounter(); + }; + + Clock.resolution = TestUtilities.QueryPerformanceFrequency(); + } else { + Clock.now = function () { + return Date.now(); + }; + + Clock.resolution = 1000; + } + })(Clock || (Clock = {})); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = Clock.now(); + }; + + Timer.prototype.end = function () { + this.time = (Clock.now() - this.startTime); + }; + return Timer; + })(); + TypeScript.Timer = Timer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + + StringScriptSnapshot.prototype.getLineStartPositions = function () { + return TypeScript.TextUtilities.parseLineStarts(TypeScript.SimpleText.fromString(this.text)); + }; + + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_lineStarts, length) { + this._lineStarts = _lineStarts; + this.length = length; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this._lineStarts, length: this.length }; + }; + + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { + return v1 === v2; + }); + }; + + LineMap.prototype.lineStarts = function () { + return this._lineStarts; + }; + + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + + LineMap.fromSimpleText = function (text) { + var lineStarts = TypeScript.TextUtilities.parseLineStarts(text); + + return new LineMap(lineStarts, text.length()); + }; + + LineMap.fromScriptSnapshot = function (scriptSnapshot) { + return new LineMap(scriptSnapshot.getLineStartPositions(), scriptSnapshot.getLength()); + }; + + LineMap.fromString = function (text) { + return LineMap.fromSimpleText(TypeScript.SimpleText.fromString(text)); + }; + LineMap.empty = new LineMap([0], 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + (function (TextFactory) { + function getStartAndLengthOfLineBreakEndingAt(text, index, info) { + var c = text.charCodeAt(index); + if (c === 10 /* lineFeed */) { + if (index > 0 && text.charCodeAt(index - 1) === 13 /* carriageReturn */) { + info.startPosition = index - 1; + info.length = 2; + } else { + info.startPosition = index; + info.length = 1; + } + } else if (TypeScript.TextUtilities.isAnyLineBreakCharacter(c)) { + info.startPosition = index; + info.length = 1; + } else { + info.startPosition = index + 1; + info.length = 0; + } + } + + var LinebreakInfo = (function () { + function LinebreakInfo(startPosition, length) { + this.startPosition = startPosition; + this.length = length; + } + return LinebreakInfo; + })(); + + var TextLine = (function () { + function TextLine(text, body, lineBreakLength, lineNumber) { + this._text = null; + this._textSpan = null; + TypeScript.Contract.throwIfNull(text); + TypeScript.Contract.throwIfFalse(lineBreakLength >= 0); + TypeScript.Contract.requires(lineNumber >= 0); + this._text = text; + this._textSpan = body; + this._lineBreakLength = lineBreakLength; + this._lineNumber = lineNumber; + } + TextLine.prototype.start = function () { + return this._textSpan.start(); + }; + + TextLine.prototype.end = function () { + return this._textSpan.end(); + }; + + TextLine.prototype.endIncludingLineBreak = function () { + return this.end() + this._lineBreakLength; + }; + + TextLine.prototype.extent = function () { + return this._textSpan; + }; + + TextLine.prototype.extentIncludingLineBreak = function () { + return TypeScript.TextSpan.fromBounds(this.start(), this.endIncludingLineBreak()); + }; + + TextLine.prototype.toString = function () { + return this._text.toString(this._textSpan); + }; + + TextLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + return TextLine; + })(); + + var TextBase = (function () { + function TextBase() { + this.lazyLineStarts = null; + this.linebreakInfo = new LinebreakInfo(0, 0); + this.lastLineFoundForPosition = null; + } + TextBase.prototype.length = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.charCodeAt = function (position) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + TextBase.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this, span); + }; + + TextBase.prototype.substr = function (start, length, intern) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + TextBase.prototype.lines = function () { + var lines = []; + + var length = this.lineCount(); + for (var i = 0; i < length; ++i) { + lines[i] = this.getLineFromLineNumber(i); + } + + return lines; + }; + + TextBase.prototype.lineMap = function () { + return new TypeScript.LineMap(this.lineStarts(), this.length()); + }; + + TextBase.prototype.lineStarts = function () { + if (this.lazyLineStarts === null) { + this.lazyLineStarts = TypeScript.TextUtilities.parseLineStarts(this); + } + + return this.lazyLineStarts; + }; + + TextBase.prototype.getLineFromLineNumber = function (lineNumber) { + var lineStarts = this.lineStarts(); + + if (lineNumber < 0 || lineNumber >= lineStarts.length) { + throw TypeScript.Errors.argumentOutOfRange("lineNumber"); + } + + var first = lineStarts[lineNumber]; + if (lineNumber === lineStarts.length - 1) { + return new TextLine(this, new TypeScript.TextSpan(first, this.length() - first), 0, lineNumber); + } else { + getStartAndLengthOfLineBreakEndingAt(this, lineStarts[lineNumber + 1] - 1, this.linebreakInfo); + return new TextLine(this, new TypeScript.TextSpan(first, this.linebreakInfo.startPosition - first), this.linebreakInfo.length, lineNumber); + } + }; + + TextBase.prototype.getLineFromPosition = function (position) { + var lastFound = this.lastLineFoundForPosition; + if (lastFound !== null && lastFound.start() <= position && lastFound.endIncludingLineBreak() > position) { + return lastFound; + } + + var lineNumber = this.getLineNumberFromPosition(position); + + var result = this.getLineFromLineNumber(lineNumber); + this.lastLineFoundForPosition = result; + return result; + }; + + TextBase.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length()) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + TextBase.prototype.getLinePosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + return TextBase; + })(); + + var SubText = (function (_super) { + __extends(SubText, _super); + function SubText(text, span) { + _super.call(this); + + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SubText.prototype.length = function () { + return this.span.length(); + }; + + SubText.prototype.charCodeAt = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.text.charCodeAt(this.span.start() + position); + }; + + SubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + return SubText; + })(TextBase); + + var StringText = (function (_super) { + __extends(StringText, _super); + function StringText(data) { + _super.call(this); + this.source = null; + + if (data === null) { + throw TypeScript.Errors.argumentNull("data"); + } + + this.source = data; + } + StringText.prototype.length = function () { + return this.source.length; + }; + + StringText.prototype.charCodeAt = function (position) { + if (position < 0 || position >= this.source.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.source.charCodeAt(position); + }; + + StringText.prototype.substr = function (start, length, intern) { + return this.source.substr(start, length); + }; + + StringText.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + if (span === null) { + span = new TypeScript.TextSpan(0, this.length()); + } + + this.checkSubSpan(span); + + if (span.start() === 0 && span.length() === this.length()) { + return this.source; + } + + return this.source.substr(span.start(), span.length()); + }; + + StringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.source, sourceIndex, destination, destinationIndex, count); + }; + return StringText; + })(TextBase); + + function createText(value) { + return new StringText(value); + } + TextFactory.createText = createText; + })(TypeScript.TextFactory || (TypeScript.TextFactory = {})); + var TextFactory = TypeScript.TextFactory; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleSubText = (function () { + function SimpleSubText(text, span) { + this.text = null; + this.span = null; + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SimpleSubText.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + SimpleSubText.prototype.checkSubPosition = function (position) { + if (position < 0 || position >= this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + }; + + SimpleSubText.prototype.length = function () { + return this.span.length(); + }; + + SimpleSubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SimpleSubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SimpleSubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SimpleSubText.prototype.substr = function (start, length, intern) { + var span = this.getCompositeSpan(start, length); + return this.text.substr(span.start(), span.length(), intern); + }; + + SimpleSubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SimpleSubText.prototype.charCodeAt = function (index) { + this.checkSubPosition(index); + return this.text.charCodeAt(this.span.start() + index); + }; + + SimpleSubText.prototype.lineMap = function () { + return TypeScript.LineMap.fromSimpleText(this); + }; + return SimpleSubText; + })(); + + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + + SimpleStringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.value, sourceIndex, destination, destinationIndex, count); + }; + + SimpleStringText.prototype.substr = function (start, length, intern) { + if (intern) { + var array = length <= SimpleStringText.charArray.length ? SimpleStringText.charArray : TypeScript.ArrayUtilities.createArray(length, 0); + this.copyTo(start, array, 0, length); + return TypeScript.Collections.DefaultStringTable.addCharArray(array, 0, length); + } + + return this.value.substr(start, length); + }; + + SimpleStringText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + + SimpleStringText.prototype.lineMap = function () { + return TypeScript.LineMap.fromSimpleText(this); + }; + SimpleStringText.charArray = TypeScript.ArrayUtilities.createArray(1024, 0); + return SimpleStringText; + })(); + + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + + SimpleScriptSnapshotText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var text = this.scriptSnapshot.getText(sourceIndex, sourceIndex + count); + TypeScript.StringUtilities.copyTo(text, 0, destination, destinationIndex, count); + }; + + SimpleScriptSnapshotText.prototype.substr = function (start, length, intern) { + return this.scriptSnapshot.getText(start, start + length); + }; + + SimpleScriptSnapshotText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleScriptSnapshotText.prototype.lineMap = function () { + var lineStartPositions = this.scriptSnapshot.getLineStartPositions(); + return new TypeScript.LineMap(lineStartPositions, this.length()); + }; + return SimpleScriptSnapshotText; + })(); + + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length(); + + if (0 === length) { + var result = []; + result.push(0); + return result; + } + + var position = 0; + var index = 0; + var arrayBuilder = []; + var lineNumber = 0; + + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + + if (0 === lineBreakLength) { + index++; + } else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + + arrayBuilder.push(position); + + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length()) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } else if (isAnyLineBreakCharacter(c)) { + return 1; + } else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + + if (start + length < start) { + throw new Error("length"); + } + + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + + TextSpan.prototype.length = function () { + return this._length; + }; + + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + return overlapStart < overlapEnd; + }; + + TextSpan.prototype.overlap = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + + return null; + }; + + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + + TextSpan.prototype.intersection = function (span) { + var intersectStart = TypeScript.MathPrototype.max(this._start, span._start); + var intersectEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + + return null; + }; + + TextSpan.fromBounds = function (start, end) { + TypeScript.Contract.requires(start >= 0); + TypeScript.Contract.requires(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + + TextChangeRange.collapseChangesFromSingleVersion = function (changes) { + var diff = 0; + var start = 1073741823 /* Max31BitInteger */; + var end = 0; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + diff += change.newLength() - change.span().length(); + + if (change.span().start() < start) { + start = change.span().start(); + } + + if (change.span().end() > end) { + end = change.span().end(); + } + } + + if (start > end) { + return null; + } + + var combined = TypeScript.TextSpan.fromBounds(start, end); + var newLen = combined.length() + diff; + + return new TextChangeRange(combined, newLen); + }; + + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + + if (changes.length === 1) { + return changes[0]; + } + + var change0 = changes[0]; + + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + + oldStartN = TypeScript.MathPrototype.min(oldStart1, oldStart2); + oldEndN = TypeScript.MathPrototype.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = TypeScript.MathPrototype.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CharacterInfo = (function () { + function CharacterInfo() { + } + CharacterInfo.isDecimalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + }; + + CharacterInfo.isHexDigit = function (c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + }; + + CharacterInfo.hexValue = function (c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + }; + + CharacterInfo.isWhitespace = function (ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + + return false; + }; + + CharacterInfo.isLineTerminator = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + + return false; + }; + return CharacterInfo; + })(); + TypeScript.CharacterInfo = CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["TriviaNewLineMask"] = 0x00000001] = "TriviaNewLineMask"; + SyntaxConstants[SyntaxConstants["TriviaCommentMask"] = 0x00000002] = "TriviaCommentMask"; + SyntaxConstants[SyntaxConstants["TriviaFullWidthShift"] = 2] = "TriviaFullWidthShift"; + + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; +})(); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfToken(token, syntaxInformationMap, options) { + return columnForStartOfToken(token, syntaxInformationMap, options) + token.width(); + } + Indentation.columnForEndOfToken = columnForEndOfToken; + + function columnForStartOfToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + var current = token; + while (current !== firstTokenInLine) { + current = syntaxInformationMap.previousToken(current); + + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } else { + leadingTextInReverse.push(current.fullText()); + } + } + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfToken = columnForStartOfToken; + + function columnForStartOfFirstTokenInLineContainingToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingToken = columnForStartOfFirstTokenInLineContainingToken; + + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + + if (lineSegments.length > 0) { + break; + } + } + + leadingTextInReverse.push(trivia.fullText()); + } + } + + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + + return column; + } + + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } else { + column++; + } + } + + return column; + } + + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = TypeScript.MathPrototype.max(0, column); + + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + + function indentationTrivia(column, options) { + return TypeScript.Syntax.whitespace(this.indentationString(column, options)); + } + Indentation.indentationTrivia = indentationTrivia; + + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(TypeScript.LanguageVersion || (TypeScript.LanguageVersion = {})); + var LanguageVersion = TypeScript.LanguageVersion; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ParseOptions = (function () { + function ParseOptions(allowAutomaticSemicolonInsertion, allowModuleKeywordInExternalModuleReference) { + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + this._allowModuleKeywordInExternalModuleReference = allowModuleKeywordInExternalModuleReference; + } + ParseOptions.prototype.toJSON = function (key) { + return { + allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion, + allowModuleKeywordInExternalModuleReference: this._allowModuleKeywordInExternalModuleReference + }; + }; + + ParseOptions.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + + ParseOptions.prototype.allowModuleKeywordInExternalModuleReference = function () { + return this._allowModuleKeywordInExternalModuleReference; + }; + return ParseOptions; + })(); + TypeScript.ParseOptions = ParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionedElement = (function () { + function PositionedElement(parent, element, fullStart) { + this._parent = parent; + this._element = element; + this._fullStart = fullStart; + } + PositionedElement.create = function (parent, element, fullStart) { + if (element === null) { + return null; + } + + if (element.isNode()) { + return new PositionedNode(parent, element, fullStart); + } else if (element.isToken()) { + return new PositionedToken(parent, element, fullStart); + } else if (element.isList()) { + return new PositionedList(parent, element, fullStart); + } else if (element.isSeparatedList()) { + return new PositionedSeparatedList(parent, element, fullStart); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + PositionedElement.prototype.parent = function () { + return this._parent; + }; + + PositionedElement.prototype.parentElement = function () { + return this._parent && this._parent._element; + }; + + PositionedElement.prototype.element = function () { + return this._element; + }; + + PositionedElement.prototype.kind = function () { + return this.element().kind(); + }; + + PositionedElement.prototype.childIndex = function (child) { + return TypeScript.Syntax.childIndex(this.element(), child); + }; + + PositionedElement.prototype.childCount = function () { + return this.element().childCount(); + }; + + PositionedElement.prototype.childAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + return PositionedElement.create(this, this.element().childAt(index), this.fullStart() + offset); + }; + + PositionedElement.prototype.childStart = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEnd = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.childStartAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEndAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.getPositionedChild = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return PositionedElement.create(this, child, this.fullStart() + offset); + }; + + PositionedElement.prototype.fullStart = function () { + return this._fullStart; + }; + + PositionedElement.prototype.fullEnd = function () { + return this.fullStart() + this.element().fullWidth(); + }; + + PositionedElement.prototype.fullWidth = function () { + return this.element().fullWidth(); + }; + + PositionedElement.prototype.start = function () { + return this.fullStart() + this.element().leadingTriviaWidth(); + }; + + PositionedElement.prototype.end = function () { + return this.fullStart() + this.element().leadingTriviaWidth() + this.element().width(); + }; + + PositionedElement.prototype.root = function () { + var current = this; + while (current.parent() !== null) { + current = current.parent(); + } + + return current; + }; + + PositionedElement.prototype.containingNode = function () { + var current = this.parent(); + + while (current !== null && !current.element().isNode()) { + current = current.parent(); + } + + return current; + }; + return PositionedElement; + })(); + TypeScript.PositionedElement = PositionedElement; + + var PositionedNodeOrToken = (function (_super) { + __extends(PositionedNodeOrToken, _super); + function PositionedNodeOrToken(parent, nodeOrToken, fullStart) { + _super.call(this, parent, nodeOrToken, fullStart); + } + PositionedNodeOrToken.prototype.nodeOrToken = function () { + return this.element(); + }; + return PositionedNodeOrToken; + })(PositionedElement); + TypeScript.PositionedNodeOrToken = PositionedNodeOrToken; + + var PositionedNode = (function (_super) { + __extends(PositionedNode, _super); + function PositionedNode(parent, node, fullStart) { + _super.call(this, parent, node, fullStart); + } + PositionedNode.prototype.node = function () { + return this.element(); + }; + return PositionedNode; + })(PositionedNodeOrToken); + TypeScript.PositionedNode = PositionedNode; + + var PositionedToken = (function (_super) { + __extends(PositionedToken, _super); + function PositionedToken(parent, token, fullStart) { + _super.call(this, parent, token, fullStart); + } + PositionedToken.prototype.token = function () { + return this.element(); + }; + + PositionedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var triviaList = this.token().leadingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = this.start(); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), currentTriviaEndPosition - trivia.fullWidth()); + } + + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + + var start = this.fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + var triviaList = this.token().trailingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var fullStart = this.end(); + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), fullStart); + } + + fullStart += trivia.fullWidth(); + } + } + + return this.root().node().findToken(this.fullEnd(), includeSkippedTokens); + }; + return PositionedToken; + })(PositionedNodeOrToken); + TypeScript.PositionedToken = PositionedToken; + + var PositionedList = (function (_super) { + __extends(PositionedList, _super); + function PositionedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedList.prototype.list = function () { + return this.element(); + }; + return PositionedList; + })(PositionedElement); + TypeScript.PositionedList = PositionedList; + + var PositionedSeparatedList = (function (_super) { + __extends(PositionedSeparatedList, _super); + function PositionedSeparatedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedSeparatedList.prototype.list = function () { + return this.element(); + }; + return PositionedSeparatedList; + })(PositionedElement); + TypeScript.PositionedSeparatedList = PositionedSeparatedList; + + var PositionedSkippedToken = (function (_super) { + __extends(PositionedSkippedToken, _super); + function PositionedSkippedToken(parentToken, token, fullStart) { + _super.call(this, parentToken.parent(), token, fullStart); + this._parentToken = parentToken; + } + PositionedSkippedToken.prototype.parentToken = function () { + return this._parentToken; + }; + + PositionedSkippedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var start = this.fullStart(); + + if (includeSkippedTokens) { + var previousToken; + + if (start >= this.parentToken().end()) { + previousToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + + return this.parentToken(); + } else { + previousToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + } + } + + var start = this.parentToken().fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedSkippedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + if (includeSkippedTokens) { + var end = this.end(); + var nextToken; + + if (end <= this.parentToken().start()) { + nextToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + + return this.parentToken(); + } else { + nextToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + } + } + + return this.root().node().findToken(this.parentToken().fullEnd(), includeSkippedTokens); + }; + return PositionedSkippedToken; + })(PositionedToken); + TypeScript.PositionedSkippedToken = PositionedSkippedToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Scanner = (function () { + function Scanner(fileName, text, languageVersion, window) { + if (typeof window === "undefined") { window = TypeScript.ArrayUtilities.createArray(2048, 0); } + Scanner.initializeStaticData(); + + this.slidingWindow = new TypeScript.SlidingWindow(this, window, 0, text.length()); + this.fileName = fileName; + this.text = text; + this._languageVersion = languageVersion; + } + Scanner.initializeStaticData = function () { + if (Scanner.isKeywordStartCharacter.length === 0) { + Scanner.isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + Scanner.isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + Scanner.isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + Scanner.isNumericLiteralStart = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if (character >= 97 /* a */ && character <= 122 /* z */) { + Scanner.isIdentifierStartCharacter[character] = true; + Scanner.isIdentifierPartCharacter[character] = true; + } else if ((character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + Scanner.isIdentifierStartCharacter[character] = true; + Scanner.isIdentifierPartCharacter[character] = true; + } else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + Scanner.isIdentifierPartCharacter[character] = true; + Scanner.isNumericLiteralStart[character] = true; + } + } + + Scanner.isNumericLiteralStart[46 /* dot */] = true; + + for (var keywordKind = TypeScript.SyntaxKind.FirstKeyword; keywordKind <= TypeScript.SyntaxKind.LastKeyword; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + Scanner.isKeywordStartCharacter[keyword.charCodeAt(0)] = true; + } + } + }; + + Scanner.prototype.languageVersion = function () { + return this._languageVersion; + }; + + Scanner.prototype.fetchMoreItems = function (argument, sourceIndex, window, destinationIndex, spaceAvailable) { + var charactersRemaining = this.text.length() - sourceIndex; + var amountToRead = TypeScript.MathPrototype.min(charactersRemaining, spaceAvailable); + this.text.copyTo(sourceIndex, window, destinationIndex, amountToRead); + return amountToRead; + }; + + Scanner.prototype.currentCharCode = function () { + return this.slidingWindow.currentItem(null); + }; + + Scanner.prototype.absoluteIndex = function () { + return this.slidingWindow.absoluteIndex(); + }; + + Scanner.prototype.setAbsoluteIndex = function (index) { + this.slidingWindow.setAbsoluteIndex(index); + }; + + Scanner.prototype.scan = function (diagnostics, allowRegularExpression) { + var diagnosticsLength = diagnostics.length; + var fullStart = this.slidingWindow.absoluteIndex(); + var leadingTriviaInfo = this.scanTriviaInfo(diagnostics, false); + + var start = this.slidingWindow.absoluteIndex(); + var kind = this.scanSyntaxToken(diagnostics, allowRegularExpression); + var end = this.slidingWindow.absoluteIndex(); + + var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo); + + return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; + }; + + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo) { + if (kind >= TypeScript.SyntaxKind.FirstFixedWidth) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); + } else { + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(this.text, fullStart, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo); + } else { + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } else { + var width = end - start; + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(this.text, fullStart, kind, width); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(this.text, fullStart, kind, width, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); + } + } + }; + + Scanner.scanTrivia = function (text, start, length, isTrailing) { + var scanner = new Scanner(null, text.subText(new TypeScript.TextSpan(start, length)), 1 /* EcmaScript5 */, Scanner.triviaWindow); + return scanner.scanTrivia(isTrailing); + }; + + Scanner.prototype.scanTrivia = function (isTrailing) { + var trivia = []; + + while (true) { + if (!this.slidingWindow.isAtEndOfSource()) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(this.scanWhitespaceTrivia()); + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + trivia.push(this.scanSingleLineCommentTrivia()); + continue; + } + + if (ch2 === 42 /* asterisk */) { + trivia.push(this.scanMultiLineCommentTrivia()); + continue; + } + + throw TypeScript.Errors.invalidOperation(); + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(this.scanLineTerminatorSequenceTrivia(ch)); + + if (!isTrailing) { + continue; + } + + break; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + return TypeScript.Syntax.triviaList(trivia); + } + }; + + Scanner.prototype.scanTriviaInfo = function (diagnostics, isTrailing) { + var width = 0; + var hasCommentOrNewLine = 0; + + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanSingleLineCommentTriviaLength(); + continue; + } + + if (ch2 === 42 /* asterisk */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanMultiLineCommentTriviaLength(diagnostics); + continue; + } + + break; + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + hasCommentOrNewLine |= 1 /* TriviaNewLineMask */; + width += this.scanLineTerminatorSequenceLength(ch); + + if (!isTrailing) { + continue; + } + + break; + } + + return (width << 2 /* TriviaFullWidthShift */) | hasCommentOrNewLine; + } + }; + + Scanner.prototype.isNewLineCharacter = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + }; + + Scanner.prototype.scanWhitespaceTrivia = function () { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var width = 0; + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + } + + break; + } + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.whitespace(text); + }; + + Scanner.prototype.scanSingleLineCommentTrivia = function () { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanSingleLineCommentTriviaLength(); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.singleLineComment(text); + }; + + Scanner.prototype.scanSingleLineCommentTriviaLength = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource() || this.isNewLineCharacter(this.currentCharCode())) { + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanMultiLineCommentTrivia = function () { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanMultiLineCommentTriviaLength(null); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.multiLineComment(text); + }; + + Scanner.prototype.scanMultiLineCommentTriviaLength = function (diagnostics) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource()) { + if (diagnostics !== null) { + diagnostics.push(new TypeScript.SyntaxDiagnostic(this.fileName, this.slidingWindow.absoluteIndex(), 0, 14 /* _StarSlash__expected */, null)); + } + + return width; + } + + var ch = this.currentCharCode(); + if (ch === 42 /* asterisk */ && this.slidingWindow.peekItemN(1) === 47 /* slash */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + width += 2; + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanLineTerminatorSequenceTrivia = function (ch) { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanLineTerminatorSequenceLength(ch); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.trivia(5 /* NewLineTrivia */, text); + }; + + Scanner.prototype.scanLineTerminatorSequenceLength = function (ch) { + this.slidingWindow.moveToNextItem(); + + if (ch === 13 /* carriageReturn */ && this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + return 2; + } else { + return 1; + } + }; + + Scanner.prototype.scanSyntaxToken = function (diagnostics, allowRegularExpression) { + if (this.slidingWindow.isAtEndOfSource()) { + return 10 /* EndOfFileToken */; + } + + var character = this.currentCharCode(); + + switch (character) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + return this.scanStringLiteral(diagnostics); + + case 47 /* slash */: + return this.scanSlashToken(allowRegularExpression); + + case 46 /* dot */: + return this.scanDotToken(); + + case 45 /* minus */: + return this.scanMinusToken(); + + case 33 /* exclamation */: + return this.scanExclamationToken(); + + case 61 /* equals */: + return this.scanEqualsToken(); + + case 124 /* bar */: + return this.scanBarToken(); + + case 42 /* asterisk */: + return this.scanAsteriskToken(); + + case 43 /* plus */: + return this.scanPlusToken(); + + case 37 /* percent */: + return this.scanPercentToken(); + + case 38 /* ampersand */: + return this.scanAmpersandToken(); + + case 94 /* caret */: + return this.scanCaretToken(); + + case 60 /* lessThan */: + return this.scanLessThanToken(); + + case 62 /* greaterThan */: + return this.advanceAndSetTokenKind(82 /* GreaterThanToken */); + + case 44 /* comma */: + return this.advanceAndSetTokenKind(80 /* CommaToken */); + + case 58 /* colon */: + return this.advanceAndSetTokenKind(107 /* ColonToken */); + + case 59 /* semicolon */: + return this.advanceAndSetTokenKind(79 /* SemicolonToken */); + + case 126 /* tilde */: + return this.advanceAndSetTokenKind(103 /* TildeToken */); + + case 40 /* openParen */: + return this.advanceAndSetTokenKind(73 /* OpenParenToken */); + + case 41 /* closeParen */: + return this.advanceAndSetTokenKind(74 /* CloseParenToken */); + + case 123 /* openBrace */: + return this.advanceAndSetTokenKind(71 /* OpenBraceToken */); + + case 125 /* closeBrace */: + return this.advanceAndSetTokenKind(72 /* CloseBraceToken */); + + case 91 /* openBracket */: + return this.advanceAndSetTokenKind(75 /* OpenBracketToken */); + + case 93 /* closeBracket */: + return this.advanceAndSetTokenKind(76 /* CloseBracketToken */); + + case 63 /* question */: + return this.advanceAndSetTokenKind(106 /* QuestionToken */); + } + + if (Scanner.isNumericLiteralStart[character]) { + return this.scanNumericLiteral(); + } + + if (Scanner.isIdentifierStartCharacter[character]) { + var result = this.tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + + if (this.isIdentifierStart(this.peekCharOrUnicodeEscape())) { + return this.slowScanIdentifier(diagnostics); + } + + return this.scanDefaultCharacter(character, diagnostics); + }; + + Scanner.prototype.isIdentifierStart = function (interpretedChar) { + if (Scanner.isIdentifierStartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.isIdentifierPart = function (interpretedChar) { + if (Scanner.isIdentifierPartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.tryFastScanIdentifierOrKeyword = function (firstCharacter) { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + while (true) { + var character = this.currentCharCode(); + if (Scanner.isIdentifierPartCharacter[character]) { + this.slidingWindow.moveToNextItem(); + } else if (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 0 /* None */; + } else { + var endIndex = this.slidingWindow.absoluteIndex(); + + var kind; + if (Scanner.isKeywordStartCharacter[firstCharacter]) { + var offset = startIndex - this.slidingWindow.windowAbsoluteStartIndex; + kind = TypeScript.ScannerUtilities.identifierKind(this.slidingWindow.window, offset, endIndex - startIndex); + } else { + kind = 11 /* IdentifierName */; + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return kind; + } + } + }; + + Scanner.prototype.slowScanIdentifier = function (diagnostics) { + var startIndex = this.slidingWindow.absoluteIndex(); + + do { + this.scanCharOrUnicodeEscape(diagnostics); + } while(this.isIdentifierPart(this.peekCharOrUnicodeEscape())); + + return 11 /* IdentifierName */; + }; + + Scanner.prototype.scanNumericLiteral = function () { + if (this.isHexNumericLiteral()) { + return this.scanHexNumericLiteral(); + } else { + return this.scanDecimalNumericLiteral(); + } + }; + + Scanner.prototype.scanDecimalNumericLiteral = function () { + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + if (this.currentCharCode() === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + } + + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + var ch = this.currentCharCode(); + if (ch === 101 /* e */ || ch === 69 /* E */) { + this.slidingWindow.moveToNextItem(); + + ch = this.currentCharCode(); + if (ch === 45 /* minus */ || ch === 43 /* plus */) { + if (TypeScript.CharacterInfo.isDecimalDigit(this.slidingWindow.peekItemN(1))) { + this.slidingWindow.moveToNextItem(); + } + } + } + + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.scanHexNumericLiteral = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + while (TypeScript.CharacterInfo.isHexDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.isHexNumericLiteral = function () { + if (this.currentCharCode() === 48 /* _0 */) { + var ch = this.slidingWindow.peekItemN(1); + + if (ch === 120 /* x */ || ch === 88 /* X */) { + ch = this.slidingWindow.peekItemN(2); + + return TypeScript.CharacterInfo.isHexDigit(ch); + } + } + + return false; + }; + + Scanner.prototype.advanceAndSetTokenKind = function (kind) { + this.slidingWindow.moveToNextItem(); + return kind; + }; + + Scanner.prototype.scanLessThanToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 83 /* LessThanEqualsToken */; + } else if (this.currentCharCode() === 60 /* lessThan */) { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 113 /* LessThanLessThanEqualsToken */; + } else { + return 96 /* LessThanLessThanToken */; + } + } else { + return 81 /* LessThanToken */; + } + }; + + Scanner.prototype.scanBarToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 117 /* BarEqualsToken */; + } else if (this.currentCharCode() === 124 /* bar */) { + this.slidingWindow.moveToNextItem(); + return 105 /* BarBarToken */; + } else { + return 100 /* BarToken */; + } + }; + + Scanner.prototype.scanCaretToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 118 /* CaretEqualsToken */; + } else { + return 101 /* CaretToken */; + } + }; + + Scanner.prototype.scanAmpersandToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 116 /* AmpersandEqualsToken */; + } else if (this.currentCharCode() === 38 /* ampersand */) { + this.slidingWindow.moveToNextItem(); + return 104 /* AmpersandAmpersandToken */; + } else { + return 99 /* AmpersandToken */; + } + }; + + Scanner.prototype.scanPercentToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 112 /* PercentEqualsToken */; + } else { + return 93 /* PercentToken */; + } + }; + + Scanner.prototype.scanMinusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 110 /* MinusEqualsToken */; + } else if (character === 45 /* minus */) { + this.slidingWindow.moveToNextItem(); + return 95 /* MinusMinusToken */; + } else { + return 91 /* MinusToken */; + } + }; + + Scanner.prototype.scanPlusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 109 /* PlusEqualsToken */; + } else if (character === 43 /* plus */) { + this.slidingWindow.moveToNextItem(); + return 94 /* PlusPlusToken */; + } else { + return 90 /* PlusToken */; + } + }; + + Scanner.prototype.scanAsteriskToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 111 /* AsteriskEqualsToken */; + } else { + return 92 /* AsteriskToken */; + } + }; + + Scanner.prototype.scanEqualsToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 88 /* EqualsEqualsEqualsToken */; + } else { + return 85 /* EqualsEqualsToken */; + } + } else if (character === 62 /* greaterThan */) { + this.slidingWindow.moveToNextItem(); + return 86 /* EqualsGreaterThanToken */; + } else { + return 108 /* EqualsToken */; + } + }; + + Scanner.prototype.isDotPrefixedNumericLiteral = function () { + if (this.currentCharCode() === 46 /* dot */) { + var ch = this.slidingWindow.peekItemN(1); + return TypeScript.CharacterInfo.isDecimalDigit(ch); + } + + return false; + }; + + Scanner.prototype.scanDotToken = function () { + if (this.isDotPrefixedNumericLiteral()) { + return this.scanNumericLiteral(); + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 46 /* dot */ && this.slidingWindow.peekItemN(1) === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + return 78 /* DotDotDotToken */; + } else { + return 77 /* DotToken */; + } + }; + + Scanner.prototype.scanSlashToken = function (allowRegularExpression) { + if (allowRegularExpression) { + var result = this.tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 120 /* SlashEqualsToken */; + } else { + return 119 /* SlashToken */; + } + }; + + Scanner.prototype.tryScanRegularExpressionToken = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + try { + this.slidingWindow.moveToNextItem(); + + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = this.currentCharCode(); + if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + return 0 /* None */; + } + + this.slidingWindow.moveToNextItem(); + if (inEscape) { + inEscape = false; + continue; + } + + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + + case 91 /* openBracket */: + inCharacterClass = true; + continue; + + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + + break; + + default: + continue; + } + + break; + } + + while (Scanner.isIdentifierPartCharacter[this.currentCharCode()]) { + this.slidingWindow.moveToNextItem(); + } + + return 12 /* RegularExpressionLiteral */; + } finally { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + } + }; + + Scanner.prototype.scanExclamationToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 89 /* ExclamationEqualsEqualsToken */; + } else { + return 87 /* ExclamationEqualsToken */; + } + } else { + return 102 /* ExclamationToken */; + } + }; + + Scanner.prototype.scanDefaultCharacter = function (character, diagnostics) { + var position = this.slidingWindow.absoluteIndex(); + this.slidingWindow.moveToNextItem(); + + var text = String.fromCharCode(character); + var messageText = this.getErrorMessageText(text); + diagnostics.push(new TypeScript.SyntaxDiagnostic(this.fileName, position, 1, 5 /* Unexpected_character_0 */, [messageText])); + + return 9 /* ErrorToken */; + }; + + Scanner.prototype.getErrorMessageText = function (text) { + if (text === "\\") { + return '"\\"'; + } + + return JSON.stringify(text); + }; + + Scanner.prototype.skipEscapeSequence = function (diagnostics) { + var rewindPoint = this.slidingWindow.getAndPinAbsoluteIndex(); + try { + this.slidingWindow.moveToNextItem(); + + var ch = this.currentCharCode(); + this.slidingWindow.moveToNextItem(); + switch (ch) { + case 120 /* x */: + case 117 /* u */: + this.slidingWindow.rewindToPinnedIndex(rewindPoint); + var value = this.scanUnicodeOrHexEscape(diagnostics); + return; + + case 13 /* carriageReturn */: + if (this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + } + return; + + default: + return; + } + } finally { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint); + } + }; + + Scanner.prototype.scanStringLiteral = function (diagnostics) { + var quoteCharacter = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + while (true) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + this.skipEscapeSequence(diagnostics); + } else if (ch === quoteCharacter) { + this.slidingWindow.moveToNextItem(); + break; + } else if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + diagnostics.push(new TypeScript.SyntaxDiagnostic(this.fileName, this.slidingWindow.absoluteIndex(), 1, 6 /* Missing_closing_quote_character */, null)); + break; + } else { + this.slidingWindow.moveToNextItem(); + } + } + + return 14 /* StringLiteral */; + }; + + Scanner.prototype.isUnicodeOrHexEscape = function (character) { + return this.isUnicodeEscape(character) || this.isHexEscape(character); + }; + + Scanner.prototype.isUnicodeEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.isHexEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 120 /* x */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.peekCharOrUnicodeOrHexEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeOrHexEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekCharOrUnicodeEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekUnicodeOrHexEscape = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var ch = this.scanUnicodeOrHexEscape(null); + + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return this.scanUnicodeOrHexEscape(errors); + } + } + + this.slidingWindow.moveToNextItem(); + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeOrHexEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */ || ch2 === 120 /* x */) { + return this.scanUnicodeOrHexEscape(errors); + } + } + + this.slidingWindow.moveToNextItem(); + return ch; + }; + + Scanner.prototype.scanUnicodeOrHexEscape = function (errors) { + var start = this.slidingWindow.absoluteIndex(); + var character = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + character = this.currentCharCode(); + + var intChar = 0; + this.slidingWindow.moveToNextItem(); + + var count = character === 117 /* u */ ? 4 : 2; + + for (var i = 0; i < count; i++) { + var ch2 = this.currentCharCode(); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (errors !== null) { + var end = this.slidingWindow.absoluteIndex(); + var info = this.createIllegalEscapeDiagnostic(start, end); + errors.push(info); + } + + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + this.slidingWindow.moveToNextItem(); + } + + return intChar; + }; + + Scanner.prototype.substring = function (start, end, intern) { + var length = end - start; + var offset = start - this.slidingWindow.windowAbsoluteStartIndex; + + if (intern) { + return TypeScript.Collections.DefaultStringTable.addCharArray(this.slidingWindow.window, offset, length); + } else { + return TypeScript.StringUtilities.fromCharCodeArray(this.slidingWindow.window.slice(offset, offset + length)); + } + }; + + Scanner.prototype.createIllegalEscapeDiagnostic = function (start, end) { + return new TypeScript.SyntaxDiagnostic(this.fileName, start, end - start, 4 /* Unrecognized_escape_sequence */, null); + }; + + Scanner.isValidIdentifier = function (text, languageVersion) { + var scanner = new Scanner(null, text, TypeScript.LanguageVersion, Scanner.triviaWindow); + var errors = []; + var token = scanner.scan(errors, false); + + return errors.length === 0 && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && token.width() === text.length(); + }; + Scanner.isKeywordStartCharacter = []; + Scanner.isIdentifierStartCharacter = []; + Scanner.isIdentifierPartCharacter = []; + Scanner.isNumericLiteralStart = []; + + Scanner.triviaWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + return Scanner; + })(); + TypeScript.Scanner = Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (array, startIndex, length) { + switch (length) { + case 2: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (array[startIndex + 1]) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 3: + switch (array[startIndex]) { + case 102 /* f */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 97 /* a */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 65 /* GetKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 69 /* SetKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 4: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (array[startIndex + 1]) { + case 108 /* l */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 1]) { + case 104 /* h */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 118 /* v */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */) ? 62 /* BoolKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 5: + switch (array[startIndex]) { + case 98 /* b */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 2] === 97 /* a */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 114 /* r */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 6: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (array[startIndex + 1]) { + case 119 /* w */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 99 /* c */ && array[startIndex + 5] === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 2]) { + case 97 /* a */: + return (array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 3] === 105 /* i */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 103 /* g */) ? 70 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 116 /* t */: + return (array[startIndex + 1] === 121 /* y */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 111 /* o */ && array[startIndex + 5] === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (array[startIndex + 1] === 109 /* m */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 100 /* d */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 101 /* e */) ? 66 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 109 /* m */ && array[startIndex + 3] === 98 /* b */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 114 /* r */) ? 68 /* NumberKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 7: + switch (array[startIndex]) { + case 100 /* d */: + switch (array[startIndex + 1]) { + case 101 /* e */: + switch (array[startIndex + 2]) { + case 102 /* f */: + return (array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 117 /* u */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + return (array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 64 /* DeclareKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 100 /* d */ && array[startIndex + 6] === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 99 /* c */ && array[startIndex + 3] === 107 /* k */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 118 /* v */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 116 /* t */ && array[startIndex + 6] === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 97 /* a */ && array[startIndex + 6] === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 113 /* q */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 67 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 8: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 103 /* g */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 105 /* i */ && array[startIndex + 6] === 111 /* o */ && array[startIndex + 7] === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 9: + switch (array[startIndex]) { + case 105 /* i */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 102 /* f */ && array[startIndex + 6] === 97 /* a */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 99 /* c */ && array[startIndex + 6] === 116 /* t */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 10: + switch (array[startIndex]) { + case 105 /* i */: + switch (array[startIndex + 1]) { + case 110 /* n */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 99 /* c */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 111 /* o */ && array[startIndex + 9] === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 109 /* m */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 110 /* n */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 11: + return (array[startIndex] === 99 /* c */ && array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 111 /* o */ && array[startIndex + 10] === 114 /* r */) ? 63 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySeparatedSyntaxList = (function () { + function EmptySeparatedSyntaxList() { + } + EmptySeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + EmptySeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isList = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + EmptySeparatedSyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySeparatedSyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySeparatedSyntaxList.prototype.width = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + + EmptySeparatedSyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + return EmptySeparatedSyntaxList; + })(); + + Syntax.emptySeparatedList = new EmptySeparatedSyntaxList(); + + var SingletonSeparatedSyntaxList = (function () { + function SingletonSeparatedSyntaxList(item) { + this.item = item; + } + SingletonSeparatedSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + SingletonSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + SingletonSeparatedSyntaxList.prototype.childCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + SingletonSeparatedSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + SingletonSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSeparatedSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSeparatedSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSeparatedSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSeparatedSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return (this.item).findTokenInternal(new TypeScript.PositionedSeparatedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSeparatedSyntaxList; + })(); + + var NormalSeparatedSyntaxList = (function () { + function NormalSeparatedSyntaxList(elements) { + this._data = 0; + this.elements = elements; + } + NormalSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + NormalSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + NormalSeparatedSyntaxList.prototype.toJSON = function (key) { + return this.elements; + }; + + NormalSeparatedSyntaxList.prototype.childCount = function () { + return this.elements.length; + }; + NormalSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length + 1, 2); + }; + NormalSeparatedSyntaxList.prototype.separatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length, 2); + }; + + NormalSeparatedSyntaxList.prototype.toArray = function () { + return this.elements.slice(0); + }; + + NormalSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + var result = []; + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + result.push(this.nonSeparatorAt(i)); + } + + return result; + }; + + NormalSeparatedSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[index]; + }; + + NormalSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + var value = index * 2; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.separatorAt = function (index) { + var value = index * 2 + 1; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.firstToken = function () { + var token; + for (var i = 0, n = this.elements.length; i < n; i++) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.firstToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.lastToken = function () { + var token; + for (var i = this.elements.length - 1; i >= 0; i--) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.lastToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i).isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSeparatedSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSeparatedSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + fullWidth += childWidth; + + isIncrementallyUnusable = isIncrementallyUnusable || element.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSeparatedSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedSeparatedList(parent, this, fullStart); + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + if (position < childWidth) { + return (element).findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + element.collectTextElements(elements); + } + }; + + NormalSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.elements); + } else { + array.splice.apply(array, [index, 0].concat(this.elements)); + } + }; + return NormalSeparatedSyntaxList; + })(); + + function separatedList(nodes) { + return separatedListAndValidate(nodes, false); + } + Syntax.separatedList = separatedList; + + function separatedListAndValidate(nodes, validate) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptySeparatedList; + } + + if (validate) { + for (var i = 0; i < nodes.length; i++) { + var item = nodes[i]; + + if (i % 2 === 1) { + } + } + } + + if (nodes.length === 1) { + return new SingletonSeparatedSyntaxList(nodes[0]); + } + + return new NormalSeparatedSyntaxList(nodes); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(source, window, defaultValue, sourceLength) { + if (typeof sourceLength === "undefined") { sourceLength = -1; } + this.source = source; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.windowAbsoluteEndIndex = function () { + return this.windowAbsoluteStartIndex + this.windowCount; + }; + + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + if (this.sourceLength >= 0 && this.absoluteIndex() >= this.sourceLength) { + return false; + } + + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + + var spaceAvailable = this.window.length - this.windowCount; + var amountFetched = this.source.fetchMoreItems(argument, this.windowAbsoluteEndIndex(), this.window, this.windowCount, spaceAvailable); + + this.windowCount += amountFetched; + return amountFetched > 0; + }; + + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + + var shiftCount = this.windowCount - shiftStartIndex; + + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + + this.windowAbsoluteStartIndex += shiftStartIndex; + + this.windowCount -= shiftStartIndex; + + this.currentRelativeItemIndex -= shiftStartIndex; + } else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + + return absoluteIndex; + }; + + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + + this.currentRelativeItemIndex = relativeIndex; + }; + + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex]; + }; + + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex + n]; + }; + + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.setAbsoluteIndex = function (absoluteIndex) { + if (this.absoluteIndex() === absoluteIndex) { + return; + } + + if (this._pinCount > 0) { + } + + if (absoluteIndex >= this.windowAbsoluteStartIndex && absoluteIndex < this.windowAbsoluteEndIndex()) { + this.currentRelativeItemIndex = (absoluteIndex - this.windowAbsoluteStartIndex); + } else { + this.windowAbsoluteStartIndex = absoluteIndex; + + this.windowCount = 0; + + this.currentRelativeItemIndex = 0; + } + }; + + SlidingWindow.prototype.pinCount = function () { + return this._pinCount; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Strings = (function () { + function Strings() { + } + Strings.module__class__interface__enum__import_or_statement = "module, class, interface, enum, import or statement"; + Strings.constructor__function__accessor_or_variable = "constructor, function, accessor or variable"; + Strings.statement = "statement"; + Strings.case_or_default_clause = "case or default clause"; + Strings.identifier = "identifier"; + Strings.call__construct__index__property_or_function_signature = "call, construct, index, property or function signature"; + Strings.expression = "expression"; + Strings.type_name = "type name"; + Strings.property_or_accessor = "property or accessor"; + Strings.parameter = "parameter"; + Strings.type = "type"; + Strings.type_parameter = "type parameter"; + return Strings; + })(); + TypeScript.Strings = Strings; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function emptySourceUnit() { + return TypeScript.Syntax.normalModeFactory.sourceUnit(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(10 /* EndOfFileToken */, { text: "" })); + } + Syntax.emptySourceUnit = emptySourceUnit; + + function getStandaloneExpression(positionedToken) { + var token = positionedToken.token(); + if (positionedToken !== null && positionedToken.kind() === 11 /* IdentifierName */) { + var parentPositionedNode = positionedToken.containingNode(); + var parentNode = parentPositionedNode.node(); + + if (parentNode.kind() === 122 /* QualifiedName */ && (parentNode).right === token) { + return parentPositionedNode; + } else if (parentNode.kind() === 211 /* MemberAccessExpression */ && (parentNode).name === token) { + return parentPositionedNode; + } + } + + return positionedToken; + } + Syntax.getStandaloneExpression = getStandaloneExpression; + + function isInModuleOrTypeContext(positionedToken) { + if (positionedToken !== null) { + var positionedNodeOrToken = TypeScript.Syntax.getStandaloneExpression(positionedToken); + var parent = positionedNodeOrToken.containingNode(); + + if (parent !== null) { + switch (parent.kind()) { + case 246 /* ModuleNameModuleReference */: + return true; + case 122 /* QualifiedName */: + return true; + default: + return isInTypeOnlyContext(positionedToken); + } + } + } + + return false; + } + Syntax.isInModuleOrTypeContext = isInModuleOrTypeContext; + + function isInTypeOnlyContext(positionedToken) { + var positionedNodeOrToken = TypeScript.Syntax.getStandaloneExpression(positionedToken); + var positionedParent = positionedNodeOrToken.containingNode(); + + var parent = positionedParent.node(); + var nodeOrToken = positionedNodeOrToken.nodeOrToken(); + + if (parent !== null) { + switch (parent.kind()) { + case 125 /* ArrayType */: + return (parent).type === nodeOrToken; + case 219 /* CastExpression */: + return (parent).type === nodeOrToken; + case 244 /* TypeAnnotation */: + case 229 /* HeritageClause */: + case 227 /* TypeArgumentList */: + return true; + } + } + + return false; + } + Syntax.isInTypeOnlyContext = isInTypeOnlyContext; + + function childOffset(parent, child) { + var offset = 0; + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return offset; + } + + if (current !== null) { + offset += current.fullWidth(); + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childOffset = childOffset; + + function childOffsetAt(parent, index) { + var offset = 0; + for (var i = 0; i < index; i++) { + var current = parent.childAt(i); + if (current !== null) { + offset += current.fullWidth(); + } + } + + return offset; + } + Syntax.childOffsetAt = childOffsetAt; + + function childIndex(parent, child) { + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return i; + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + + function nodeStructuralEquals(node1, node2) { + if (node1 === null) { + return node2 === null; + } + + return node1.structuralEquals(node2); + } + Syntax.nodeStructuralEquals = nodeStructuralEquals; + + function nodeOrTokenStructuralEquals(node1, node2) { + if (node1 === node2) { + return true; + } + + if (node1 === null || node2 === null) { + return false; + } + + if (node1.isToken()) { + return node2.isToken() ? tokenStructuralEquals(node1, node2) : false; + } + + return node2.isNode() ? nodeStructuralEquals(node1, node2) : false; + } + Syntax.nodeOrTokenStructuralEquals = nodeOrTokenStructuralEquals; + + function tokenStructuralEquals(token1, token2) { + if (token1 === token2) { + return true; + } + + if (token1 === null || token2 === null) { + return false; + } + + return token1.kind() === token2.kind() && token1.width() === token2.width() && token1.fullWidth() === token2.fullWidth() && token1.text() === token2.text() && TypeScript.Syntax.triviaListStructuralEquals(token1.leadingTrivia(), token2.leadingTrivia()) && TypeScript.Syntax.triviaListStructuralEquals(token1.trailingTrivia(), token2.trailingTrivia()); + } + Syntax.tokenStructuralEquals = tokenStructuralEquals; + + function triviaListStructuralEquals(triviaList1, triviaList2) { + if (triviaList1.count() !== triviaList2.count()) { + return false; + } + + for (var i = 0, n = triviaList1.count(); i < n; i++) { + if (!TypeScript.Syntax.triviaStructuralEquals(triviaList1.syntaxTriviaAt(i), triviaList2.syntaxTriviaAt(i))) { + return false; + } + } + + return true; + } + Syntax.triviaListStructuralEquals = triviaListStructuralEquals; + + function triviaStructuralEquals(trivia1, trivia2) { + return trivia1.kind() === trivia2.kind() && trivia1.fullWidth() === trivia2.fullWidth() && trivia1.fullText() === trivia2.fullText(); + } + Syntax.triviaStructuralEquals = triviaStructuralEquals; + + function listStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var child1 = list1.childAt(i); + var child2 = list2.childAt(i); + + if (!TypeScript.Syntax.nodeOrTokenStructuralEquals(child1, child2)) { + return false; + } + } + + return true; + } + Syntax.listStructuralEquals = listStructuralEquals; + + function separatedListStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var element1 = list1.childAt(i); + var element2 = list2.childAt(i); + if (!TypeScript.Syntax.nodeOrTokenStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + } + Syntax.separatedListStructuralEquals = separatedListStructuralEquals; + + function elementStructuralEquals(element1, element2) { + if (element1 === element2) { + return true; + } + + if (element1 === null || element2 === null) { + return false; + } + + if (element2.kind() !== element2.kind()) { + return false; + } + + if (element1.isToken()) { + return tokenStructuralEquals(element1, element2); + } else if (element1.isNode()) { + return nodeStructuralEquals(element1, element2); + } else if (element1.isList()) { + return listStructuralEquals(element1, element2); + } else if (element1.isSeparatedList()) { + return separatedListStructuralEquals(element1, element2); + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.elementStructuralEquals = elementStructuralEquals; + + function identifierName(text, info) { + if (typeof info === "undefined") { info = null; } + return Syntax.identifier(text); + } + Syntax.identifierName = identifierName; + + function trueExpression() { + return TypeScript.Syntax.token(37 /* TrueKeyword */); + } + Syntax.trueExpression = trueExpression; + + function falseExpression() { + return TypeScript.Syntax.token(24 /* FalseKeyword */); + } + Syntax.falseExpression = falseExpression; + + function numericLiteralExpression(text) { + return TypeScript.Syntax.token(13 /* NumericLiteral */, { text: text }); + } + Syntax.numericLiteralExpression = numericLiteralExpression; + + function stringLiteralExpression(text) { + return TypeScript.Syntax.token(14 /* StringLiteral */, { text: text }); + } + Syntax.stringLiteralExpression = stringLiteralExpression; + + function isSuperInvocationExpression(node) { + return node.kind() === 212 /* InvocationExpression */ && (node).expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperInvocationExpression = isSuperInvocationExpression; + + function isSuperInvocationExpressionStatement(node) { + return node.kind() === 148 /* ExpressionStatement */ && isSuperInvocationExpression((node).expression); + } + Syntax.isSuperInvocationExpressionStatement = isSuperInvocationExpressionStatement; + + function isSuperMemberAccessExpression(node) { + return node.kind() === 211 /* MemberAccessExpression */ && (node).expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperMemberAccessExpression = isSuperMemberAccessExpression; + + function isSuperMemberAccessInvocationExpression(node) { + return node.kind() === 212 /* InvocationExpression */ && isSuperMemberAccessExpression((node).expression); + } + Syntax.isSuperMemberAccessInvocationExpression = isSuperMemberAccessInvocationExpression; + + function assignmentExpression(left, token, right) { + return TypeScript.Syntax.normalModeFactory.binaryExpression(173 /* AssignmentExpression */, left, token, right); + } + Syntax.assignmentExpression = assignmentExpression; + + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < node.childCount(); i++) { + var child = node.childAt(i); + if (child !== null && child.isToken()) { + var token = child; + + if (token.hasSkippedToken() || (token.width() === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.token().hasLeadingTrivia()) { + triviaList = positionedToken.token().leadingTrivia(); + } else { + positionedToken = positionedToken.previousToken(); + if (positionedToken) { + if (positionedToken && positionedToken.token().hasTrailingTrivia()) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + } + } else { + if (position <= (fullStart + positionedToken.token().leadingTriviaWidth())) { + triviaList = positionedToken.token().leadingTrivia(); + } else if (position >= (fullStart + positionedToken.token().width())) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + + fullStart += trivia.fullWidth(); + } + } + + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = positionedToken.previousToken(); + return positionedToken && positionedToken.token().trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken.token()); + } else if (position > positionedToken.start()) { + return (position < positionedToken.end() && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= positionedToken.end() && isUnterminatedStringLiteral(positionedToken.token())); + } + } + + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullStart = positionedToken.fullStart(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullStart); + } + + fullStart += triviaWidth; + } + } + + return null; + } + + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + Syntax.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + Syntax.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent()) { + if (positionedToken.parent().kind() === kind) { + return positionedToken.parent(); + } + + positionedToken = positionedToken.parent(); + } + + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + + function hasAncestorOfKind(positionedToken, kind) { + return TypeScript.Syntax.getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDiagnostic = (function (_super) { + __extends(SyntaxDiagnostic, _super); + function SyntaxDiagnostic() { + _super.apply(this, arguments); + } + SyntaxDiagnostic.equals = function (diagnostic1, diagnostic2) { + return TypeScript.Diagnostic.equals(diagnostic1, diagnostic2); + }; + return SyntaxDiagnostic; + })(TypeScript.Diagnostic); + TypeScript.SyntaxDiagnostic = SyntaxDiagnostic; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var NormalModeFactory = (function () { + function NormalModeFactory() { + } + NormalModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, false); + }; + NormalModeFactory.prototype.externalModuleReference = function (moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, false); + }; + NormalModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, false); + }; + NormalModeFactory.prototype.importDeclaration = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + NormalModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, false); + }; + NormalModeFactory.prototype.heritageClause = function (extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, false); + }; + NormalModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, false); + }; + NormalModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, false); + }; + NormalModeFactory.prototype.variableDeclarator = function (identifier, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, false); + }; + NormalModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, false); + }; + NormalModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, false); + }; + NormalModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(false); + }; + NormalModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, false); + }; + NormalModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, body) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, false); + }; + NormalModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, body) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, false); + }; + NormalModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, false); + }; + NormalModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, false); + }; + NormalModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, false); + }; + NormalModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, false); + }; + NormalModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, false); + }; + NormalModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, false); + }; + NormalModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, false); + }; + NormalModeFactory.prototype.parameter = function (dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, false); + }; + NormalModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, false); + }; + NormalModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, false); + }; + NormalModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, false); + }; + NormalModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, false); + }; + NormalModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, false); + }; + NormalModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, false); + }; + NormalModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, false); + }; + NormalModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, false); + }; + NormalModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, false); + }; + NormalModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, false); + }; + NormalModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, false); + }; + NormalModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, false); + }; + NormalModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, false); + }; + NormalModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, false); + }; + NormalModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, false); + }; + NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); + }; + NormalModeFactory.prototype.constructorDeclaration = function (constructorKeyword, parameterList, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, false); + }; + NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.getMemberAccessorDeclaration = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setMemberAccessorDeclaration = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, false); + }; + NormalModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, false); + }; + NormalModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, false); + }; + NormalModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, false); + }; + NormalModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, false); + }; + NormalModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, false); + }; + NormalModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, false); + }; + NormalModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, false); + }; + NormalModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, false); + }; + NormalModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, false); + }; + NormalModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, false); + }; + NormalModeFactory.prototype.getAccessorPropertyAssignment = function (getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block) { + return new TypeScript.GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setAccessorPropertyAssignment = function (setKeyword, propertyName, openParenToken, parameter, closeParenToken, block) { + return new TypeScript.SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, false); + }; + NormalModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, false); + }; + NormalModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, false); + }; + NormalModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, false); + }; + NormalModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, false); + }; + NormalModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, false); + }; + NormalModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, false); + }; + NormalModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, false); + }; + NormalModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, false); + }; + NormalModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, false); + }; + NormalModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, false); + }; + NormalModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, false); + }; + return NormalModeFactory; + })(); + Syntax.NormalModeFactory = NormalModeFactory; + + var StrictModeFactory = (function () { + function StrictModeFactory() { + } + StrictModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, true); + }; + StrictModeFactory.prototype.externalModuleReference = function (moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, true); + }; + StrictModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, true); + }; + StrictModeFactory.prototype.importDeclaration = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, true); + }; + StrictModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, true); + }; + StrictModeFactory.prototype.heritageClause = function (extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, true); + }; + StrictModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, true); + }; + StrictModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, true); + }; + StrictModeFactory.prototype.variableDeclarator = function (identifier, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, true); + }; + StrictModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, true); + }; + StrictModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, true); + }; + StrictModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(true); + }; + StrictModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, true); + }; + StrictModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, body) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, true); + }; + StrictModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, body) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, true); + }; + StrictModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, true); + }; + StrictModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, true); + }; + StrictModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, true); + }; + StrictModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, true); + }; + StrictModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, true); + }; + StrictModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, true); + }; + StrictModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, true); + }; + StrictModeFactory.prototype.parameter = function (dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, true); + }; + StrictModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, true); + }; + StrictModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, true); + }; + StrictModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, true); + }; + StrictModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, true); + }; + StrictModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, true); + }; + StrictModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, true); + }; + StrictModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, true); + }; + StrictModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, true); + }; + StrictModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, true); + }; + StrictModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, true); + }; + StrictModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, true); + }; + StrictModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, true); + }; + StrictModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, true); + }; + StrictModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, true); + }; + StrictModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, true); + }; + StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); + }; + StrictModeFactory.prototype.constructorDeclaration = function (constructorKeyword, parameterList, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, true); + }; + StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.getMemberAccessorDeclaration = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setMemberAccessorDeclaration = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, true); + }; + StrictModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, true); + }; + StrictModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, true); + }; + StrictModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, true); + }; + StrictModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, true); + }; + StrictModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, true); + }; + StrictModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, true); + }; + StrictModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, true); + }; + StrictModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, true); + }; + StrictModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, true); + }; + StrictModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, true); + }; + StrictModeFactory.prototype.getAccessorPropertyAssignment = function (getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block) { + return new TypeScript.GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setAccessorPropertyAssignment = function (setKeyword, propertyName, openParenToken, parameter, closeParenToken, block) { + return new TypeScript.SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, true); + }; + StrictModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, true); + }; + StrictModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, true); + }; + StrictModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, true); + }; + StrictModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, true); + }; + StrictModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, true); + }; + StrictModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, true); + }; + StrictModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, true); + }; + StrictModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, true); + }; + StrictModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, true); + }; + StrictModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, true); + }; + StrictModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, true); + }; + return StrictModeFactory; + })(); + Syntax.StrictModeFactory = StrictModeFactory; + + Syntax.normalModeFactory = new NormalModeFactory(); + Syntax.strictModeFactory = new StrictModeFactory(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["BoolKeyword"] = 62] = "BoolKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 63] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 64] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 65] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 66] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 67] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 68] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 69] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 70] = "StringKeyword"; + + SyntaxKind[SyntaxKind["OpenBraceToken"] = 71] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 72] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 73] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 74] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 75] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 76] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 77] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 78] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 79] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 80] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 81] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 82] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 83] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 84] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 85] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 86] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 87] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 88] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 89] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 90] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 91] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 92] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 93] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 94] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 95] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 96] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 98] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 99] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 100] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 101] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 102] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 103] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 104] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 105] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 106] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 107] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 108] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 109] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 110] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 111] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 112] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 113] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 115] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 116] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 117] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 118] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 119] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 120] = "SlashEqualsToken"; + + SyntaxKind[SyntaxKind["SourceUnit"] = 121] = "SourceUnit"; + + SyntaxKind[SyntaxKind["QualifiedName"] = 122] = "QualifiedName"; + + SyntaxKind[SyntaxKind["ObjectType"] = 123] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 124] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 125] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 126] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 127] = "GenericType"; + + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["GetMemberAccessorDeclaration"] = 138] = "GetMemberAccessorDeclaration"; + SyntaxKind[SyntaxKind["SetMemberAccessorDeclaration"] = 139] = "SetMemberAccessorDeclaration"; + + SyntaxKind[SyntaxKind["PropertySignature"] = 140] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 141] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 142] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 143] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 144] = "MethodSignature"; + + SyntaxKind[SyntaxKind["Block"] = 145] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 146] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 147] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 148] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 149] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 150] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 151] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 152] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 153] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 154] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 155] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 156] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 157] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 158] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 159] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 160] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 161] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 162] = "WithStatement"; + + SyntaxKind[SyntaxKind["PlusExpression"] = 163] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 164] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 165] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 166] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 167] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 168] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 169] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 170] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 171] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 172] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 173] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 174] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 175] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 176] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 177] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 178] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 179] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 180] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 181] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 182] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 183] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 184] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 185] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 186] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 187] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 188] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 189] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 190] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 191] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 192] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 193] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 194] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 195] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 196] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 197] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 198] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 199] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 200] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 201] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 202] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 203] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 204] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 205] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 206] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 207] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 208] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 209] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 210] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 211] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 212] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 213] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 214] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 215] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 216] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 217] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 218] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 219] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 220] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 221] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; + + SyntaxKind[SyntaxKind["VariableDeclaration"] = 223] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 224] = "VariableDeclarator"; + + SyntaxKind[SyntaxKind["ArgumentList"] = 225] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 226] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 227] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 228] = "TypeParameterList"; + + SyntaxKind[SyntaxKind["HeritageClause"] = 229] = "HeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 230] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 231] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 232] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 233] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 234] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 235] = "FinallyClause"; + + SyntaxKind[SyntaxKind["TypeParameter"] = 236] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 237] = "Constraint"; + + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 238] = "SimplePropertyAssignment"; + SyntaxKind[SyntaxKind["GetAccessorPropertyAssignment"] = 239] = "GetAccessorPropertyAssignment"; + SyntaxKind[SyntaxKind["SetAccessorPropertyAssignment"] = 240] = "SetAccessorPropertyAssignment"; + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "bool": 62 /* BoolKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 63 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 64 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 65 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 66 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 68 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 67 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 69 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 70 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 71 /* OpenBraceToken */, + "}": 72 /* CloseBraceToken */, + "(": 73 /* OpenParenToken */, + ")": 74 /* CloseParenToken */, + "[": 75 /* OpenBracketToken */, + "]": 76 /* CloseBracketToken */, + ".": 77 /* DotToken */, + "...": 78 /* DotDotDotToken */, + ";": 79 /* SemicolonToken */, + ",": 80 /* CommaToken */, + "<": 81 /* LessThanToken */, + ">": 82 /* GreaterThanToken */, + "<=": 83 /* LessThanEqualsToken */, + ">=": 84 /* GreaterThanEqualsToken */, + "==": 85 /* EqualsEqualsToken */, + "=>": 86 /* EqualsGreaterThanToken */, + "!=": 87 /* ExclamationEqualsToken */, + "===": 88 /* EqualsEqualsEqualsToken */, + "!==": 89 /* ExclamationEqualsEqualsToken */, + "+": 90 /* PlusToken */, + "-": 91 /* MinusToken */, + "*": 92 /* AsteriskToken */, + "%": 93 /* PercentToken */, + "++": 94 /* PlusPlusToken */, + "--": 95 /* MinusMinusToken */, + "<<": 96 /* LessThanLessThanToken */, + ">>": 97 /* GreaterThanGreaterThanToken */, + ">>>": 98 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 99 /* AmpersandToken */, + "|": 100 /* BarToken */, + "^": 101 /* CaretToken */, + "!": 102 /* ExclamationToken */, + "~": 103 /* TildeToken */, + "&&": 104 /* AmpersandAmpersandToken */, + "||": 105 /* BarBarToken */, + "?": 106 /* QuestionToken */, + ":": 107 /* ColonToken */, + "=": 108 /* EqualsToken */, + "+=": 109 /* PlusEqualsToken */, + "-=": 110 /* MinusEqualsToken */, + "*=": 111 /* AsteriskEqualsToken */, + "%=": 112 /* PercentEqualsToken */, + "<<=": 113 /* LessThanLessThanEqualsToken */, + ">>=": 114 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 116 /* AmpersandEqualsToken */, + "|=": 117 /* BarEqualsToken */, + "^=": 118 /* CaretEqualsToken */, + "/": 119 /* SlashToken */, + "/=": 120 /* SlashEqualsToken */ + }; + + var kindToText = []; + + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + + kindToText[63 /* ConstructorKeyword */] = "constructor"; + + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + + function isTokenKind(kind) { + return kind >= 9 /* FirstToken */ && kind <= 120 /* LastToken */; + } + SyntaxFacts.isTokenKind = isTokenKind; + + function isAnyKeyword(kind) { + return kind >= TypeScript.SyntaxKind.FirstKeyword && kind <= TypeScript.SyntaxKind.LastKeyword; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + + function isStandardKeyword(kind) { + return kind >= 15 /* FirstStandardKeyword */ && kind <= 43 /* LastStandardKeyword */; + } + SyntaxFacts.isStandardKeyword = isStandardKeyword; + + function isFutureReservedKeyword(kind) { + return kind >= 44 /* FirstFutureReservedKeyword */ && kind <= 50 /* LastFutureReservedKeyword */; + } + SyntaxFacts.isFutureReservedKeyword = isFutureReservedKeyword; + + function isFutureReservedStrictKeyword(kind) { + return kind >= 51 /* FirstFutureReservedStrictKeyword */ && kind <= 59 /* LastFutureReservedStrictKeyword */; + } + SyntaxFacts.isFutureReservedStrictKeyword = isFutureReservedStrictKeyword; + + function isAnyPunctuation(kind) { + return kind >= 71 /* FirstPunctuation */ && kind <= 120 /* LastPunctuation */; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 90 /* PlusToken */: + return 163 /* PlusExpression */; + case 91 /* MinusToken */: + return 164 /* NegateExpression */; + case 103 /* TildeToken */: + return 165 /* BitwiseNotExpression */; + case 102 /* ExclamationToken */: + return 166 /* LogicalNotExpression */; + case 94 /* PlusPlusToken */: + return 167 /* PreIncrementExpression */; + case 95 /* MinusMinusToken */: + return 168 /* PreDecrementExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 94 /* PlusPlusToken */: + return 209 /* PostIncrementExpression */; + case 95 /* MinusMinusToken */: + return 210 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 92 /* AsteriskToken */: + return 204 /* MultiplyExpression */; + + case 119 /* SlashToken */: + return 205 /* DivideExpression */; + + case 93 /* PercentToken */: + return 206 /* ModuloExpression */; + + case 90 /* PlusToken */: + return 207 /* AddExpression */; + + case 91 /* MinusToken */: + return 208 /* SubtractExpression */; + + case 96 /* LessThanLessThanToken */: + return 201 /* LeftShiftExpression */; + + case 97 /* GreaterThanGreaterThanToken */: + return 202 /* SignedRightShiftExpression */; + + case 98 /* GreaterThanGreaterThanGreaterThanToken */: + return 203 /* UnsignedRightShiftExpression */; + + case 81 /* LessThanToken */: + return 195 /* LessThanExpression */; + + case 82 /* GreaterThanToken */: + return 196 /* GreaterThanExpression */; + + case 83 /* LessThanEqualsToken */: + return 197 /* LessThanOrEqualExpression */; + + case 84 /* GreaterThanEqualsToken */: + return 198 /* GreaterThanOrEqualExpression */; + + case 30 /* InstanceOfKeyword */: + return 199 /* InstanceOfExpression */; + + case 29 /* InKeyword */: + return 200 /* InExpression */; + + case 85 /* EqualsEqualsToken */: + return 191 /* EqualsWithTypeConversionExpression */; + + case 87 /* ExclamationEqualsToken */: + return 192 /* NotEqualsWithTypeConversionExpression */; + + case 88 /* EqualsEqualsEqualsToken */: + return 193 /* EqualsExpression */; + + case 89 /* ExclamationEqualsEqualsToken */: + return 194 /* NotEqualsExpression */; + + case 99 /* AmpersandToken */: + return 190 /* BitwiseAndExpression */; + + case 101 /* CaretToken */: + return 189 /* BitwiseExclusiveOrExpression */; + + case 100 /* BarToken */: + return 188 /* BitwiseOrExpression */; + + case 104 /* AmpersandAmpersandToken */: + return 187 /* LogicalAndExpression */; + + case 105 /* BarBarToken */: + return 186 /* LogicalOrExpression */; + + case 117 /* BarEqualsToken */: + return 181 /* OrAssignmentExpression */; + + case 116 /* AmpersandEqualsToken */: + return 179 /* AndAssignmentExpression */; + + case 118 /* CaretEqualsToken */: + return 180 /* ExclusiveOrAssignmentExpression */; + + case 113 /* LessThanLessThanEqualsToken */: + return 182 /* LeftShiftAssignmentExpression */; + + case 114 /* GreaterThanGreaterThanEqualsToken */: + return 183 /* SignedRightShiftAssignmentExpression */; + + case 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 184 /* UnsignedRightShiftAssignmentExpression */; + + case 109 /* PlusEqualsToken */: + return 174 /* AddAssignmentExpression */; + + case 110 /* MinusEqualsToken */: + return 175 /* SubtractAssignmentExpression */; + + case 111 /* AsteriskEqualsToken */: + return 176 /* MultiplyAssignmentExpression */; + + case 120 /* SlashEqualsToken */: + return 177 /* DivideAssignmentExpression */; + + case 112 /* PercentEqualsToken */: + return 178 /* ModuloAssignmentExpression */; + + case 108 /* EqualsToken */: + return 173 /* AssignmentExpression */; + + case 80 /* CommaToken */: + return 172 /* CommaExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + + function isAnyDivideToken(kind) { + switch (kind) { + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideToken = isAnyDivideToken; + + function isAnyDivideOrRegularExpressionToken(kind) { + switch (kind) { + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + case 12 /* RegularExpressionLiteral */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideOrRegularExpressionToken = isAnyDivideOrRegularExpressionToken; + + function isParserGenerated(kind) { + switch (kind) { + case 97 /* GreaterThanGreaterThanToken */: + case 98 /* GreaterThanGreaterThanGreaterThanToken */: + case 84 /* GreaterThanEqualsToken */: + case 114 /* GreaterThanGreaterThanEqualsToken */: + case 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isParserGenerated = isParserGenerated; + + function isAnyBinaryExpression(kind) { + switch (kind) { + case 172 /* CommaExpression */: + case 173 /* AssignmentExpression */: + case 174 /* AddAssignmentExpression */: + case 175 /* SubtractAssignmentExpression */: + case 176 /* MultiplyAssignmentExpression */: + case 177 /* DivideAssignmentExpression */: + case 178 /* ModuloAssignmentExpression */: + case 179 /* AndAssignmentExpression */: + case 180 /* ExclusiveOrAssignmentExpression */: + case 181 /* OrAssignmentExpression */: + case 182 /* LeftShiftAssignmentExpression */: + case 183 /* SignedRightShiftAssignmentExpression */: + case 184 /* UnsignedRightShiftAssignmentExpression */: + case 186 /* LogicalOrExpression */: + case 187 /* LogicalAndExpression */: + case 188 /* BitwiseOrExpression */: + case 189 /* BitwiseExclusiveOrExpression */: + case 190 /* BitwiseAndExpression */: + case 191 /* EqualsWithTypeConversionExpression */: + case 192 /* NotEqualsWithTypeConversionExpression */: + case 193 /* EqualsExpression */: + case 194 /* NotEqualsExpression */: + case 195 /* LessThanExpression */: + case 196 /* GreaterThanExpression */: + case 197 /* LessThanOrEqualExpression */: + case 198 /* GreaterThanOrEqualExpression */: + case 199 /* InstanceOfExpression */: + case 200 /* InExpression */: + case 201 /* LeftShiftExpression */: + case 202 /* SignedRightShiftExpression */: + case 203 /* UnsignedRightShiftExpression */: + case 204 /* MultiplyExpression */: + case 205 /* DivideExpression */: + case 206 /* ModuloExpression */: + case 207 /* AddExpression */: + case 208 /* SubtractExpression */: + return true; + } + + return false; + } + SyntaxFacts.isAnyBinaryExpression = isAnyBinaryExpression; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 148 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.tokenKind; + return tokenKind === 11 /* IdentifierName */ || TypeScript.SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySyntaxList = (function () { + function EmptySyntaxList() { + } + EmptySyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + EmptySyntaxList.prototype.isNode = function () { + return false; + }; + EmptySyntaxList.prototype.isToken = function () { + return false; + }; + EmptySyntaxList.prototype.isList = function () { + return true; + }; + EmptySyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + EmptySyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.width = function () { + return 0; + }; + + EmptySyntaxList.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + return EmptySyntaxList; + })(); + Syntax.EmptySyntaxList = EmptySyntaxList; + + Syntax.emptyList = new EmptySyntaxList(); + + var SingletonSyntaxList = (function () { + function SingletonSyntaxList(item) { + this.item = item; + } + SingletonSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + SingletonSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSyntaxList.prototype.isList = function () { + return true; + }; + SingletonSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + SingletonSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxList.prototype.childCount = function () { + return 1; + }; + + SingletonSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return (this.item).findTokenInternal(new TypeScript.PositionedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSyntaxList; + })(); + + var NormalSyntaxList = (function () { + function NormalSyntaxList(nodeOrTokens) { + this._data = 0; + this.nodeOrTokens = nodeOrTokens; + } + NormalSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + NormalSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSyntaxList.prototype.isList = function () { + return true; + }; + NormalSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + NormalSyntaxList.prototype.toJSON = function (key) { + return this.nodeOrTokens; + }; + + NormalSyntaxList.prototype.childCount = function () { + return this.nodeOrTokens.length; + }; + + NormalSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.nodeOrTokens.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.nodeOrTokens[index]; + }; + + NormalSyntaxList.prototype.toArray = function () { + return this.nodeOrTokens.slice(0); + }; + + NormalSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var element = this.nodeOrTokens[i]; + element.collectTextElements(elements); + } + }; + + NormalSyntaxList.prototype.firstToken = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var token = this.nodeOrTokens[i].firstToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.lastToken = function () { + for (var i = this.nodeOrTokens.length - 1; i >= 0; i--) { + var token = this.nodeOrTokens[i].lastToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + if (this.nodeOrTokens[i].isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var node = this.nodeOrTokens[i]; + fullWidth += node.fullWidth(); + isIncrementallyUnusable = isIncrementallyUnusable || node.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedList(parent, this, fullStart); + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var nodeOrToken = this.nodeOrTokens[i]; + + var childWidth = nodeOrToken.fullWidth(); + if (position < childWidth) { + return (nodeOrToken).findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.nodeOrTokens); + } else { + array.splice.apply(array, [index, 0].concat(this.nodeOrTokens)); + } + }; + return NormalSyntaxList; + })(); + + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptyList; + } + + if (nodes.length === 1) { + var item = nodes[0]; + return new SingletonSyntaxList(item); + } + + return new NormalSyntaxList(nodes); + } + Syntax.list = list; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(parsedInStrictMode) { + this._data = parsedInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + SyntaxNode.prototype.isNode = function () { + return true; + }; + SyntaxNode.prototype.isToken = function () { + return false; + }; + SyntaxNode.prototype.isList = function () { + return false; + }; + SyntaxNode.prototype.isSeparatedList = function () { + return false; + }; + + SyntaxNode.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childCount = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childAt = function (slot) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.firstToken = function () { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.firstToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.lastToken = function () { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.lastToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.insertChildrenInto = function (array, index) { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.isNode() || element.isToken()) { + array.splice(index, 0, element); + } else if (element.isList()) { + (element).insertChildrenInto(array, index); + } else if (element.isSeparatedList()) { + (element).insertChildrenInto(array, index); + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + } + }; + + SyntaxNode.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + SyntaxNode.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + SyntaxNode.prototype.toJSON = function (key) { + var result = { + kind: TypeScript.SyntaxKind[this.kind()], + fullWidth: this.fullWidth() + }; + + if (this.isIncrementallyUnusable()) { + result.isIncrementallyUnusable = true; + } + + if (this.parsedInStrictMode()) { + result.parsedInStrictMode = true; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var value = this.childAt(i); + + if (value) { + for (var name in this) { + if (value === this[name]) { + result[name] = value; + break; + } + } + } + } + + return result; + }; + + SyntaxNode.prototype.accept = function (visitor) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + SyntaxNode.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + element.collectTextElements(elements); + } + } + }; + + SyntaxNode.prototype.replaceToken = function (token1, token2) { + if (token1 === token2) { + return this; + } + + return this.accept(new TypeScript.SyntaxTokenReplacer(token1, token2)); + }; + + SyntaxNode.prototype.withLeadingTrivia = function (trivia) { + return this.replaceToken(this.firstToken(), this.firstToken().withLeadingTrivia(trivia)); + }; + + SyntaxNode.prototype.withTrailingTrivia = function (trivia) { + return this.replaceToken(this.lastToken(), this.lastToken().withTrailingTrivia(trivia)); + }; + + SyntaxNode.prototype.hasLeadingTrivia = function () { + return this.lastToken().hasLeadingTrivia(); + }; + + SyntaxNode.prototype.hasTrailingTrivia = function () { + return this.lastToken().hasTrailingTrivia(); + }; + + SyntaxNode.prototype.isTypeScriptSpecific = function () { + return false; + }; + + SyntaxNode.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + SyntaxNode.prototype.parsedInStrictMode = function () { + return (this.data() & 4 /* NodeParsedInStrictModeMask */) !== 0; + }; + + SyntaxNode.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + SyntaxNode.prototype.computeData = function () { + var slotCount = this.childCount(); + + var fullWidth = 0; + var childWidth = 0; + + var isIncrementallyUnusable = ((this._data & 2 /* NodeIncrementallyUnusableMask */) !== 0) || slotCount === 0; + + for (var i = 0, n = slotCount; i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + childWidth = element.fullWidth(); + fullWidth += childWidth; + + if (!isIncrementallyUnusable) { + isIncrementallyUnusable = element.isIncrementallyUnusable(); + } + } + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + SyntaxNode.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data |= this.computeData(); + } + + return this._data; + }; + + SyntaxNode.prototype.findToken = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var endOfFileToken = this.tryGetEndOfFileAt(position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + + if (position < 0 || position >= this.fullWidth()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var positionedToken = this.findTokenInternal(null, position, 0); + + if (includeSkippedTokens) { + return TypeScript.Syntax.findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + + return positionedToken; + }; + + SyntaxNode.prototype.tryGetEndOfFileAt = function (position) { + if (this.kind() === 121 /* SourceUnit */ && position === this.fullWidth()) { + var sourceUnit = this; + return new TypeScript.PositionedToken(new TypeScript.PositionedNode(null, sourceUnit, 0), sourceUnit.endOfFileToken, sourceUnit.moduleElements.fullWidth()); + } + + return null; + }; + + SyntaxNode.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedNode(parent, this, fullStart); + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + var childWidth = element.fullWidth(); + + if (position < childWidth) { + return (element).findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxNode.prototype.findTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, includeSkippedTokens); + var start = positionedToken.start(); + + if (position > start) { + return positionedToken; + } + + if (positionedToken.fullStart() === 0) { + return null; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.findCompleteTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, includeSkippedTokens); + + if (positionedToken.token().width() > 0 && position >= positionedToken.end()) { + return positionedToken; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.isModuleElement = function () { + return false; + }; + + SyntaxNode.prototype.isClassElement = function () { + return false; + }; + + SyntaxNode.prototype.isTypeMember = function () { + return false; + }; + + SyntaxNode.prototype.isStatement = function () { + return false; + }; + + SyntaxNode.prototype.isSwitchClause = function () { + return false; + }; + + SyntaxNode.prototype.structuralEquals = function (node) { + if (this === node) { + return true; + } + if (node === null) { + return false; + } + if (this.kind() !== node.kind()) { + return false; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var element1 = this.childAt(i); + var element2 = node.childAt(i); + + if (!TypeScript.Syntax.elementStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + }; + + SyntaxNode.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + SyntaxNode.prototype.leadingTriviaWidth = function () { + var firstToken = this.firstToken(); + return firstToken === null ? 0 : firstToken.leadingTriviaWidth(); + }; + + SyntaxNode.prototype.trailingTriviaWidth = function () { + var lastToken = this.lastToken(); + return lastToken === null ? 0 : lastToken.trailingTriviaWidth(); + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(moduleElements, endOfFileToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleElements = moduleElements; + this.endOfFileToken = endOfFileToken; + } + SourceUnitSyntax.prototype.accept = function (visitor) { + return visitor.visitSourceUnit(this); + }; + + SourceUnitSyntax.prototype.kind = function () { + return 121 /* SourceUnit */; + }; + + SourceUnitSyntax.prototype.childCount = function () { + return 2; + }; + + SourceUnitSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleElements; + case 1: + return this.endOfFileToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SourceUnitSyntax.prototype.update = function (moduleElements, endOfFileToken) { + if (this.moduleElements === moduleElements && this.endOfFileToken === endOfFileToken) { + return this; + } + + return new SourceUnitSyntax(moduleElements, endOfFileToken, this.parsedInStrictMode()); + }; + + SourceUnitSyntax.create = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.create1 = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(moduleElements, this.endOfFileToken); + }; + + SourceUnitSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + SourceUnitSyntax.prototype.withEndOfFileToken = function (endOfFileToken) { + return this.update(this.moduleElements, endOfFileToken); + }; + + SourceUnitSyntax.prototype.isTypeScriptSpecific = function () { + if (this.moduleElements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SourceUnitSyntax = SourceUnitSyntax; + + var ModuleReferenceSyntax = (function (_super) { + __extends(ModuleReferenceSyntax, _super); + function ModuleReferenceSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + ModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleReferenceSyntax = ModuleReferenceSyntax; + + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleOrRequireKeyword = moduleOrRequireKeyword; + this.openParenToken = openParenToken; + this.stringLiteral = stringLiteral; + this.closeParenToken = closeParenToken; + } + ExternalModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitExternalModuleReference(this); + }; + + ExternalModuleReferenceSyntax.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + + ExternalModuleReferenceSyntax.prototype.childCount = function () { + return 4; + }; + + ExternalModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleOrRequireKeyword; + case 1: + return this.openParenToken; + case 2: + return this.stringLiteral; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExternalModuleReferenceSyntax.prototype.update = function (moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken) { + if (this.moduleOrRequireKeyword === moduleOrRequireKeyword && this.openParenToken === openParenToken && this.stringLiteral === stringLiteral && this.closeParenToken === closeParenToken) { + return this; + } + + return new ExternalModuleReferenceSyntax(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken, this.parsedInStrictMode()); + }; + + ExternalModuleReferenceSyntax.create1 = function (moduleOrRequireKeyword, stringLiteral) { + return new ExternalModuleReferenceSyntax(moduleOrRequireKeyword, TypeScript.Syntax.token(73 /* OpenParenToken */), stringLiteral, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ExternalModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withModuleOrRequireKeyword = function (moduleOrRequireKeyword) { + return this.update(moduleOrRequireKeyword, this.openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.moduleOrRequireKeyword, openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.moduleOrRequireKeyword, this.openParenToken, stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.moduleOrRequireKeyword, this.openParenToken, this.stringLiteral, closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExternalModuleReferenceSyntax; + })(ModuleReferenceSyntax); + TypeScript.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(moduleName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleName = moduleName; + } + ModuleNameModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleNameModuleReference(this); + }; + + ModuleNameModuleReferenceSyntax.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + + ModuleNameModuleReferenceSyntax.prototype.childCount = function () { + return 1; + }; + + ModuleNameModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleName; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleNameModuleReferenceSyntax.prototype.update = function (moduleName) { + if (this.moduleName === moduleName) { + return this; + } + + return new ModuleNameModuleReferenceSyntax(moduleName, this.parsedInStrictMode()); + }; + + ModuleNameModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withModuleName = function (moduleName) { + return this.update(moduleName); + }; + + ModuleNameModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleNameModuleReferenceSyntax; + })(ModuleReferenceSyntax); + TypeScript.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.importKeyword = importKeyword; + this.identifier = identifier; + this.equalsToken = equalsToken; + this.moduleReference = moduleReference; + this.semicolonToken = semicolonToken; + } + ImportDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitImportDeclaration(this); + }; + + ImportDeclarationSyntax.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + ImportDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.importKeyword; + case 1: + return this.identifier; + case 2: + return this.equalsToken; + case 3: + return this.moduleReference; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ImportDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ImportDeclarationSyntax.prototype.update = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + if (this.importKeyword === importKeyword && this.identifier === identifier && this.equalsToken === equalsToken && this.moduleReference === moduleReference && this.semicolonToken === semicolonToken) { + return this; + } + + return new ImportDeclarationSyntax(importKeyword, identifier, equalsToken, moduleReference, semicolonToken, this.parsedInStrictMode()); + }; + + ImportDeclarationSyntax.create1 = function (identifier, moduleReference) { + return new ImportDeclarationSyntax(TypeScript.Syntax.token(49 /* ImportKeyword */), identifier, TypeScript.Syntax.token(108 /* EqualsToken */), moduleReference, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ImportDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withImportKeyword = function (importKeyword) { + return this.update(importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.importKeyword, identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.importKeyword, this.identifier, equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModuleReference = function (moduleReference) { + return this.update(this.importKeyword, this.identifier, this.equalsToken, moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, semicolonToken); + }; + + ImportDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ImportDeclarationSyntax = ImportDeclarationSyntax; + + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.exportKeyword = exportKeyword; + this.equalsToken = equalsToken; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ExportAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitExportAssignment(this); + }; + + ExportAssignmentSyntax.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignmentSyntax.prototype.childCount = function () { + return 4; + }; + + ExportAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.exportKeyword; + case 1: + return this.equalsToken; + case 2: + return this.identifier; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExportAssignmentSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExportAssignmentSyntax.prototype.update = function (exportKeyword, equalsToken, identifier, semicolonToken) { + if (this.exportKeyword === exportKeyword && this.equalsToken === equalsToken && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ExportAssignmentSyntax.create1 = function (identifier) { + return new ExportAssignmentSyntax(TypeScript.Syntax.token(47 /* ExportKeyword */), TypeScript.Syntax.token(108 /* EqualsToken */), identifier, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ExportAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withExportKeyword = function (exportKeyword) { + return this.update(exportKeyword, this.equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.exportKeyword, equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.exportKeyword, this.equalsToken, identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.exportKeyword, this.equalsToken, this.identifier, semicolonToken); + }; + + ExportAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExportAssignmentSyntax = ExportAssignmentSyntax; + + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.classKeyword = classKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.openBraceToken = openBraceToken; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + } + ClassDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitClassDeclaration(this); + }; + + ClassDeclarationSyntax.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclarationSyntax.prototype.childCount = function () { + return 8; + }; + + ClassDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.classKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.openBraceToken; + case 6: + return this.classElements; + case 7: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ClassDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ClassDeclarationSyntax.prototype.update = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + if (this.modifiers === modifiers && this.classKeyword === classKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.openBraceToken === openBraceToken && this.classElements === classElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ClassDeclarationSyntax.create = function (classKeyword, identifier, openBraceToken, closeBraceToken) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, classKeyword, identifier, null, TypeScript.Syntax.emptyList, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ClassDeclarationSyntax.create1 = function (identifier) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(44 /* ClassKeyword */), identifier, null, TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ClassDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ClassDeclarationSyntax.prototype.withClassKeyword = function (classKeyword) { + return this.update(this.modifiers, classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.classKeyword, identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.classKeyword, this.identifier, typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + ClassDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElements = function (classElements) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElement = function (classElement) { + return this.withClassElements(TypeScript.Syntax.list([classElement])); + }; + + ClassDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ClassDeclarationSyntax = ClassDeclarationSyntax; + + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.interfaceKeyword = interfaceKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + } + InterfaceDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitInterfaceDeclaration(this); + }; + + InterfaceDeclarationSyntax.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + InterfaceDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.interfaceKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InterfaceDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + InterfaceDeclarationSyntax.prototype.update = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + if (this.modifiers === modifiers && this.interfaceKeyword === interfaceKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.body === body) { + return this; + } + + return new InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, this.parsedInStrictMode()); + }; + + InterfaceDeclarationSyntax.create = function (interfaceKeyword, identifier, body) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, interfaceKeyword, identifier, null, TypeScript.Syntax.emptyList, body, false); + }; + + InterfaceDeclarationSyntax.create1 = function (identifier) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(52 /* InterfaceKeyword */), identifier, null, TypeScript.Syntax.emptyList, ObjectTypeSyntax.create1(), false); + }; + + InterfaceDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + InterfaceDeclarationSyntax.prototype.withInterfaceKeyword = function (interfaceKeyword) { + return this.update(this.modifiers, interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.interfaceKeyword, identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + InterfaceDeclarationSyntax.prototype.withBody = function (body) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, body); + }; + + InterfaceDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword; + this.typeNames = typeNames; + } + HeritageClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitHeritageClause(this); + }; + + HeritageClauseSyntax.prototype.kind = function () { + return 229 /* HeritageClause */; + }; + + HeritageClauseSyntax.prototype.childCount = function () { + return 2; + }; + + HeritageClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsOrImplementsKeyword; + case 1: + return this.typeNames; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + HeritageClauseSyntax.prototype.update = function (extendsOrImplementsKeyword, typeNames) { + if (this.extendsOrImplementsKeyword === extendsOrImplementsKeyword && this.typeNames === typeNames) { + return this; + } + + return new HeritageClauseSyntax(extendsOrImplementsKeyword, typeNames, this.parsedInStrictMode()); + }; + + HeritageClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withExtendsOrImplementsKeyword = function (extendsOrImplementsKeyword) { + return this.update(extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeNames = function (typeNames) { + return this.update(this.extendsOrImplementsKeyword, typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeName = function (typeName) { + return this.withTypeNames(TypeScript.Syntax.separatedList([typeName])); + }; + + HeritageClauseSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.HeritageClauseSyntax = HeritageClauseSyntax; + + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.moduleKeyword = moduleKeyword; + this.moduleName = moduleName; + this.stringLiteral = stringLiteral; + this.openBraceToken = openBraceToken; + this.moduleElements = moduleElements; + this.closeBraceToken = closeBraceToken; + } + ModuleDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleDeclaration(this); + }; + + ModuleDeclarationSyntax.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclarationSyntax.prototype.childCount = function () { + return 7; + }; + + ModuleDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.moduleKeyword; + case 2: + return this.moduleName; + case 3: + return this.stringLiteral; + case 4: + return this.openBraceToken; + case 5: + return this.moduleElements; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ModuleDeclarationSyntax.prototype.update = function (modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + if (this.modifiers === modifiers && this.moduleKeyword === moduleKeyword && this.moduleName === moduleName && this.stringLiteral === stringLiteral && this.openBraceToken === openBraceToken && this.moduleElements === moduleElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ModuleDeclarationSyntax(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ModuleDeclarationSyntax.create = function (moduleKeyword, openBraceToken, closeBraceToken) { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, moduleKeyword, null, null, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ModuleDeclarationSyntax.create1 = function () { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(66 /* ModuleKeyword */), null, null, TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ModuleDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ModuleDeclarationSyntax.prototype.withModuleKeyword = function (moduleKeyword) { + return this.update(this.modifiers, moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleName = function (moduleName) { + return this.update(this.modifiers, this.moduleKeyword, moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + ModuleDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.moduleName, this.stringLiteral, this.openBraceToken, this.moduleElements, closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + FunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionDeclaration(this); + }; + + FunctionDeclarationSyntax.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + FunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.functionKeyword; + case 2: + return this.identifier; + case 3: + return this.callSignature; + case 4: + return this.block; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionDeclarationSyntax.prototype.isStatement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.update = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + FunctionDeclarationSyntax.create = function (functionKeyword, identifier, callSignature) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, functionKeyword, identifier, callSignature, null, null, false); + }; + + FunctionDeclarationSyntax.create1 = function (identifier) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(27 /* FunctionKeyword */), identifier, CallSignatureSyntax.create1(), null, null, false); + }; + + FunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + FunctionDeclarationSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(this.modifiers, functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.functionKeyword, identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block !== null && this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclaration = variableDeclaration; + this.semicolonToken = semicolonToken; + } + VariableStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableStatement(this); + }; + + VariableStatementSyntax.prototype.kind = function () { + return 147 /* VariableStatement */; + }; + + VariableStatementSyntax.prototype.childCount = function () { + return 3; + }; + + VariableStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclaration; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableStatementSyntax.prototype.isStatement = function () { + return true; + }; + + VariableStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + VariableStatementSyntax.prototype.update = function (modifiers, variableDeclaration, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclaration === variableDeclaration && this.semicolonToken === semicolonToken) { + return this; + } + + return new VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, this.parsedInStrictMode()); + }; + + VariableStatementSyntax.create = function (variableDeclaration, semicolonToken) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, semicolonToken, false); + }; + + VariableStatementSyntax.create1 = function (variableDeclaration) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + VariableStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + VariableStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.modifiers, variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclaration, semicolonToken); + }; + + VariableStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableStatementSyntax = VariableStatementSyntax; + + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(varKeyword, variableDeclarators, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.varKeyword = varKeyword; + this.variableDeclarators = variableDeclarators; + } + VariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclaration(this); + }; + + VariableDeclarationSyntax.prototype.kind = function () { + return 223 /* VariableDeclaration */; + }; + + VariableDeclarationSyntax.prototype.childCount = function () { + return 2; + }; + + VariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.varKeyword; + case 1: + return this.variableDeclarators; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclarationSyntax.prototype.update = function (varKeyword, variableDeclarators) { + if (this.varKeyword === varKeyword && this.variableDeclarators === variableDeclarators) { + return this; + } + + return new VariableDeclarationSyntax(varKeyword, variableDeclarators, this.parsedInStrictMode()); + }; + + VariableDeclarationSyntax.create1 = function (variableDeclarators) { + return new VariableDeclarationSyntax(TypeScript.Syntax.token(40 /* VarKeyword */), variableDeclarators, false); + }; + + VariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withVarKeyword = function (varKeyword) { + return this.update(varKeyword, this.variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarators = function (variableDeclarators) { + return this.update(this.varKeyword, variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.withVariableDeclarators(TypeScript.Syntax.separatedList([variableDeclarator])); + }; + + VariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclarators.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclarationSyntax = VariableDeclarationSyntax; + + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + VariableDeclaratorSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclarator(this); + }; + + VariableDeclaratorSyntax.prototype.kind = function () { + return 224 /* VariableDeclarator */; + }; + + VariableDeclaratorSyntax.prototype.childCount = function () { + return 3; + }; + + VariableDeclaratorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.typeAnnotation; + case 2: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclaratorSyntax.prototype.update = function (identifier, typeAnnotation, equalsValueClause) { + if (this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new VariableDeclaratorSyntax(identifier, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + VariableDeclaratorSyntax.create = function (identifier) { + return new VariableDeclaratorSyntax(identifier, null, null, false); + }; + + VariableDeclaratorSyntax.create1 = function (identifier) { + return new VariableDeclaratorSyntax(identifier, null, null, false); + }; + + VariableDeclaratorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.identifier, typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.identifier, this.typeAnnotation, equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(equalsToken, value, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsToken = equalsToken; + this.value = value; + } + EqualsValueClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitEqualsValueClause(this); + }; + + EqualsValueClauseSyntax.prototype.kind = function () { + return 230 /* EqualsValueClause */; + }; + + EqualsValueClauseSyntax.prototype.childCount = function () { + return 2; + }; + + EqualsValueClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.equalsToken; + case 1: + return this.value; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EqualsValueClauseSyntax.prototype.update = function (equalsToken, value) { + if (this.equalsToken === equalsToken && this.value === value) { + return this; + } + + return new EqualsValueClauseSyntax(equalsToken, value, this.parsedInStrictMode()); + }; + + EqualsValueClauseSyntax.create1 = function (value) { + return new EqualsValueClauseSyntax(TypeScript.Syntax.token(108 /* EqualsToken */), value, false); + }; + + EqualsValueClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(equalsToken, this.value); + }; + + EqualsValueClauseSyntax.prototype.withValue = function (value) { + return this.update(this.equalsToken, value); + }; + + EqualsValueClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.value.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(kind, operatorToken, operand, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operatorToken = operatorToken; + this.operand = operand; + + this._kind = kind; + } + PrefixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPrefixUnaryExpression(this); + }; + + PrefixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PrefixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operatorToken; + case 1: + return this.operand; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PrefixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PrefixUnaryExpressionSyntax.prototype.update = function (kind, operatorToken, operand) { + if (this._kind === kind && this.operatorToken === operatorToken && this.operand === operand) { + return this; + } + + return new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, this.parsedInStrictMode()); + }; + + PrefixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, this.operatorToken, operand); + }; + + PrefixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.expressions = expressions; + this.closeBracketToken = closeBracketToken; + } + ArrayLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayLiteralExpression(this); + }; + + ArrayLiteralExpressionSyntax.prototype.kind = function () { + return 213 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.expressions; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.update = function (openBracketToken, expressions, closeBracketToken) { + if (this.openBracketToken === openBracketToken && this.expressions === expressions && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayLiteralExpressionSyntax.create = function (openBracketToken, closeBracketToken) { + return new ArrayLiteralExpressionSyntax(openBracketToken, TypeScript.Syntax.emptySeparatedList, closeBracketToken, false); + }; + + ArrayLiteralExpressionSyntax.create1 = function () { + return new ArrayLiteralExpressionSyntax(TypeScript.Syntax.token(75 /* OpenBracketToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(76 /* CloseBracketToken */), false); + }; + + ArrayLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpressions = function (expressions) { + return this.update(this.openBracketToken, expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpression = function (expression) { + return this.withExpressions(TypeScript.Syntax.separatedList([expression])); + }; + + ArrayLiteralExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.expressions, closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expressions.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + OmittedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitOmittedExpression(this); + }; + + OmittedExpressionSyntax.prototype.kind = function () { + return 222 /* OmittedExpression */; + }; + + OmittedExpressionSyntax.prototype.childCount = function () { + return 0; + }; + + OmittedExpressionSyntax.prototype.childAt = function (slot) { + throw TypeScript.Errors.invalidOperation(); + }; + + OmittedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + OmittedExpressionSyntax.prototype.update = function () { + return this; + }; + + OmittedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.OmittedExpressionSyntax = OmittedExpressionSyntax; + + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + } + ParenthesizedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedExpression(this); + }; + + ParenthesizedExpressionSyntax.prototype.kind = function () { + return 216 /* ParenthesizedExpression */; + }; + + ParenthesizedExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.expression; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.update = function (openParenToken, expression, closeParenToken) { + if (this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, this.parsedInStrictMode()); + }; + + ParenthesizedExpressionSyntax.create1 = function (expression) { + return new ParenthesizedExpressionSyntax(TypeScript.Syntax.token(73 /* OpenParenToken */), expression, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ParenthesizedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.openParenToken, expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.expression, closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + + var ArrowFunctionExpressionSyntax = (function (_super) { + __extends(ArrowFunctionExpressionSyntax, _super); + function ArrowFunctionExpressionSyntax(equalsGreaterThanToken, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.body = body; + } + ArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrowFunctionExpressionSyntax = ArrowFunctionExpressionSyntax; + + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, parsedInStrictMode) { + _super.call(this, equalsGreaterThanToken, body, parsedInStrictMode); + this.identifier = identifier; + } + SimpleArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitSimpleArrowFunctionExpression(this); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.kind = function () { + return 218 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimpleArrowFunctionExpressionSyntax.prototype.update = function (identifier, equalsGreaterThanToken, body) { + if (this.identifier === identifier && this.equalsGreaterThanToken === equalsGreaterThanToken && this.body === body) { + return this; + } + + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, body, this.parsedInStrictMode()); + }; + + SimpleArrowFunctionExpressionSyntax.create1 = function (identifier, body) { + return new SimpleArrowFunctionExpressionSyntax(identifier, TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), body, false); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.equalsGreaterThanToken, this.body); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.identifier, equalsGreaterThanToken, this.body); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withBody = function (body) { + return this.update(this.identifier, this.equalsGreaterThanToken, body); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SimpleArrowFunctionExpressionSyntax; + })(ArrowFunctionExpressionSyntax); + TypeScript.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, parsedInStrictMode) { + _super.call(this, equalsGreaterThanToken, body, parsedInStrictMode); + this.callSignature = callSignature; + } + ParenthesizedArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedArrowFunctionExpression(this); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.kind = function () { + return 217 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.callSignature; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.update = function (callSignature, equalsGreaterThanToken, body) { + if (this.callSignature === callSignature && this.equalsGreaterThanToken === equalsGreaterThanToken && this.body === body) { + return this; + } + + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, body, this.parsedInStrictMode()); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create1 = function (body) { + return new ParenthesizedArrowFunctionExpressionSyntax(CallSignatureSyntax.create1(), TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), body, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(callSignature, this.equalsGreaterThanToken, this.body); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.callSignature, equalsGreaterThanToken, this.body); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withBody = function (body) { + return this.update(this.callSignature, this.equalsGreaterThanToken, body); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ParenthesizedArrowFunctionExpressionSyntax; + })(ArrowFunctionExpressionSyntax); + TypeScript.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(left, dotToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.dotToken = dotToken; + this.right = right; + } + QualifiedNameSyntax.prototype.accept = function (visitor) { + return visitor.visitQualifiedName(this); + }; + + QualifiedNameSyntax.prototype.kind = function () { + return 122 /* QualifiedName */; + }; + + QualifiedNameSyntax.prototype.childCount = function () { + return 3; + }; + + QualifiedNameSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.dotToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + QualifiedNameSyntax.prototype.isName = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isType = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isExpression = function () { + return true; + }; + + QualifiedNameSyntax.prototype.update = function (left, dotToken, right) { + if (this.left === left && this.dotToken === dotToken && this.right === right) { + return this; + } + + return new QualifiedNameSyntax(left, dotToken, right, this.parsedInStrictMode()); + }; + + QualifiedNameSyntax.create1 = function (left, right) { + return new QualifiedNameSyntax(left, TypeScript.Syntax.token(77 /* DotToken */), right, false); + }; + + QualifiedNameSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withLeft = function (left) { + return this.update(left, this.dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.left, dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withRight = function (right) { + return this.update(this.left, this.dotToken, right); + }; + + QualifiedNameSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + TypeScript.QualifiedNameSyntax = QualifiedNameSyntax; + + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeArguments = typeArguments; + this.greaterThanToken = greaterThanToken; + } + TypeArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeArgumentList(this); + }; + + TypeArgumentListSyntax.prototype.kind = function () { + return 227 /* TypeArgumentList */; + }; + + TypeArgumentListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeArguments; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeArgumentListSyntax.prototype.update = function (lessThanToken, typeArguments, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeArguments === typeArguments && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeArgumentListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeArgumentListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeArgumentListSyntax.create1 = function () { + return new TypeArgumentListSyntax(TypeScript.Syntax.token(81 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(82 /* GreaterThanToken */), false); + }; + + TypeArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArguments = function (typeArguments) { + return this.update(this.lessThanToken, typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArgument = function (typeArgument) { + return this.withTypeArguments(TypeScript.Syntax.separatedList([typeArgument])); + }; + + TypeArgumentListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeArguments, greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeArgumentListSyntax = TypeArgumentListSyntax; + + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + ConstructorTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorType(this); + }; + + ConstructorTypeSyntax.prototype.kind = function () { + return 126 /* ConstructorType */; + }; + + ConstructorTypeSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.typeParameterList; + case 2: + return this.parameterList; + case 3: + return this.equalsGreaterThanToken; + case 4: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorTypeSyntax.prototype.isType = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.isExpression = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.update = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.newKeyword === newKeyword && this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + ConstructorTypeSyntax.create = function (newKeyword, parameterList, equalsGreaterThanToken, type) { + return new ConstructorTypeSyntax(newKeyword, null, parameterList, equalsGreaterThanToken, type, false); + }; + + ConstructorTypeSyntax.create1 = function (type) { + return new ConstructorTypeSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), null, ParameterListSyntax.create1(), TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), type, false); + }; + + ConstructorTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.newKeyword, typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.newKeyword, this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withType = function (type) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + ConstructorTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorTypeSyntax = ConstructorTypeSyntax; + + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + FunctionTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionType(this); + }; + + FunctionTypeSyntax.prototype.kind = function () { + return 124 /* FunctionType */; + }; + + FunctionTypeSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.equalsGreaterThanToken; + case 3: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionTypeSyntax.prototype.isType = function () { + return true; + }; + + FunctionTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionTypeSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionTypeSyntax.prototype.update = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + FunctionTypeSyntax.create = function (parameterList, equalsGreaterThanToken, type) { + return new FunctionTypeSyntax(null, parameterList, equalsGreaterThanToken, type, false); + }; + + FunctionTypeSyntax.create1 = function (type) { + return new FunctionTypeSyntax(null, ParameterListSyntax.create1(), TypeScript.Syntax.token(86 /* EqualsGreaterThanToken */), type, false); + }; + + FunctionTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withType = function (type) { + return this.update(this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + FunctionTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionTypeSyntax = FunctionTypeSyntax; + + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.typeMembers = typeMembers; + this.closeBraceToken = closeBraceToken; + } + ObjectTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectType(this); + }; + + ObjectTypeSyntax.prototype.kind = function () { + return 123 /* ObjectType */; + }; + + ObjectTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.typeMembers; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectTypeSyntax.prototype.isType = function () { + return true; + }; + + ObjectTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectTypeSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectTypeSyntax.prototype.update = function (openBraceToken, typeMembers, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.typeMembers === typeMembers && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectTypeSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectTypeSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectTypeSyntax.create1 = function () { + return new ObjectTypeSyntax(TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ObjectTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMembers = function (typeMembers) { + return this.update(this.openBraceToken, typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMember = function (typeMember) { + return this.withTypeMembers(TypeScript.Syntax.separatedList([typeMember])); + }; + + ObjectTypeSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.typeMembers, closeBraceToken); + }; + + ObjectTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectTypeSyntax = ObjectTypeSyntax; + + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(type, openBracketToken, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.type = type; + this.openBracketToken = openBracketToken; + this.closeBracketToken = closeBracketToken; + } + ArrayTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayType(this); + }; + + ArrayTypeSyntax.prototype.kind = function () { + return 125 /* ArrayType */; + }; + + ArrayTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.type; + case 1: + return this.openBracketToken; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayTypeSyntax.prototype.isType = function () { + return true; + }; + + ArrayTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayTypeSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayTypeSyntax.prototype.update = function (type, openBracketToken, closeBracketToken) { + if (this.type === type && this.openBracketToken === openBracketToken && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayTypeSyntax(type, openBracketToken, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayTypeSyntax.create1 = function (type) { + return new ArrayTypeSyntax(type, TypeScript.Syntax.token(75 /* OpenBracketToken */), TypeScript.Syntax.token(76 /* CloseBracketToken */), false); + }; + + ArrayTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withType = function (type) { + return this.update(type, this.openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.type, openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.type, this.openBracketToken, closeBracketToken); + }; + + ArrayTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayTypeSyntax = ArrayTypeSyntax; + + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(name, typeArgumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.name = name; + this.typeArgumentList = typeArgumentList; + } + GenericTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitGenericType(this); + }; + + GenericTypeSyntax.prototype.kind = function () { + return 127 /* GenericType */; + }; + + GenericTypeSyntax.prototype.childCount = function () { + return 2; + }; + + GenericTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.name; + case 1: + return this.typeArgumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GenericTypeSyntax.prototype.isType = function () { + return true; + }; + + GenericTypeSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + GenericTypeSyntax.prototype.isExpression = function () { + return true; + }; + + GenericTypeSyntax.prototype.update = function (name, typeArgumentList) { + if (this.name === name && this.typeArgumentList === typeArgumentList) { + return this; + } + + return new GenericTypeSyntax(name, typeArgumentList, this.parsedInStrictMode()); + }; + + GenericTypeSyntax.create1 = function (name) { + return new GenericTypeSyntax(name, TypeArgumentListSyntax.create1(), false); + }; + + GenericTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withName = function (name) { + return this.update(name, this.typeArgumentList); + }; + + GenericTypeSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(this.name, typeArgumentList); + }; + + GenericTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GenericTypeSyntax = GenericTypeSyntax; + + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(colonToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.type = type; + } + TypeAnnotationSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeAnnotation(this); + }; + + TypeAnnotationSyntax.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + + TypeAnnotationSyntax.prototype.childCount = function () { + return 2; + }; + + TypeAnnotationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.colonToken; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeAnnotationSyntax.prototype.update = function (colonToken, type) { + if (this.colonToken === colonToken && this.type === type) { + return this; + } + + return new TypeAnnotationSyntax(colonToken, type, this.parsedInStrictMode()); + }; + + TypeAnnotationSyntax.create1 = function (type) { + return new TypeAnnotationSyntax(TypeScript.Syntax.token(107 /* ColonToken */), type, false); + }; + + TypeAnnotationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withColonToken = function (colonToken) { + return this.update(colonToken, this.type); + }; + + TypeAnnotationSyntax.prototype.withType = function (type) { + return this.update(this.colonToken, type); + }; + + TypeAnnotationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeAnnotationSyntax = TypeAnnotationSyntax; + + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(openBraceToken, statements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.statements = statements; + this.closeBraceToken = closeBraceToken; + } + BlockSyntax.prototype.accept = function (visitor) { + return visitor.visitBlock(this); + }; + + BlockSyntax.prototype.kind = function () { + return 145 /* Block */; + }; + + BlockSyntax.prototype.childCount = function () { + return 3; + }; + + BlockSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.statements; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BlockSyntax.prototype.isStatement = function () { + return true; + }; + + BlockSyntax.prototype.isModuleElement = function () { + return true; + }; + + BlockSyntax.prototype.update = function (openBraceToken, statements, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.statements === statements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new BlockSyntax(openBraceToken, statements, closeBraceToken, this.parsedInStrictMode()); + }; + + BlockSyntax.create = function (openBraceToken, closeBraceToken) { + return new BlockSyntax(openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + BlockSyntax.create1 = function () { + return new BlockSyntax(TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + BlockSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatements = function (statements) { + return this.update(this.openBraceToken, statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + BlockSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.statements, closeBraceToken); + }; + + BlockSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BlockSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BlockSyntax = BlockSyntax; + + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.dotDotDotToken = dotDotDotToken; + this.publicOrPrivateKeyword = publicOrPrivateKeyword; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + ParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitParameter(this); + }; + + ParameterSyntax.prototype.kind = function () { + return 242 /* Parameter */; + }; + + ParameterSyntax.prototype.childCount = function () { + return 6; + }; + + ParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.dotDotDotToken; + case 1: + return this.publicOrPrivateKeyword; + case 2: + return this.identifier; + case 3: + return this.questionToken; + case 4: + return this.typeAnnotation; + case 5: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterSyntax.prototype.update = function (dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause) { + if (this.dotDotDotToken === dotDotDotToken && this.publicOrPrivateKeyword === publicOrPrivateKeyword && this.identifier === identifier && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new ParameterSyntax(dotDotDotToken, publicOrPrivateKeyword, identifier, questionToken, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + ParameterSyntax.create = function (identifier) { + return new ParameterSyntax(null, null, identifier, null, null, null, false); + }; + + ParameterSyntax.create1 = function (identifier) { + return new ParameterSyntax(null, null, identifier, null, null, null, false); + }; + + ParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withDotDotDotToken = function (dotDotDotToken) { + return this.update(dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withPublicOrPrivateKeyword = function (publicOrPrivateKeyword) { + return this.update(this.dotDotDotToken, publicOrPrivateKeyword, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, this.questionToken, typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.dotDotDotToken, this.publicOrPrivateKeyword, this.identifier, this.questionToken, this.typeAnnotation, equalsValueClause); + }; + + ParameterSyntax.prototype.isTypeScriptSpecific = function () { + if (this.dotDotDotToken !== null) { + return true; + } + if (this.publicOrPrivateKeyword !== null) { + return true; + } + if (this.questionToken !== null) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null) { + return true; + } + return false; + }; + return ParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterSyntax = ParameterSyntax; + + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(expression, dotToken, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.dotToken = dotToken; + this.name = name; + } + MemberAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberAccessExpression(this); + }; + + MemberAccessExpressionSyntax.prototype.kind = function () { + return 211 /* MemberAccessExpression */; + }; + + MemberAccessExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + MemberAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.dotToken; + case 2: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.update = function (expression, dotToken, name) { + if (this.expression === expression && this.dotToken === dotToken && this.name === name) { + return this; + } + + return new MemberAccessExpressionSyntax(expression, dotToken, name, this.parsedInStrictMode()); + }; + + MemberAccessExpressionSyntax.create1 = function (expression, name) { + return new MemberAccessExpressionSyntax(expression, TypeScript.Syntax.token(77 /* DotToken */), name, false); + }; + + MemberAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.expression, dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withName = function (name) { + return this.update(this.expression, this.dotToken, name); + }; + + MemberAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(kind, operand, operatorToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operand = operand; + this.operatorToken = operatorToken; + + this._kind = kind; + } + PostfixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPostfixUnaryExpression(this); + }; + + PostfixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PostfixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operand; + case 1: + return this.operatorToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PostfixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PostfixUnaryExpressionSyntax.prototype.update = function (kind, operand, operatorToken) { + if (this._kind === kind && this.operand === operand && this.operatorToken === operatorToken) { + return this; + } + + return new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, this.parsedInStrictMode()); + }; + + PostfixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.operand, operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.openBracketToken = openBracketToken; + this.argumentExpression = argumentExpression; + this.closeBracketToken = closeBracketToken; + } + ElementAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitElementAccessExpression(this); + }; + + ElementAccessExpressionSyntax.prototype.kind = function () { + return 220 /* ElementAccessExpression */; + }; + + ElementAccessExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ElementAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.openBracketToken; + case 2: + return this.argumentExpression; + case 3: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElementAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.update = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + if (this.expression === expression && this.openBracketToken === openBracketToken && this.argumentExpression === argumentExpression && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, this.parsedInStrictMode()); + }; + + ElementAccessExpressionSyntax.create1 = function (expression, argumentExpression) { + return new ElementAccessExpressionSyntax(expression, TypeScript.Syntax.token(75 /* OpenBracketToken */), argumentExpression, TypeScript.Syntax.token(76 /* CloseBracketToken */), false); + }; + + ElementAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.expression, openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withArgumentExpression = function (argumentExpression) { + return this.update(this.expression, this.openBracketToken, argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.expression, this.openBracketToken, this.argumentExpression, closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentExpression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.argumentList = argumentList; + } + InvocationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitInvocationExpression(this); + }; + + InvocationExpressionSyntax.prototype.kind = function () { + return 212 /* InvocationExpression */; + }; + + InvocationExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + InvocationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InvocationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.update = function (expression, argumentList) { + if (this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new InvocationExpressionSyntax(expression, argumentList, this.parsedInStrictMode()); + }; + + InvocationExpressionSyntax.create1 = function (expression) { + return new InvocationExpressionSyntax(expression, ArgumentListSyntax.create1(), false); + }; + + InvocationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.argumentList); + }; + + InvocationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.expression, argumentList); + }; + + InvocationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InvocationExpressionSyntax = InvocationExpressionSyntax; + + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(typeArgumentList, openParenToken, arguments, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeArgumentList = typeArgumentList; + this.openParenToken = openParenToken; + this.arguments = arguments; + this.closeParenToken = closeParenToken; + } + ArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitArgumentList(this); + }; + + ArgumentListSyntax.prototype.kind = function () { + return 225 /* ArgumentList */; + }; + + ArgumentListSyntax.prototype.childCount = function () { + return 4; + }; + + ArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeArgumentList; + case 1: + return this.openParenToken; + case 2: + return this.arguments; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArgumentListSyntax.prototype.update = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + if (this.typeArgumentList === typeArgumentList && this.openParenToken === openParenToken && this.arguments === _arguments && this.closeParenToken === closeParenToken) { + return this; + } + + return new ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, this.parsedInStrictMode()); + }; + + ArgumentListSyntax.create = function (openParenToken, closeParenToken) { + return new ArgumentListSyntax(null, openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ArgumentListSyntax.create1 = function () { + return new ArgumentListSyntax(null, TypeScript.Syntax.token(73 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(typeArgumentList, this.openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.typeArgumentList, openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArguments = function (_arguments) { + return this.update(this.typeArgumentList, this.openParenToken, _arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArgument = function (_argument) { + return this.withArguments(TypeScript.Syntax.separatedList([_argument])); + }; + + ArgumentListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.typeArgumentList, this.openParenToken, this.arguments, closeParenToken); + }; + + ArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeArgumentList !== null && this.typeArgumentList.isTypeScriptSpecific()) { + return true; + } + if (this.arguments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArgumentListSyntax = ArgumentListSyntax; + + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(kind, left, operatorToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.operatorToken = operatorToken; + this.right = right; + + this._kind = kind; + } + BinaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitBinaryExpression(this); + }; + + BinaryExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + BinaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.operatorToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BinaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + BinaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + BinaryExpressionSyntax.prototype.update = function (kind, left, operatorToken, right) { + if (this._kind === kind && this.left === left && this.operatorToken === operatorToken && this.right === right) { + return this; + } + + return new BinaryExpressionSyntax(kind, left, operatorToken, right, this.parsedInStrictMode()); + }; + + BinaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withLeft = function (left) { + return this.update(this._kind, left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.left, operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withRight = function (right) { + return this.update(this._kind, this.left, this.operatorToken, right); + }; + + BinaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.left.isTypeScriptSpecific()) { + return true; + } + if (this.right.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BinaryExpressionSyntax = BinaryExpressionSyntax; + + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.condition = condition; + this.questionToken = questionToken; + this.whenTrue = whenTrue; + this.colonToken = colonToken; + this.whenFalse = whenFalse; + } + ConditionalExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitConditionalExpression(this); + }; + + ConditionalExpressionSyntax.prototype.kind = function () { + return 185 /* ConditionalExpression */; + }; + + ConditionalExpressionSyntax.prototype.childCount = function () { + return 5; + }; + + ConditionalExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.condition; + case 1: + return this.questionToken; + case 2: + return this.whenTrue; + case 3: + return this.colonToken; + case 4: + return this.whenFalse; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConditionalExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ConditionalExpressionSyntax.prototype.update = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + if (this.condition === condition && this.questionToken === questionToken && this.whenTrue === whenTrue && this.colonToken === colonToken && this.whenFalse === whenFalse) { + return this; + } + + return new ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, this.parsedInStrictMode()); + }; + + ConditionalExpressionSyntax.create1 = function (condition, whenTrue, whenFalse) { + return new ConditionalExpressionSyntax(condition, TypeScript.Syntax.token(106 /* QuestionToken */), whenTrue, TypeScript.Syntax.token(107 /* ColonToken */), whenFalse, false); + }; + + ConditionalExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withCondition = function (condition) { + return this.update(condition, this.questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.condition, questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenTrue = function (whenTrue) { + return this.update(this.condition, this.questionToken, whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.condition, this.questionToken, this.whenTrue, colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenFalse = function (whenFalse) { + return this.update(this.condition, this.questionToken, this.whenTrue, this.colonToken, whenFalse); + }; + + ConditionalExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.whenTrue.isTypeScriptSpecific()) { + return true; + } + if (this.whenFalse.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(newKeyword, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.callSignature = callSignature; + } + ConstructSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructSignature(this); + }; + + ConstructSignatureSyntax.prototype.kind = function () { + return 142 /* ConstructSignature */; + }; + + ConstructSignatureSyntax.prototype.childCount = function () { + return 2; + }; + + ConstructSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + ConstructSignatureSyntax.prototype.update = function (newKeyword, callSignature) { + if (this.newKeyword === newKeyword && this.callSignature === callSignature) { + return this; + } + + return new ConstructSignatureSyntax(newKeyword, callSignature, this.parsedInStrictMode()); + }; + + ConstructSignatureSyntax.create1 = function () { + return new ConstructSignatureSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), CallSignatureSyntax.create1(), false); + }; + + ConstructSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.callSignature); + }; + + ConstructSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.newKeyword, callSignature); + }; + + ConstructSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructSignatureSyntax = ConstructSignatureSyntax; + + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(propertyName, questionToken, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + } + MethodSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitMethodSignature(this); + }; + + MethodSignatureSyntax.prototype.kind = function () { + return 144 /* MethodSignature */; + }; + + MethodSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + MethodSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MethodSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + MethodSignatureSyntax.prototype.update = function (propertyName, questionToken, callSignature) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.callSignature === callSignature) { + return this; + } + + return new MethodSignatureSyntax(propertyName, questionToken, callSignature, this.parsedInStrictMode()); + }; + + MethodSignatureSyntax.create = function (propertyName, callSignature) { + return new MethodSignatureSyntax(propertyName, null, callSignature, false); + }; + + MethodSignatureSyntax.create1 = function (propertyName) { + return new MethodSignatureSyntax(propertyName, null, CallSignatureSyntax.create1(), false); + }; + + MethodSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, this.questionToken, callSignature); + }; + + MethodSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MethodSignatureSyntax = MethodSignatureSyntax; + + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.parameter = parameter; + this.closeBracketToken = closeBracketToken; + this.typeAnnotation = typeAnnotation; + } + IndexSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexSignature(this); + }; + + IndexSignatureSyntax.prototype.kind = function () { + return 143 /* IndexSignature */; + }; + + IndexSignatureSyntax.prototype.childCount = function () { + return 4; + }; + + IndexSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.parameter; + case 2: + return this.closeBracketToken; + case 3: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + IndexSignatureSyntax.prototype.isClassElement = function () { + return true; + }; + + IndexSignatureSyntax.prototype.update = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + if (this.openBracketToken === openBracketToken && this.parameter === parameter && this.closeBracketToken === closeBracketToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, this.parsedInStrictMode()); + }; + + IndexSignatureSyntax.create = function (openBracketToken, parameter, closeBracketToken) { + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, null, false); + }; + + IndexSignatureSyntax.create1 = function (parameter) { + return new IndexSignatureSyntax(TypeScript.Syntax.token(75 /* OpenBracketToken */), parameter, TypeScript.Syntax.token(76 /* CloseBracketToken */), null, false); + }; + + IndexSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withParameter = function (parameter) { + return this.update(this.openBracketToken, parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.parameter, closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.openBracketToken, this.parameter, this.closeBracketToken, typeAnnotation); + }; + + IndexSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexSignatureSyntax = IndexSignatureSyntax; + + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + } + PropertySignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitPropertySignature(this); + }; + + PropertySignatureSyntax.prototype.kind = function () { + return 140 /* PropertySignature */; + }; + + PropertySignatureSyntax.prototype.childCount = function () { + return 3; + }; + + PropertySignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PropertySignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + PropertySignatureSyntax.prototype.update = function (propertyName, questionToken, typeAnnotation) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, this.parsedInStrictMode()); + }; + + PropertySignatureSyntax.create = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.create1 = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, this.questionToken, typeAnnotation); + }; + + PropertySignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertySignatureSyntax = PropertySignatureSyntax; + + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + } + CallSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitCallSignature(this); + }; + + CallSignatureSyntax.prototype.kind = function () { + return 141 /* CallSignature */; + }; + + CallSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + CallSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CallSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + CallSignatureSyntax.prototype.update = function (typeParameterList, parameterList, typeAnnotation) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, this.parsedInStrictMode()); + }; + + CallSignatureSyntax.create = function (parameterList) { + return new CallSignatureSyntax(null, parameterList, null, false); + }; + + CallSignatureSyntax.create1 = function () { + return new CallSignatureSyntax(null, ParameterListSyntax.create1(), null, false); + }; + + CallSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.typeParameterList, this.parameterList, typeAnnotation); + }; + + CallSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeParameterList !== null) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + return false; + }; + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CallSignatureSyntax = CallSignatureSyntax; + + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(openParenToken, parameters, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.parameters = parameters; + this.closeParenToken = closeParenToken; + } + ParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitParameterList(this); + }; + + ParameterListSyntax.prototype.kind = function () { + return 226 /* ParameterList */; + }; + + ParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + ParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.parameters; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterListSyntax.prototype.update = function (openParenToken, parameters, closeParenToken) { + if (this.openParenToken === openParenToken && this.parameters === parameters && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParameterListSyntax(openParenToken, parameters, closeParenToken, this.parsedInStrictMode()); + }; + + ParameterListSyntax.create = function (openParenToken, closeParenToken) { + return new ParameterListSyntax(openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ParameterListSyntax.create1 = function () { + return new ParameterListSyntax(TypeScript.Syntax.token(73 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(74 /* CloseParenToken */), false); + }; + + ParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameters = function (parameters) { + return this.update(this.openParenToken, parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameter = function (parameter) { + return this.withParameters(TypeScript.Syntax.separatedList([parameter])); + }; + + ParameterListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.parameters, closeParenToken); + }; + + ParameterListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameters.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterListSyntax = ParameterListSyntax; + + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeParameters = typeParameters; + this.greaterThanToken = greaterThanToken; + } + TypeParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameterList(this); + }; + + TypeParameterListSyntax.prototype.kind = function () { + return 228 /* TypeParameterList */; + }; + + TypeParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeParameters; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterListSyntax.prototype.update = function (lessThanToken, typeParameters, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeParameters === typeParameters && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeParameterListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeParameterListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeParameterListSyntax.create1 = function () { + return new TypeParameterListSyntax(TypeScript.Syntax.token(81 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(82 /* GreaterThanToken */), false); + }; + + TypeParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameters = function (typeParameters) { + return this.update(this.lessThanToken, typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameter = function (typeParameter) { + return this.withTypeParameters(TypeScript.Syntax.separatedList([typeParameter])); + }; + + TypeParameterListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeParameters, greaterThanToken); + }; + + TypeParameterListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterListSyntax = TypeParameterListSyntax; + + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(identifier, constraint, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.constraint = constraint; + } + TypeParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameter(this); + }; + + TypeParameterSyntax.prototype.kind = function () { + return 236 /* TypeParameter */; + }; + + TypeParameterSyntax.prototype.childCount = function () { + return 2; + }; + + TypeParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.constraint; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterSyntax.prototype.update = function (identifier, constraint) { + if (this.identifier === identifier && this.constraint === constraint) { + return this; + } + + return new TypeParameterSyntax(identifier, constraint, this.parsedInStrictMode()); + }; + + TypeParameterSyntax.create = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.create1 = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.constraint); + }; + + TypeParameterSyntax.prototype.withConstraint = function (constraint) { + return this.update(this.identifier, constraint); + }; + + TypeParameterSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterSyntax = TypeParameterSyntax; + + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(extendsKeyword, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsKeyword = extendsKeyword; + this.type = type; + } + ConstraintSyntax.prototype.accept = function (visitor) { + return visitor.visitConstraint(this); + }; + + ConstraintSyntax.prototype.kind = function () { + return 237 /* Constraint */; + }; + + ConstraintSyntax.prototype.childCount = function () { + return 2; + }; + + ConstraintSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsKeyword; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstraintSyntax.prototype.update = function (extendsKeyword, type) { + if (this.extendsKeyword === extendsKeyword && this.type === type) { + return this; + } + + return new ConstraintSyntax(extendsKeyword, type, this.parsedInStrictMode()); + }; + + ConstraintSyntax.create1 = function (type) { + return new ConstraintSyntax(TypeScript.Syntax.token(48 /* ExtendsKeyword */), type, false); + }; + + ConstraintSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withExtendsKeyword = function (extendsKeyword) { + return this.update(extendsKeyword, this.type); + }; + + ConstraintSyntax.prototype.withType = function (type) { + return this.update(this.extendsKeyword, type); + }; + + ConstraintSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstraintSyntax = ConstraintSyntax; + + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(elseKeyword, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.elseKeyword = elseKeyword; + this.statement = statement; + } + ElseClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitElseClause(this); + }; + + ElseClauseSyntax.prototype.kind = function () { + return 233 /* ElseClause */; + }; + + ElseClauseSyntax.prototype.childCount = function () { + return 2; + }; + + ElseClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.elseKeyword; + case 1: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElseClauseSyntax.prototype.update = function (elseKeyword, statement) { + if (this.elseKeyword === elseKeyword && this.statement === statement) { + return this; + } + + return new ElseClauseSyntax(elseKeyword, statement, this.parsedInStrictMode()); + }; + + ElseClauseSyntax.create1 = function (statement) { + return new ElseClauseSyntax(TypeScript.Syntax.token(23 /* ElseKeyword */), statement, false); + }; + + ElseClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withElseKeyword = function (elseKeyword) { + return this.update(elseKeyword, this.statement); + }; + + ElseClauseSyntax.prototype.withStatement = function (statement) { + return this.update(this.elseKeyword, statement); + }; + + ElseClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElseClauseSyntax = ElseClauseSyntax; + + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.ifKeyword = ifKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + this.elseClause = elseClause; + } + IfStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitIfStatement(this); + }; + + IfStatementSyntax.prototype.kind = function () { + return 146 /* IfStatement */; + }; + + IfStatementSyntax.prototype.childCount = function () { + return 6; + }; + + IfStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.ifKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + case 5: + return this.elseClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IfStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IfStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IfStatementSyntax.prototype.update = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + if (this.ifKeyword === ifKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement && this.elseClause === elseClause) { + return this; + } + + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, this.parsedInStrictMode()); + }; + + IfStatementSyntax.create = function (ifKeyword, openParenToken, condition, closeParenToken, statement) { + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, null, false); + }; + + IfStatementSyntax.create1 = function (condition, statement) { + return new IfStatementSyntax(TypeScript.Syntax.token(28 /* IfKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, null, false); + }; + + IfStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withIfKeyword = function (ifKeyword) { + return this.update(ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.ifKeyword, openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.ifKeyword, this.openParenToken, condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withElseClause = function (elseClause) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, elseClause); + }; + + IfStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.elseClause !== null && this.elseClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IfStatementSyntax = IfStatementSyntax; + + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ExpressionStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitExpressionStatement(this); + }; + + ExpressionStatementSyntax.prototype.kind = function () { + return 148 /* ExpressionStatement */; + }; + + ExpressionStatementSyntax.prototype.childCount = function () { + return 2; + }; + + ExpressionStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExpressionStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.update = function (expression, semicolonToken) { + if (this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExpressionStatementSyntax(expression, semicolonToken, this.parsedInStrictMode()); + }; + + ExpressionStatementSyntax.create1 = function (expression) { + return new ExpressionStatementSyntax(expression, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ExpressionStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.semicolonToken); + }; + + ExpressionStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.expression, semicolonToken); + }; + + ExpressionStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExpressionStatementSyntax = ExpressionStatementSyntax; + + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.constructorKeyword = constructorKeyword; + this.parameterList = parameterList; + this.block = block; + this.semicolonToken = semicolonToken; + } + ConstructorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorDeclaration(this); + }; + + ConstructorDeclarationSyntax.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + + ConstructorDeclarationSyntax.prototype.childCount = function () { + return 4; + }; + + ConstructorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.constructorKeyword; + case 1: + return this.parameterList; + case 2: + return this.block; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + ConstructorDeclarationSyntax.prototype.update = function (constructorKeyword, parameterList, block, semicolonToken) { + if (this.constructorKeyword === constructorKeyword && this.parameterList === parameterList && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new ConstructorDeclarationSyntax(constructorKeyword, parameterList, block, semicolonToken, this.parsedInStrictMode()); + }; + + ConstructorDeclarationSyntax.create = function (constructorKeyword, parameterList) { + return new ConstructorDeclarationSyntax(constructorKeyword, parameterList, null, null, false); + }; + + ConstructorDeclarationSyntax.create1 = function () { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.token(63 /* ConstructorKeyword */), ParameterListSyntax.create1(), null, null, false); + }; + + ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { + return this.update(constructorKeyword, this.parameterList, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.constructorKeyword, parameterList, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.constructorKeyword, this.parameterList, block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.constructorKeyword, this.parameterList, this.block, semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + MemberFunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberFunctionDeclaration(this); + }; + + MemberFunctionDeclarationSyntax.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + + MemberFunctionDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + MemberFunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.propertyName; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberFunctionDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.update = function (modifiers, propertyName, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.propertyName === propertyName && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + MemberFunctionDeclarationSyntax.create = function (propertyName, callSignature) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, callSignature, null, null, false); + }; + + MemberFunctionDeclarationSyntax.create1 = function (propertyName) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, CallSignatureSyntax.create1(), null, null, false); + }; + + MemberFunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberFunctionDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.propertyName, callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.propertyName, this.callSignature, block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.propertyName, this.callSignature, this.block, semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + + var MemberAccessorDeclarationSyntax = (function (_super) { + __extends(MemberAccessorDeclarationSyntax, _super); + function MemberAccessorDeclarationSyntax(modifiers, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + } + MemberAccessorDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberAccessorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberAccessorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberAccessorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessorDeclarationSyntax = MemberAccessorDeclarationSyntax; + + var GetMemberAccessorDeclarationSyntax = (function (_super) { + __extends(GetMemberAccessorDeclarationSyntax, _super); + function GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, modifiers, propertyName, parameterList, block, parsedInStrictMode); + this.getKeyword = getKeyword; + this.typeAnnotation = typeAnnotation; + } + GetMemberAccessorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitGetMemberAccessorDeclaration(this); + }; + + GetMemberAccessorDeclarationSyntax.prototype.kind = function () { + return 138 /* GetMemberAccessorDeclaration */; + }; + + GetMemberAccessorDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + GetMemberAccessorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.getKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetMemberAccessorDeclarationSyntax.prototype.update = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + if (this.modifiers === modifiers && this.getKeyword === getKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetMemberAccessorDeclarationSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetMemberAccessorDeclarationSyntax.create = function (getKeyword, propertyName, parameterList, block) { + return new GetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, getKeyword, propertyName, parameterList, null, block, false); + }; + + GetMemberAccessorDeclarationSyntax.create1 = function (propertyName) { + return new GetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(65 /* GetKeyword */), propertyName, ParameterListSyntax.create1(), null, BlockSyntax.create1(), false); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(this.modifiers, getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.getKeyword, propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, parameterList, this.typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, typeAnnotation, this.block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, block); + }; + + GetMemberAccessorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GetMemberAccessorDeclarationSyntax; + })(MemberAccessorDeclarationSyntax); + TypeScript.GetMemberAccessorDeclarationSyntax = GetMemberAccessorDeclarationSyntax; + + var SetMemberAccessorDeclarationSyntax = (function (_super) { + __extends(SetMemberAccessorDeclarationSyntax, _super); + function SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, modifiers, propertyName, parameterList, block, parsedInStrictMode); + this.setKeyword = setKeyword; + } + SetMemberAccessorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitSetMemberAccessorDeclaration(this); + }; + + SetMemberAccessorDeclarationSyntax.prototype.kind = function () { + return 139 /* SetMemberAccessorDeclaration */; + }; + + SetMemberAccessorDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + SetMemberAccessorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.setKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetMemberAccessorDeclarationSyntax.prototype.update = function (modifiers, setKeyword, propertyName, parameterList, block) { + if (this.modifiers === modifiers && this.setKeyword === setKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.block === block) { + return this; + } + + return new SetMemberAccessorDeclarationSyntax(modifiers, setKeyword, propertyName, parameterList, block, this.parsedInStrictMode()); + }; + + SetMemberAccessorDeclarationSyntax.create = function (setKeyword, propertyName, parameterList, block) { + return new SetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, setKeyword, propertyName, parameterList, block, false); + }; + + SetMemberAccessorDeclarationSyntax.create1 = function (propertyName) { + return new SetMemberAccessorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(69 /* SetKeyword */), propertyName, ParameterListSyntax.create1(), BlockSyntax.create1(), false); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(this.modifiers, setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.setKeyword, propertyName, this.parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, parameterList, this.block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, this.parameterList, block); + }; + + SetMemberAccessorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SetMemberAccessorDeclarationSyntax; + })(MemberAccessorDeclarationSyntax); + TypeScript.SetMemberAccessorDeclarationSyntax = SetMemberAccessorDeclarationSyntax; + + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + this.semicolonToken = semicolonToken; + } + MemberVariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberVariableDeclaration(this); + }; + + MemberVariableDeclarationSyntax.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + + MemberVariableDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + MemberVariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclarator; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberVariableDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.update = function (modifiers, variableDeclarator, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclarator === variableDeclarator && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, this.parsedInStrictMode()); + }; + + MemberVariableDeclarationSyntax.create = function (variableDeclarator, semicolonToken) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, semicolonToken, false); + }; + + MemberVariableDeclarationSyntax.create1 = function (variableDeclarator) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + MemberVariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberVariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.update(this.modifiers, variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclarator, semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(throwKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.throwKeyword = throwKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ThrowStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitThrowStatement(this); + }; + + ThrowStatementSyntax.prototype.kind = function () { + return 156 /* ThrowStatement */; + }; + + ThrowStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ThrowStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.throwKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ThrowStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.update = function (throwKeyword, expression, semicolonToken) { + if (this.throwKeyword === throwKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ThrowStatementSyntax(throwKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ThrowStatementSyntax.create1 = function (expression) { + return new ThrowStatementSyntax(TypeScript.Syntax.token(36 /* ThrowKeyword */), expression, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ThrowStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withThrowKeyword = function (throwKeyword) { + return this.update(throwKeyword, this.expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.throwKeyword, expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.throwKeyword, this.expression, semicolonToken); + }; + + ThrowStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ThrowStatementSyntax = ThrowStatementSyntax; + + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(returnKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.returnKeyword = returnKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ReturnStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitReturnStatement(this); + }; + + ReturnStatementSyntax.prototype.kind = function () { + return 149 /* ReturnStatement */; + }; + + ReturnStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ReturnStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.returnKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ReturnStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.update = function (returnKeyword, expression, semicolonToken) { + if (this.returnKeyword === returnKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ReturnStatementSyntax(returnKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ReturnStatementSyntax.create = function (returnKeyword, semicolonToken) { + return new ReturnStatementSyntax(returnKeyword, null, semicolonToken, false); + }; + + ReturnStatementSyntax.create1 = function () { + return new ReturnStatementSyntax(TypeScript.Syntax.token(33 /* ReturnKeyword */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ReturnStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withReturnKeyword = function (returnKeyword) { + return this.update(returnKeyword, this.expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.returnKeyword, expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.returnKeyword, this.expression, semicolonToken); + }; + + ReturnStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression !== null && this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ReturnStatementSyntax = ReturnStatementSyntax; + + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.expression = expression; + this.argumentList = argumentList; + } + ObjectCreationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectCreationExpression(this); + }; + + ObjectCreationExpressionSyntax.prototype.kind = function () { + return 215 /* ObjectCreationExpression */; + }; + + ObjectCreationExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectCreationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.expression; + case 2: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectCreationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.update = function (newKeyword, expression, argumentList) { + if (this.newKeyword === newKeyword && this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, this.parsedInStrictMode()); + }; + + ObjectCreationExpressionSyntax.create = function (newKeyword, expression) { + return new ObjectCreationExpressionSyntax(newKeyword, expression, null, false); + }; + + ObjectCreationExpressionSyntax.create1 = function (expression) { + return new ObjectCreationExpressionSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), expression, null, false); + }; + + ObjectCreationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.newKeyword, expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.newKeyword, this.expression, argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList !== null && this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.switchKeyword = switchKeyword; + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.openBraceToken = openBraceToken; + this.switchClauses = switchClauses; + this.closeBraceToken = closeBraceToken; + } + SwitchStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitSwitchStatement(this); + }; + + SwitchStatementSyntax.prototype.kind = function () { + return 150 /* SwitchStatement */; + }; + + SwitchStatementSyntax.prototype.childCount = function () { + return 7; + }; + + SwitchStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.switchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.expression; + case 3: + return this.closeParenToken; + case 4: + return this.openBraceToken; + case 5: + return this.switchClauses; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SwitchStatementSyntax.prototype.isStatement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.update = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + if (this.switchKeyword === switchKeyword && this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken && this.openBraceToken === openBraceToken && this.switchClauses === switchClauses && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, this.parsedInStrictMode()); + }; + + SwitchStatementSyntax.create = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, closeBraceToken) { + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + SwitchStatementSyntax.create1 = function (expression) { + return new SwitchStatementSyntax(TypeScript.Syntax.token(34 /* SwitchKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), expression, TypeScript.Syntax.token(74 /* CloseParenToken */), TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + SwitchStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withSwitchKeyword = function (switchKeyword) { + return this.update(switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.switchKeyword, openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.switchKeyword, this.openParenToken, expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClauses = function (switchClauses) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClause = function (switchClause) { + return this.withSwitchClauses(TypeScript.Syntax.list([switchClause])); + }; + + SwitchStatementSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, closeBraceToken); + }; + + SwitchStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.switchClauses.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchStatementSyntax = SwitchStatementSyntax; + + var SwitchClauseSyntax = (function (_super) { + __extends(SwitchClauseSyntax, _super); + function SwitchClauseSyntax(colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.statements = statements; + } + SwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + SwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return SwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchClauseSyntax = SwitchClauseSyntax; + + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, parsedInStrictMode) { + _super.call(this, colonToken, statements, parsedInStrictMode); + this.caseKeyword = caseKeyword; + this.expression = expression; + } + CaseSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCaseSwitchClause(this); + }; + + CaseSwitchClauseSyntax.prototype.kind = function () { + return 231 /* CaseSwitchClause */; + }; + + CaseSwitchClauseSyntax.prototype.childCount = function () { + return 4; + }; + + CaseSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.caseKeyword; + case 1: + return this.expression; + case 2: + return this.colonToken; + case 3: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CaseSwitchClauseSyntax.prototype.update = function (caseKeyword, expression, colonToken, statements) { + if (this.caseKeyword === caseKeyword && this.expression === expression && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, this.parsedInStrictMode()); + }; + + CaseSwitchClauseSyntax.create = function (caseKeyword, expression, colonToken) { + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.create1 = function (expression) { + return new CaseSwitchClauseSyntax(TypeScript.Syntax.token(16 /* CaseKeyword */), expression, TypeScript.Syntax.token(107 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withCaseKeyword = function (caseKeyword) { + return this.update(caseKeyword, this.expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withExpression = function (expression) { + return this.update(this.caseKeyword, expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.caseKeyword, this.expression, colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.caseKeyword, this.expression, this.colonToken, statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + CaseSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CaseSwitchClauseSyntax; + })(SwitchClauseSyntax); + TypeScript.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, parsedInStrictMode) { + _super.call(this, colonToken, statements, parsedInStrictMode); + this.defaultKeyword = defaultKeyword; + } + DefaultSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitDefaultSwitchClause(this); + }; + + DefaultSwitchClauseSyntax.prototype.kind = function () { + return 232 /* DefaultSwitchClause */; + }; + + DefaultSwitchClauseSyntax.prototype.childCount = function () { + return 3; + }; + + DefaultSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.defaultKeyword; + case 1: + return this.colonToken; + case 2: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DefaultSwitchClauseSyntax.prototype.update = function (defaultKeyword, colonToken, statements) { + if (this.defaultKeyword === defaultKeyword && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, this.parsedInStrictMode()); + }; + + DefaultSwitchClauseSyntax.create = function (defaultKeyword, colonToken) { + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.create1 = function () { + return new DefaultSwitchClauseSyntax(TypeScript.Syntax.token(20 /* DefaultKeyword */), TypeScript.Syntax.token(107 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withDefaultKeyword = function (defaultKeyword) { + return this.update(defaultKeyword, this.colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.defaultKeyword, colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.defaultKeyword, this.colonToken, statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + DefaultSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DefaultSwitchClauseSyntax; + })(SwitchClauseSyntax); + TypeScript.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(breakKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.breakKeyword = breakKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + BreakStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitBreakStatement(this); + }; + + BreakStatementSyntax.prototype.kind = function () { + return 151 /* BreakStatement */; + }; + + BreakStatementSyntax.prototype.childCount = function () { + return 3; + }; + + BreakStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.breakKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BreakStatementSyntax.prototype.isStatement = function () { + return true; + }; + + BreakStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + BreakStatementSyntax.prototype.update = function (breakKeyword, identifier, semicolonToken) { + if (this.breakKeyword === breakKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new BreakStatementSyntax(breakKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + BreakStatementSyntax.create = function (breakKeyword, semicolonToken) { + return new BreakStatementSyntax(breakKeyword, null, semicolonToken, false); + }; + + BreakStatementSyntax.create1 = function () { + return new BreakStatementSyntax(TypeScript.Syntax.token(15 /* BreakKeyword */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + BreakStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withBreakKeyword = function (breakKeyword) { + return this.update(breakKeyword, this.identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.breakKeyword, identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.breakKeyword, this.identifier, semicolonToken); + }; + + BreakStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BreakStatementSyntax = BreakStatementSyntax; + + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.continueKeyword = continueKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ContinueStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitContinueStatement(this); + }; + + ContinueStatementSyntax.prototype.kind = function () { + return 152 /* ContinueStatement */; + }; + + ContinueStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ContinueStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.continueKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ContinueStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.update = function (continueKeyword, identifier, semicolonToken) { + if (this.continueKeyword === continueKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ContinueStatementSyntax.create = function (continueKeyword, semicolonToken) { + return new ContinueStatementSyntax(continueKeyword, null, semicolonToken, false); + }; + + ContinueStatementSyntax.create1 = function () { + return new ContinueStatementSyntax(TypeScript.Syntax.token(18 /* ContinueKeyword */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + ContinueStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withContinueKeyword = function (continueKeyword) { + return this.update(continueKeyword, this.identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.continueKeyword, identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.continueKeyword, this.identifier, semicolonToken); + }; + + ContinueStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ContinueStatementSyntax = ContinueStatementSyntax; + + var IterationStatementSyntax = (function (_super) { + __extends(IterationStatementSyntax, _super); + function IterationStatementSyntax(openParenToken, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + IterationStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IterationStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IterationStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IterationStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IterationStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return IterationStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IterationStatementSyntax = IterationStatementSyntax; + + var BaseForStatementSyntax = (function (_super) { + __extends(BaseForStatementSyntax, _super); + function BaseForStatementSyntax(forKeyword, openParenToken, variableDeclaration, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, openParenToken, closeParenToken, statement, parsedInStrictMode); + this.forKeyword = forKeyword; + this.variableDeclaration = variableDeclaration; + } + BaseForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BaseForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BaseForStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BaseForStatementSyntax; + })(IterationStatementSyntax); + TypeScript.BaseForStatementSyntax = BaseForStatementSyntax; + + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, forKeyword, openParenToken, variableDeclaration, closeParenToken, statement, parsedInStrictMode); + this.initializer = initializer; + this.firstSemicolonToken = firstSemicolonToken; + this.condition = condition; + this.secondSemicolonToken = secondSemicolonToken; + this.incrementor = incrementor; + } + ForStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForStatement(this); + }; + + ForStatementSyntax.prototype.kind = function () { + return 153 /* ForStatement */; + }; + + ForStatementSyntax.prototype.childCount = function () { + return 10; + }; + + ForStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.initializer; + case 4: + return this.firstSemicolonToken; + case 5: + return this.condition; + case 6: + return this.secondSemicolonToken; + case 7: + return this.incrementor; + case 8: + return this.closeParenToken; + case 9: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.initializer === initializer && this.firstSemicolonToken === firstSemicolonToken && this.condition === condition && this.secondSemicolonToken === secondSemicolonToken && this.incrementor === incrementor && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForStatementSyntax.create = function (forKeyword, openParenToken, firstSemicolonToken, secondSemicolonToken, closeParenToken, statement) { + return new ForStatementSyntax(forKeyword, openParenToken, null, null, firstSemicolonToken, null, secondSemicolonToken, null, closeParenToken, statement, false); + }; + + ForStatementSyntax.create1 = function (statement) { + return new ForStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), null, null, TypeScript.Syntax.token(79 /* SemicolonToken */), null, TypeScript.Syntax.token(79 /* SemicolonToken */), null, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + ForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withInitializer = function (initializer) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withFirstSemicolonToken = function (firstSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withSecondSemicolonToken = function (secondSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withIncrementor = function (incrementor) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, statement); + }; + + ForStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.initializer !== null && this.initializer.isTypeScriptSpecific()) { + return true; + } + if (this.condition !== null && this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.incrementor !== null && this.incrementor.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForStatementSyntax; + })(BaseForStatementSyntax); + TypeScript.ForStatementSyntax = ForStatementSyntax; + + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, forKeyword, openParenToken, variableDeclaration, closeParenToken, statement, parsedInStrictMode); + this.left = left; + this.inKeyword = inKeyword; + this.expression = expression; + } + ForInStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForInStatement(this); + }; + + ForInStatementSyntax.prototype.kind = function () { + return 154 /* ForInStatement */; + }; + + ForInStatementSyntax.prototype.childCount = function () { + return 8; + }; + + ForInStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.left; + case 4: + return this.inKeyword; + case 5: + return this.expression; + case 6: + return this.closeParenToken; + case 7: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForInStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.left === left && this.inKeyword === inKeyword && this.expression === expression && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForInStatementSyntax.create = function (forKeyword, openParenToken, inKeyword, expression, closeParenToken, statement) { + return new ForInStatementSyntax(forKeyword, openParenToken, null, null, inKeyword, expression, closeParenToken, statement, false); + }; + + ForInStatementSyntax.create1 = function (expression, statement) { + return new ForInStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), null, null, TypeScript.Syntax.token(29 /* InKeyword */), expression, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + ForInStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withLeft = function (left) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withInKeyword = function (inKeyword) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, statement); + }; + + ForInStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.left !== null && this.left.isTypeScriptSpecific()) { + return true; + } + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForInStatementSyntax; + })(BaseForStatementSyntax); + TypeScript.ForInStatementSyntax = ForInStatementSyntax; + + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, openParenToken, closeParenToken, statement, parsedInStrictMode); + this.whileKeyword = whileKeyword; + this.condition = condition; + } + WhileStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWhileStatement(this); + }; + + WhileStatementSyntax.prototype.kind = function () { + return 157 /* WhileStatement */; + }; + + WhileStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WhileStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.whileKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WhileStatementSyntax.prototype.update = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WhileStatementSyntax.create1 = function (condition, statement) { + return new WhileStatementSyntax(TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + WhileStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WhileStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WhileStatementSyntax; + })(IterationStatementSyntax); + TypeScript.WhileStatementSyntax = WhileStatementSyntax; + + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.withKeyword = withKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WithStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWithStatement(this); + }; + + WithStatementSyntax.prototype.kind = function () { + return 162 /* WithStatement */; + }; + + WithStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WithStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.withKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WithStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WithStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WithStatementSyntax.prototype.update = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.withKeyword === withKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WithStatementSyntax.create1 = function (condition, statement) { + return new WithStatementSyntax(TypeScript.Syntax.token(43 /* WithKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), statement, false); + }; + + WithStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withWithKeyword = function (withKeyword) { + return this.update(withKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.withKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.withKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.withKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.withKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WithStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WithStatementSyntax = WithStatementSyntax; + + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.enumKeyword = enumKeyword; + this.identifier = identifier; + this.openBraceToken = openBraceToken; + this.enumElements = enumElements; + this.closeBraceToken = closeBraceToken; + } + EnumDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumDeclaration(this); + }; + + EnumDeclarationSyntax.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + + EnumDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + EnumDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.enumKeyword; + case 2: + return this.identifier; + case 3: + return this.openBraceToken; + case 4: + return this.enumElements; + case 5: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + EnumDeclarationSyntax.prototype.update = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + if (this.modifiers === modifiers && this.enumKeyword === enumKeyword && this.identifier === identifier && this.openBraceToken === openBraceToken && this.enumElements === enumElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, this.parsedInStrictMode()); + }; + + EnumDeclarationSyntax.create = function (enumKeyword, identifier, openBraceToken, closeBraceToken) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, enumKeyword, identifier, openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + EnumDeclarationSyntax.create1 = function (identifier) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(46 /* EnumKeyword */), identifier, TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + EnumDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + EnumDeclarationSyntax.prototype.withEnumKeyword = function (enumKeyword) { + return this.update(this.modifiers, enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.enumKeyword, identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElements = function (enumElements) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElement = function (enumElement) { + return this.withEnumElements(TypeScript.Syntax.separatedList([enumElement])); + }; + + EnumDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumDeclarationSyntax = EnumDeclarationSyntax; + + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(propertyName, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + } + EnumElementSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumElement(this); + }; + + EnumElementSyntax.prototype.kind = function () { + return 243 /* EnumElement */; + }; + + EnumElementSyntax.prototype.childCount = function () { + return 2; + }; + + EnumElementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumElementSyntax.prototype.update = function (propertyName, equalsValueClause) { + if (this.propertyName === propertyName && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new EnumElementSyntax(propertyName, equalsValueClause, this.parsedInStrictMode()); + }; + + EnumElementSyntax.create = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.create1 = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.equalsValueClause); + }; + + EnumElementSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, equalsValueClause); + }; + + EnumElementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumElementSyntax = EnumElementSyntax; + + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.type = type; + this.greaterThanToken = greaterThanToken; + this.expression = expression; + } + CastExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitCastExpression(this); + }; + + CastExpressionSyntax.prototype.kind = function () { + return 219 /* CastExpression */; + }; + + CastExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + CastExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.type; + case 2: + return this.greaterThanToken; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CastExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.update = function (lessThanToken, type, greaterThanToken, expression) { + if (this.lessThanToken === lessThanToken && this.type === type && this.greaterThanToken === greaterThanToken && this.expression === expression) { + return this; + } + + return new CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, this.parsedInStrictMode()); + }; + + CastExpressionSyntax.create1 = function (type, expression) { + return new CastExpressionSyntax(TypeScript.Syntax.token(81 /* LessThanToken */), type, TypeScript.Syntax.token(82 /* GreaterThanToken */), expression, false); + }; + + CastExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withType = function (type) { + return this.update(this.lessThanToken, type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.type, greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.lessThanToken, this.type, this.greaterThanToken, expression); + }; + + CastExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CastExpressionSyntax = CastExpressionSyntax; + + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.propertyAssignments = propertyAssignments; + this.closeBraceToken = closeBraceToken; + } + ObjectLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectLiteralExpression(this); + }; + + ObjectLiteralExpressionSyntax.prototype.kind = function () { + return 214 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.propertyAssignments; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.update = function (openBraceToken, propertyAssignments, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.propertyAssignments === propertyAssignments && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectLiteralExpressionSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectLiteralExpressionSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectLiteralExpressionSyntax.create1 = function () { + return new ObjectLiteralExpressionSyntax(TypeScript.Syntax.token(71 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(72 /* CloseBraceToken */), false); + }; + + ObjectLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignments = function (propertyAssignments) { + return this.update(this.openBraceToken, propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignment = function (propertyAssignment) { + return this.withPropertyAssignments(TypeScript.Syntax.separatedList([propertyAssignment])); + }; + + ObjectLiteralExpressionSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.propertyAssignments, closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.propertyAssignments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + + var PropertyAssignmentSyntax = (function (_super) { + __extends(PropertyAssignmentSyntax, _super); + function PropertyAssignmentSyntax(propertyName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + } + PropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return PropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertyAssignmentSyntax = PropertyAssignmentSyntax; + + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, parsedInStrictMode) { + _super.call(this, propertyName, parsedInStrictMode); + this.colonToken = colonToken; + this.expression = expression; + } + SimplePropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSimplePropertyAssignment(this); + }; + + SimplePropertyAssignmentSyntax.prototype.kind = function () { + return 238 /* SimplePropertyAssignment */; + }; + + SimplePropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + SimplePropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.colonToken; + case 2: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimplePropertyAssignmentSyntax.prototype.update = function (propertyName, colonToken, expression) { + if (this.propertyName === propertyName && this.colonToken === colonToken && this.expression === expression) { + return this; + } + + return new SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, this.parsedInStrictMode()); + }; + + SimplePropertyAssignmentSyntax.create1 = function (propertyName, expression) { + return new SimplePropertyAssignmentSyntax(propertyName, TypeScript.Syntax.token(107 /* ColonToken */), expression, false); + }; + + SimplePropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.propertyName, colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withExpression = function (expression) { + return this.update(this.propertyName, this.colonToken, expression); + }; + + SimplePropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SimplePropertyAssignmentSyntax; + })(PropertyAssignmentSyntax); + TypeScript.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, parsedInStrictMode) { + _super.call(this, propertyName, parsedInStrictMode); + this.callSignature = callSignature; + this.block = block; + } + FunctionPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionPropertyAssignment(this); + }; + + FunctionPropertyAssignmentSyntax.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + + FunctionPropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + FunctionPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.callSignature; + case 2: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionPropertyAssignmentSyntax.prototype.update = function (propertyName, callSignature, block) { + if (this.propertyName === propertyName && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionPropertyAssignmentSyntax.create1 = function (propertyName) { + return new FunctionPropertyAssignmentSyntax(propertyName, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.propertyName, this.callSignature, block); + }; + + FunctionPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionPropertyAssignmentSyntax; + })(PropertyAssignmentSyntax); + TypeScript.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + + var AccessorPropertyAssignmentSyntax = (function (_super) { + __extends(AccessorPropertyAssignmentSyntax, _super); + function AccessorPropertyAssignmentSyntax(propertyName, openParenToken, closeParenToken, block, parsedInStrictMode) { + _super.call(this, propertyName, parsedInStrictMode); + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + this.block = block; + } + AccessorPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + AccessorPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + AccessorPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return AccessorPropertyAssignmentSyntax; + })(PropertyAssignmentSyntax); + TypeScript.AccessorPropertyAssignmentSyntax = AccessorPropertyAssignmentSyntax; + + var GetAccessorPropertyAssignmentSyntax = (function (_super) { + __extends(GetAccessorPropertyAssignmentSyntax, _super); + function GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, propertyName, openParenToken, closeParenToken, block, parsedInStrictMode); + this.getKeyword = getKeyword; + this.typeAnnotation = typeAnnotation; + } + GetAccessorPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitGetAccessorPropertyAssignment(this); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.kind = function () { + return 239 /* GetAccessorPropertyAssignment */; + }; + + GetAccessorPropertyAssignmentSyntax.prototype.childCount = function () { + return 6; + }; + + GetAccessorPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.getKeyword; + case 1: + return this.propertyName; + case 2: + return this.openParenToken; + case 3: + return this.closeParenToken; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetAccessorPropertyAssignmentSyntax.prototype.update = function (getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block) { + if (this.getKeyword === getKeyword && this.propertyName === propertyName && this.openParenToken === openParenToken && this.closeParenToken === closeParenToken && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetAccessorPropertyAssignmentSyntax.create = function (getKeyword, propertyName, openParenToken, closeParenToken, block) { + return new GetAccessorPropertyAssignmentSyntax(getKeyword, propertyName, openParenToken, closeParenToken, null, block, false); + }; + + GetAccessorPropertyAssignmentSyntax.create1 = function (propertyName) { + return new GetAccessorPropertyAssignmentSyntax(TypeScript.Syntax.token(65 /* GetKeyword */), propertyName, TypeScript.Syntax.token(73 /* OpenParenToken */), TypeScript.Syntax.token(74 /* CloseParenToken */), null, BlockSyntax.create1(), false); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(getKeyword, this.propertyName, this.openParenToken, this.closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.getKeyword, propertyName, this.openParenToken, this.closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.getKeyword, this.propertyName, openParenToken, this.closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.getKeyword, this.propertyName, this.openParenToken, closeParenToken, this.typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.getKeyword, this.propertyName, this.openParenToken, this.closeParenToken, typeAnnotation, this.block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.getKeyword, this.propertyName, this.openParenToken, this.closeParenToken, this.typeAnnotation, block); + }; + + GetAccessorPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return GetAccessorPropertyAssignmentSyntax; + })(AccessorPropertyAssignmentSyntax); + TypeScript.GetAccessorPropertyAssignmentSyntax = GetAccessorPropertyAssignmentSyntax; + + var SetAccessorPropertyAssignmentSyntax = (function (_super) { + __extends(SetAccessorPropertyAssignmentSyntax, _super); + function SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, parsedInStrictMode) { + _super.call(this, propertyName, openParenToken, closeParenToken, block, parsedInStrictMode); + this.setKeyword = setKeyword; + this.parameter = parameter; + } + SetAccessorPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSetAccessorPropertyAssignment(this); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.kind = function () { + return 240 /* SetAccessorPropertyAssignment */; + }; + + SetAccessorPropertyAssignmentSyntax.prototype.childCount = function () { + return 6; + }; + + SetAccessorPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.setKeyword; + case 1: + return this.propertyName; + case 2: + return this.openParenToken; + case 3: + return this.parameter; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetAccessorPropertyAssignmentSyntax.prototype.update = function (setKeyword, propertyName, openParenToken, parameter, closeParenToken, block) { + if (this.setKeyword === setKeyword && this.propertyName === propertyName && this.openParenToken === openParenToken && this.parameter === parameter && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new SetAccessorPropertyAssignmentSyntax(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block, this.parsedInStrictMode()); + }; + + SetAccessorPropertyAssignmentSyntax.create1 = function (propertyName, parameter) { + return new SetAccessorPropertyAssignmentSyntax(TypeScript.Syntax.token(69 /* SetKeyword */), propertyName, TypeScript.Syntax.token(73 /* OpenParenToken */), parameter, TypeScript.Syntax.token(74 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(setKeyword, this.propertyName, this.openParenToken, this.parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.setKeyword, propertyName, this.openParenToken, this.parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.setKeyword, this.propertyName, openParenToken, this.parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withParameter = function (parameter) { + return this.update(this.setKeyword, this.propertyName, this.openParenToken, parameter, this.closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.setKeyword, this.propertyName, this.openParenToken, this.parameter, closeParenToken, this.block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.setKeyword, this.propertyName, this.openParenToken, this.parameter, this.closeParenToken, block); + }; + + SetAccessorPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameter.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SetAccessorPropertyAssignmentSyntax; + })(AccessorPropertyAssignmentSyntax); + TypeScript.SetAccessorPropertyAssignmentSyntax = SetAccessorPropertyAssignmentSyntax; + + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + } + FunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionExpression(this); + }; + + FunctionExpressionSyntax.prototype.kind = function () { + return 221 /* FunctionExpression */; + }; + + FunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.functionKeyword; + case 1: + return this.identifier; + case 2: + return this.callSignature; + case 3: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.update = function (functionKeyword, identifier, callSignature, block) { + if (this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionExpressionSyntax.create = function (functionKeyword, callSignature, block) { + return new FunctionExpressionSyntax(functionKeyword, null, callSignature, block, false); + }; + + FunctionExpressionSyntax.create1 = function () { + return new FunctionExpressionSyntax(TypeScript.Syntax.token(27 /* FunctionKeyword */), null, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(functionKeyword, this.identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.functionKeyword, identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.functionKeyword, this.identifier, callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.functionKeyword, this.identifier, this.callSignature, block); + }; + + FunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionExpressionSyntax = FunctionExpressionSyntax; + + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.semicolonToken = semicolonToken; + } + EmptyStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitEmptyStatement(this); + }; + + EmptyStatementSyntax.prototype.kind = function () { + return 155 /* EmptyStatement */; + }; + + EmptyStatementSyntax.prototype.childCount = function () { + return 1; + }; + + EmptyStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EmptyStatementSyntax.prototype.isStatement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.update = function (semicolonToken) { + if (this.semicolonToken === semicolonToken) { + return this; + } + + return new EmptyStatementSyntax(semicolonToken, this.parsedInStrictMode()); + }; + + EmptyStatementSyntax.create1 = function () { + return new EmptyStatementSyntax(TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + EmptyStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(semicolonToken); + }; + + EmptyStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EmptyStatementSyntax = EmptyStatementSyntax; + + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.tryKeyword = tryKeyword; + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + } + TryStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitTryStatement(this); + }; + + TryStatementSyntax.prototype.kind = function () { + return 158 /* TryStatement */; + }; + + TryStatementSyntax.prototype.childCount = function () { + return 4; + }; + + TryStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.tryKeyword; + case 1: + return this.block; + case 2: + return this.catchClause; + case 3: + return this.finallyClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TryStatementSyntax.prototype.isStatement = function () { + return true; + }; + + TryStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + TryStatementSyntax.prototype.update = function (tryKeyword, block, catchClause, finallyClause) { + if (this.tryKeyword === tryKeyword && this.block === block && this.catchClause === catchClause && this.finallyClause === finallyClause) { + return this; + } + + return new TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, this.parsedInStrictMode()); + }; + + TryStatementSyntax.create = function (tryKeyword, block) { + return new TryStatementSyntax(tryKeyword, block, null, null, false); + }; + + TryStatementSyntax.create1 = function () { + return new TryStatementSyntax(TypeScript.Syntax.token(38 /* TryKeyword */), BlockSyntax.create1(), null, null, false); + }; + + TryStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTryKeyword = function (tryKeyword) { + return this.update(tryKeyword, this.block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withBlock = function (block) { + return this.update(this.tryKeyword, block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withCatchClause = function (catchClause) { + return this.update(this.tryKeyword, this.block, catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withFinallyClause = function (finallyClause) { + return this.update(this.tryKeyword, this.block, this.catchClause, finallyClause); + }; + + TryStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + if (this.catchClause !== null && this.catchClause.isTypeScriptSpecific()) { + return true; + } + if (this.finallyClause !== null && this.finallyClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TryStatementSyntax = TryStatementSyntax; + + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.catchKeyword = catchKeyword; + this.openParenToken = openParenToken; + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.closeParenToken = closeParenToken; + this.block = block; + } + CatchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCatchClause(this); + }; + + CatchClauseSyntax.prototype.kind = function () { + return 234 /* CatchClause */; + }; + + CatchClauseSyntax.prototype.childCount = function () { + return 6; + }; + + CatchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.catchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.identifier; + case 3: + return this.typeAnnotation; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CatchClauseSyntax.prototype.update = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + if (this.catchKeyword === catchKeyword && this.openParenToken === openParenToken && this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, this.parsedInStrictMode()); + }; + + CatchClauseSyntax.create = function (catchKeyword, openParenToken, identifier, closeParenToken, block) { + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, null, closeParenToken, block, false); + }; + + CatchClauseSyntax.create1 = function (identifier) { + return new CatchClauseSyntax(TypeScript.Syntax.token(17 /* CatchKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), identifier, null, TypeScript.Syntax.token(74 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + CatchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withCatchKeyword = function (catchKeyword) { + return this.update(catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.catchKeyword, openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.catchKeyword, this.openParenToken, identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, block); + }; + + CatchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CatchClauseSyntax = CatchClauseSyntax; + + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(finallyKeyword, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.finallyKeyword = finallyKeyword; + this.block = block; + } + FinallyClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitFinallyClause(this); + }; + + FinallyClauseSyntax.prototype.kind = function () { + return 235 /* FinallyClause */; + }; + + FinallyClauseSyntax.prototype.childCount = function () { + return 2; + }; + + FinallyClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.finallyKeyword; + case 1: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FinallyClauseSyntax.prototype.update = function (finallyKeyword, block) { + if (this.finallyKeyword === finallyKeyword && this.block === block) { + return this; + } + + return new FinallyClauseSyntax(finallyKeyword, block, this.parsedInStrictMode()); + }; + + FinallyClauseSyntax.create1 = function () { + return new FinallyClauseSyntax(TypeScript.Syntax.token(25 /* FinallyKeyword */), BlockSyntax.create1(), false); + }; + + FinallyClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withFinallyKeyword = function (finallyKeyword) { + return this.update(finallyKeyword, this.block); + }; + + FinallyClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.finallyKeyword, block); + }; + + FinallyClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FinallyClauseSyntax = FinallyClauseSyntax; + + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(identifier, colonToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.colonToken = colonToken; + this.statement = statement; + } + LabeledStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitLabeledStatement(this); + }; + + LabeledStatementSyntax.prototype.kind = function () { + return 159 /* LabeledStatement */; + }; + + LabeledStatementSyntax.prototype.childCount = function () { + return 3; + }; + + LabeledStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.colonToken; + case 2: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + LabeledStatementSyntax.prototype.isStatement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.update = function (identifier, colonToken, statement) { + if (this.identifier === identifier && this.colonToken === colonToken && this.statement === statement) { + return this; + } + + return new LabeledStatementSyntax(identifier, colonToken, statement, this.parsedInStrictMode()); + }; + + LabeledStatementSyntax.create1 = function (identifier, statement) { + return new LabeledStatementSyntax(identifier, TypeScript.Syntax.token(107 /* ColonToken */), statement, false); + }; + + LabeledStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.identifier, colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.identifier, this.colonToken, statement); + }; + + LabeledStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.LabeledStatementSyntax = LabeledStatementSyntax; + + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, parsedInStrictMode) { + _super.call(this, openParenToken, closeParenToken, statement, parsedInStrictMode); + this.doKeyword = doKeyword; + this.whileKeyword = whileKeyword; + this.condition = condition; + this.semicolonToken = semicolonToken; + } + DoStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDoStatement(this); + }; + + DoStatementSyntax.prototype.kind = function () { + return 160 /* DoStatement */; + }; + + DoStatementSyntax.prototype.childCount = function () { + return 7; + }; + + DoStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.doKeyword; + case 1: + return this.statement; + case 2: + return this.whileKeyword; + case 3: + return this.openParenToken; + case 4: + return this.condition; + case 5: + return this.closeParenToken; + case 6: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DoStatementSyntax.prototype.update = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + if (this.doKeyword === doKeyword && this.statement === statement && this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.semicolonToken === semicolonToken) { + return this; + } + + return new DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, this.parsedInStrictMode()); + }; + + DoStatementSyntax.create1 = function (statement, condition) { + return new DoStatementSyntax(TypeScript.Syntax.token(22 /* DoKeyword */), statement, TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(73 /* OpenParenToken */), condition, TypeScript.Syntax.token(74 /* CloseParenToken */), TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + DoStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withDoKeyword = function (doKeyword) { + return this.update(doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.doKeyword, statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(this.doKeyword, this.statement, whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, semicolonToken); + }; + + DoStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.condition.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DoStatementSyntax; + })(IterationStatementSyntax); + TypeScript.DoStatementSyntax = DoStatementSyntax; + + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(typeOfKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.expression = expression; + } + TypeOfExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeOfExpression(this); + }; + + TypeOfExpressionSyntax.prototype.kind = function () { + return 170 /* TypeOfExpression */; + }; + + TypeOfExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + TypeOfExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeOfExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.update = function (typeOfKeyword, expression) { + if (this.typeOfKeyword === typeOfKeyword && this.expression === expression) { + return this; + } + + return new TypeOfExpressionSyntax(typeOfKeyword, expression, this.parsedInStrictMode()); + }; + + TypeOfExpressionSyntax.create1 = function (expression) { + return new TypeOfExpressionSyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), expression, false); + }; + + TypeOfExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.expression); + }; + + TypeOfExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.typeOfKeyword, expression); + }; + + TypeOfExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(deleteKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.deleteKeyword = deleteKeyword; + this.expression = expression; + } + DeleteExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitDeleteExpression(this); + }; + + DeleteExpressionSyntax.prototype.kind = function () { + return 169 /* DeleteExpression */; + }; + + DeleteExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + DeleteExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.deleteKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DeleteExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.update = function (deleteKeyword, expression) { + if (this.deleteKeyword === deleteKeyword && this.expression === expression) { + return this; + } + + return new DeleteExpressionSyntax(deleteKeyword, expression, this.parsedInStrictMode()); + }; + + DeleteExpressionSyntax.create1 = function (expression) { + return new DeleteExpressionSyntax(TypeScript.Syntax.token(21 /* DeleteKeyword */), expression, false); + }; + + DeleteExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withDeleteKeyword = function (deleteKeyword) { + return this.update(deleteKeyword, this.expression); + }; + + DeleteExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.deleteKeyword, expression); + }; + + DeleteExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DeleteExpressionSyntax = DeleteExpressionSyntax; + + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(voidKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.voidKeyword = voidKeyword; + this.expression = expression; + } + VoidExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitVoidExpression(this); + }; + + VoidExpressionSyntax.prototype.kind = function () { + return 171 /* VoidExpression */; + }; + + VoidExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + VoidExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.voidKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VoidExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.update = function (voidKeyword, expression) { + if (this.voidKeyword === voidKeyword && this.expression === expression) { + return this; + } + + return new VoidExpressionSyntax(voidKeyword, expression, this.parsedInStrictMode()); + }; + + VoidExpressionSyntax.create1 = function (expression) { + return new VoidExpressionSyntax(TypeScript.Syntax.token(41 /* VoidKeyword */), expression, false); + }; + + VoidExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withVoidKeyword = function (voidKeyword) { + return this.update(voidKeyword, this.expression); + }; + + VoidExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.voidKeyword, expression); + }; + + VoidExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VoidExpressionSyntax = VoidExpressionSyntax; + + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(debuggerKeyword, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.debuggerKeyword = debuggerKeyword; + this.semicolonToken = semicolonToken; + } + DebuggerStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDebuggerStatement(this); + }; + + DebuggerStatementSyntax.prototype.kind = function () { + return 161 /* DebuggerStatement */; + }; + + DebuggerStatementSyntax.prototype.childCount = function () { + return 2; + }; + + DebuggerStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.debuggerKeyword; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DebuggerStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.update = function (debuggerKeyword, semicolonToken) { + if (this.debuggerKeyword === debuggerKeyword && this.semicolonToken === semicolonToken) { + return this; + } + + return new DebuggerStatementSyntax(debuggerKeyword, semicolonToken, this.parsedInStrictMode()); + }; + + DebuggerStatementSyntax.create1 = function () { + return new DebuggerStatementSyntax(TypeScript.Syntax.token(19 /* DebuggerKeyword */), TypeScript.Syntax.token(79 /* SemicolonToken */), false); + }; + + DebuggerStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withDebuggerKeyword = function (debuggerKeyword) { + return this.update(debuggerKeyword, this.semicolonToken); + }; + + DebuggerStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.debuggerKeyword, semicolonToken); + }; + + DebuggerStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DebuggerStatementSyntax = DebuggerStatementSyntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxRewriter = (function () { + function SyntaxRewriter() { + } + SyntaxRewriter.prototype.visitToken = function (token) { + return token; + }; + + SyntaxRewriter.prototype.visitNode = function (node) { + return node.accept(this); + }; + + SyntaxRewriter.prototype.visitNodeOrToken = function (node) { + return node.isToken() ? this.visitToken(node) : this.visitNode(node); + }; + + SyntaxRewriter.prototype.visitList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = this.visitNodeOrToken(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.list(newItems); + }; + + SyntaxRewriter.prototype.visitSeparatedList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = item.isToken() ? this.visitToken(item) : this.visitNode(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.separatedList(newItems); + }; + + SyntaxRewriter.prototype.visitSourceUnit = function (node) { + return node.update(this.visitList(node.moduleElements), this.visitToken(node.endOfFileToken)); + }; + + SyntaxRewriter.prototype.visitExternalModuleReference = function (node) { + return node.update(this.visitToken(node.moduleOrRequireKeyword), this.visitToken(node.openParenToken), this.visitToken(node.stringLiteral), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitModuleNameModuleReference = function (node) { + return node.update(this.visitNodeOrToken(node.moduleName)); + }; + + SyntaxRewriter.prototype.visitImportDeclaration = function (node) { + return node.update(this.visitToken(node.importKeyword), this.visitToken(node.identifier), this.visitToken(node.equalsToken), this.visitNode(node.moduleReference), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitExportAssignment = function (node) { + return node.update(this.visitToken(node.exportKeyword), this.visitToken(node.equalsToken), this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitClassDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.classKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitToken(node.openBraceToken), this.visitList(node.classElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitInterfaceDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.interfaceKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitNode(node.body)); + }; + + SyntaxRewriter.prototype.visitHeritageClause = function (node) { + return node.update(this.visitToken(node.extendsOrImplementsKeyword), this.visitSeparatedList(node.typeNames)); + }; + + SyntaxRewriter.prototype.visitModuleDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.moduleKeyword), node.moduleName === null ? null : this.visitNodeOrToken(node.moduleName), node.stringLiteral === null ? null : this.visitToken(node.stringLiteral), this.visitToken(node.openBraceToken), this.visitList(node.moduleElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.functionKeyword), this.visitToken(node.identifier), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableStatement = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclaration), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableDeclaration = function (node) { + return node.update(this.visitToken(node.varKeyword), this.visitSeparatedList(node.variableDeclarators)); + }; + + SyntaxRewriter.prototype.visitVariableDeclarator = function (node) { + return node.update(this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitEqualsValueClause = function (node) { + return node.update(this.visitToken(node.equalsToken), this.visitNodeOrToken(node.value)); + }; + + SyntaxRewriter.prototype.visitPrefixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.operand)); + }; + + SyntaxRewriter.prototype.visitArrayLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitSeparatedList(node.expressions), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitOmittedExpression = function (node) { + return node; + }; + + SyntaxRewriter.prototype.visitParenthesizedExpression = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitSimpleArrowFunctionExpression = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.body)); + }; + + SyntaxRewriter.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return node.update(this.visitNode(node.callSignature), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.body)); + }; + + SyntaxRewriter.prototype.visitQualifiedName = function (node) { + return node.update(this.visitNodeOrToken(node.left), this.visitToken(node.dotToken), this.visitToken(node.right)); + }; + + SyntaxRewriter.prototype.visitTypeArgumentList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeArguments), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitConstructorType = function (node) { + return node.update(this.visitToken(node.newKeyword), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitFunctionType = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitObjectType = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.typeMembers), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitArrayType = function (node) { + return node.update(this.visitNodeOrToken(node.type), this.visitToken(node.openBracketToken), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitGenericType = function (node) { + return node.update(this.visitNodeOrToken(node.name), this.visitNode(node.typeArgumentList)); + }; + + SyntaxRewriter.prototype.visitTypeAnnotation = function (node) { + return node.update(this.visitToken(node.colonToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitBlock = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitList(node.statements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitParameter = function (node) { + return node.update(node.dotDotDotToken === null ? null : this.visitToken(node.dotDotDotToken), node.publicOrPrivateKeyword === null ? null : this.visitToken(node.publicOrPrivateKeyword), this.visitToken(node.identifier), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitMemberAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.dotToken), this.visitToken(node.name)); + }; + + SyntaxRewriter.prototype.visitPostfixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.operand), this.visitToken(node.operatorToken)); + }; + + SyntaxRewriter.prototype.visitElementAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.openBracketToken), this.visitNodeOrToken(node.argumentExpression), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitInvocationExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitArgumentList = function (node) { + return node.update(node.typeArgumentList === null ? null : this.visitNode(node.typeArgumentList), this.visitToken(node.openParenToken), this.visitSeparatedList(node.arguments), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitBinaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.left), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.right)); + }; + + SyntaxRewriter.prototype.visitConditionalExpression = function (node) { + return node.update(this.visitNodeOrToken(node.condition), this.visitToken(node.questionToken), this.visitNodeOrToken(node.whenTrue), this.visitToken(node.colonToken), this.visitNodeOrToken(node.whenFalse)); + }; + + SyntaxRewriter.prototype.visitConstructSignature = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitMethodSignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitIndexSignature = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitNode(node.parameter), this.visitToken(node.closeBracketToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitPropertySignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitCallSignature = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitParameterList = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitSeparatedList(node.parameters), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameterList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeParameters), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameter = function (node) { + return node.update(this.visitToken(node.identifier), node.constraint === null ? null : this.visitNode(node.constraint)); + }; + + SyntaxRewriter.prototype.visitConstraint = function (node) { + return node.update(this.visitToken(node.extendsKeyword), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitElseClause = function (node) { + return node.update(this.visitToken(node.elseKeyword), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitIfStatement = function (node) { + return node.update(this.visitToken(node.ifKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement), node.elseClause === null ? null : this.visitNode(node.elseClause)); + }; + + SyntaxRewriter.prototype.visitExpressionStatement = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { + return node.update(this.visitToken(node.constructorKeyword), this.visitNode(node.parameterList), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.propertyName), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitGetMemberAccessorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetMemberAccessorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitMemberVariableDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclarator), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitThrowStatement = function (node) { + return node.update(this.visitToken(node.throwKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitReturnStatement = function (node) { + return node.update(this.visitToken(node.returnKeyword), node.expression === null ? null : this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitObjectCreationExpression = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNodeOrToken(node.expression), node.argumentList === null ? null : this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitSwitchStatement = function (node) { + return node.update(this.visitToken(node.switchKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitToken(node.openBraceToken), this.visitList(node.switchClauses), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitCaseSwitchClause = function (node) { + return node.update(this.visitToken(node.caseKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitDefaultSwitchClause = function (node) { + return node.update(this.visitToken(node.defaultKeyword), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitBreakStatement = function (node) { + return node.update(this.visitToken(node.breakKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitContinueStatement = function (node) { + return node.update(this.visitToken(node.continueKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitForStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.initializer === null ? null : this.visitNodeOrToken(node.initializer), this.visitToken(node.firstSemicolonToken), node.condition === null ? null : this.visitNodeOrToken(node.condition), this.visitToken(node.secondSemicolonToken), node.incrementor === null ? null : this.visitNodeOrToken(node.incrementor), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitForInStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.left === null ? null : this.visitNodeOrToken(node.left), this.visitToken(node.inKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWhileStatement = function (node) { + return node.update(this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWithStatement = function (node) { + return node.update(this.visitToken(node.withKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitEnumDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.enumKeyword), this.visitToken(node.identifier), this.visitToken(node.openBraceToken), this.visitSeparatedList(node.enumElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitEnumElement = function (node) { + return node.update(this.visitToken(node.propertyName), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitCastExpression = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitNodeOrToken(node.type), this.visitToken(node.greaterThanToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitObjectLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.propertyAssignments), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitSimplePropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitToken(node.colonToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitFunctionPropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitGetAccessorPropertyAssignment = function (node) { + return node.update(this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitToken(node.openParenToken), this.visitToken(node.closeParenToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetAccessorPropertyAssignment = function (node) { + return node.update(this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitToken(node.openParenToken), this.visitNode(node.parameter), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFunctionExpression = function (node) { + return node.update(this.visitToken(node.functionKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitEmptyStatement = function (node) { + return node.update(this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTryStatement = function (node) { + return node.update(this.visitToken(node.tryKeyword), this.visitNode(node.block), node.catchClause === null ? null : this.visitNode(node.catchClause), node.finallyClause === null ? null : this.visitNode(node.finallyClause)); + }; + + SyntaxRewriter.prototype.visitCatchClause = function (node) { + return node.update(this.visitToken(node.catchKeyword), this.visitToken(node.openParenToken), this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFinallyClause = function (node) { + return node.update(this.visitToken(node.finallyKeyword), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitLabeledStatement = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.colonToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitDoStatement = function (node) { + return node.update(this.visitToken(node.doKeyword), this.visitNodeOrToken(node.statement), this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTypeOfExpression = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDeleteExpression = function (node) { + return node.update(this.visitToken(node.deleteKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitVoidExpression = function (node) { + return node.update(this.visitToken(node.voidKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDebuggerStatement = function (node) { + return node.update(this.visitToken(node.debuggerKeyword), this.visitToken(node.semicolonToken)); + }; + return SyntaxRewriter; + })(); + TypeScript.SyntaxRewriter = SyntaxRewriter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDedenter = (function (_super) { + __extends(SyntaxDedenter, _super); + function SyntaxDedenter(dedentFirstToken, dedentationAmount, minimumIndent, options) { + _super.call(this); + this.dedentationAmount = dedentationAmount; + this.minimumIndent = minimumIndent; + this.options = options; + this.lastTriviaWasNewLine = dedentFirstToken; + } + SyntaxDedenter.prototype.abort = function () { + this.lastTriviaWasNewLine = false; + this.dedentationAmount = 0; + }; + + SyntaxDedenter.prototype.isAborted = function () { + return this.dedentationAmount === 0; + }; + + SyntaxDedenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.dedentTriviaList(token.leadingTrivia())); + } + + if (this.isAborted()) { + return token; + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxDedenter.prototype.dedentTriviaList = function (triviaList) { + var result = []; + var dedentNextWhitespace = true; + + for (var i = 0, n = triviaList.count(); i < n && !this.isAborted(); i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var dedentThisTrivia = dedentNextWhitespace; + dedentNextWhitespace = false; + + if (dedentThisTrivia) { + if (trivia.kind() === 4 /* WhitespaceTrivia */) { + var hasFollowingNewLine = (i < triviaList.count() - 1) && triviaList.syntaxTriviaAt(i + 1).kind() === 5 /* NewLineTrivia */; + result.push(this.dedentWhitespace(trivia, hasFollowingNewLine)); + continue; + } else if (trivia.kind() !== 5 /* NewLineTrivia */) { + this.abort(); + break; + } + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + result.push(this.dedentMultiLineComment(trivia)); + continue; + } + + result.push(trivia); + if (trivia.kind() === 5 /* NewLineTrivia */) { + dedentNextWhitespace = true; + } + } + + if (dedentNextWhitespace) { + this.abort(); + } + + if (this.isAborted()) { + return triviaList; + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxDedenter.prototype.dedentSegment = function (segment, hasFollowingNewLineTrivia) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition === segment.length) { + if (hasFollowingNewLineTrivia) { + return ""; + } + } else if (TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment.substring(firstNonWhitespacePosition); + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = TypeScript.MathPrototype.min(firstNonWhitespaceColumn, TypeScript.MathPrototype.max(firstNonWhitespaceColumn - this.dedentationAmount, this.minimumIndent)); + + if (newFirstNonWhitespaceColumn === firstNonWhitespaceColumn) { + this.abort(); + return segment; + } + + this.dedentationAmount = firstNonWhitespaceColumn - newFirstNonWhitespaceColumn; + TypeScript.Debug.assert(this.dedentationAmount >= 0); + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxDedenter.prototype.dedentWhitespace = function (trivia, hasFollowingNewLineTrivia) { + var newIndentation = this.dedentSegment(trivia.fullText(), hasFollowingNewLineTrivia); + return TypeScript.Syntax.whitespace(newIndentation); + }; + + SyntaxDedenter.prototype.dedentMultiLineComment = function (trivia) { + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length === 1) { + return trivia; + } + + for (var i = 1; i < segments.length; i++) { + var segment = segments[i]; + segments[i] = this.dedentSegment(segment, false); + } + + var result = segments.join(""); + + return TypeScript.Syntax.multiLineComment(result); + }; + + SyntaxDedenter.dedentNode = function (node, dedentFirstToken, dedentAmount, minimumIndent, options) { + var dedenter = new SyntaxDedenter(dedentFirstToken, dedentAmount, minimumIndent, options); + var result = node.accept(dedenter); + + if (dedenter.isAborted()) { + return node; + } + + return result; + }; + return SyntaxDedenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxDedenter = SyntaxDedenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxIndenter = (function (_super) { + __extends(SyntaxIndenter, _super); + function SyntaxIndenter(indentFirstToken, indentationAmount, options) { + _super.call(this); + this.indentationAmount = indentationAmount; + this.options = options; + this.lastTriviaWasNewLine = indentFirstToken; + this.indentationTrivia = TypeScript.Indentation.indentationTrivia(this.indentationAmount, this.options); + } + SyntaxIndenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.indentTriviaList(token.leadingTrivia())); + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxIndenter.prototype.indentTriviaList = function (triviaList) { + var result = []; + + var indentNextTrivia = true; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var indentThisTrivia = indentNextTrivia; + indentNextTrivia = false; + + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.indentMultiLineComment(trivia, indentThisTrivia, result); + continue; + + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + this.indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + continue; + + case 4 /* WhitespaceTrivia */: + this.indentWhitespace(trivia, indentThisTrivia, result); + continue; + + case 5 /* NewLineTrivia */: + result.push(trivia); + indentNextTrivia = true; + continue; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + if (indentNextTrivia) { + result.push(this.indentationTrivia); + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxIndenter.prototype.indentSegment = function (segment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment; + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = firstNonWhitespaceColumn + this.indentationAmount; + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxIndenter.prototype.indentWhitespace = function (trivia, indentThisTrivia, result) { + if (!indentThisTrivia) { + result.push(trivia); + return; + } + + var newIndentation = this.indentSegment(trivia.fullText()); + result.push(TypeScript.Syntax.whitespace(newIndentation)); + }; + + SyntaxIndenter.prototype.indentSingleLineOrSkippedText = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + result.push(trivia); + }; + + SyntaxIndenter.prototype.indentMultiLineComment = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + + for (var i = 1; i < segments.length; i++) { + segments[i] = this.indentSegment(segments[i]); + } + + var newText = segments.join(""); + result.push(TypeScript.Syntax.multiLineComment(newText)); + }; + + SyntaxIndenter.indentNode = function (node, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + return node.accept(indenter); + }; + + SyntaxIndenter.indentNodes = function (nodes, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + var result = TypeScript.ArrayUtilities.select(nodes, function (n) { + return n.accept(indenter); + }); + + return result; + }; + return SyntaxIndenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxIndenter = SyntaxIndenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var VariableWidthTokenWithNoTrivia = (function () { + function VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, textOrWidth) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._textOrWidth = textOrWidth; + } + VariableWidthTokenWithNoTrivia.prototype.clone = function () { + return new VariableWidthTokenWithNoTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth); + }; + + VariableWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.width(); + }; + VariableWidthTokenWithNoTrivia.prototype.start = function () { + return this._fullStart; + }; + VariableWidthTokenWithNoTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithNoTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithNoTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithNoTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithNoTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithNoTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithNoTrivia; + })(); + Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; + + var VariableWidthTokenWithLeadingTrivia = (function () { + function VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._textOrWidth = textOrWidth; + } + VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + }; + VariableWidthTokenWithLeadingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithLeadingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; + + var VariableWidthTokenWithTrailingTrivia = (function () { + function VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, textOrWidth, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._textOrWidth = textOrWidth; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.start = function () { + return this._fullStart; + }; + VariableWidthTokenWithTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; + + var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { + function VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._textOrWidth = textOrWidth; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + if (typeof this._textOrWidth === 'number') { + this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); + } + + return this._textOrWidth; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + if ((this)._value === undefined) { + (this)._value = Syntax.value(this); + } + + return (this)._value; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + if ((this)._valueText === undefined) { + (this)._valueText = Syntax.valueText(this); + } + + return (this)._valueText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return VariableWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia = VariableWidthTokenWithLeadingAndTrailingTrivia; + + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(kind) { + this.tokenKind = kind; + } + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this.tokenKind); + }; + + FixedWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.width(); + }; + FixedWidthTokenWithNoTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return this.text(); + }; + + FixedWidthTokenWithNoTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithNoTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithNoTrivia; + })(); + Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; + + var FixedWidthTokenWithLeadingTrivia = (function () { + function FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + }; + FixedWidthTokenWithLeadingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithLeadingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; + + var FixedWidthTokenWithTrailingTrivia = (function () { + function FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.start = function () { + return this._fullStart; + }; + FixedWidthTokenWithTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; + + var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { + function FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._sourceText = sourceText; + this._fullStart = fullStart; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { + return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { + return this.start() + this.width(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return FixedWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia = FixedWidthTokenWithLeadingAndTrailingTrivia; + + function collectTokenTextElements(token, elements) { + token.leadingTrivia().collectTextElements(elements); + elements.push(token.text()); + token.trailingTrivia().collectTextElements(elements); + } + + function fixedWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new FixedWidthTokenWithNoTrivia(kind); + } else { + return new FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo); + } else { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } + Syntax.fixedWidthToken = fixedWidthToken; + + function variableWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, width); + } else { + return new VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, width, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width); + } else { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); + } + } + Syntax.variableWidthToken = variableWidthToken; + + function getTriviaWidth(value) { + return value >>> 2 /* TriviaFullWidthShift */; + } + + function hasTriviaComment(value) { + return (value & 2 /* TriviaCommentMask */) !== 0; + } + + function hasTriviaNewLine(value) { + return (value & 1 /* TriviaNewLineMask */) !== 0; + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function realizeToken(token) { + return new RealizedToken(token.tokenKind, token.leadingTrivia(), token.text(), token.value(), token.valueText(), token.trailingTrivia()); + } + Syntax.realizeToken = realizeToken; + + function convertToIdentifierName(token) { + TypeScript.Debug.assert(TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)); + return new RealizedToken(11 /* IdentifierName */, token.leadingTrivia(), token.text(), token.text(), token.text(), token.trailingTrivia()); + } + Syntax.convertToIdentifierName = convertToIdentifierName; + + function tokenToJSON(token) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === token.kind()) { + result.kind = name; + break; + } + } + + result.width = token.width(); + if (token.fullWidth() !== token.width()) { + result.fullWidth = token.fullWidth(); + } + + result.text = token.text(); + + var value = token.value(); + if (value !== null) { + result.value = value; + result.valueText = token.valueText(); + } + + if (token.hasLeadingTrivia()) { + result.hasLeadingTrivia = true; + } + + if (token.hasLeadingComment()) { + result.hasLeadingComment = true; + } + + if (token.hasLeadingNewLine()) { + result.hasLeadingNewLine = true; + } + + if (token.hasLeadingSkippedText()) { + result.hasLeadingSkippedText = true; + } + + if (token.hasTrailingTrivia()) { + result.hasTrailingTrivia = true; + } + + if (token.hasTrailingComment()) { + result.hasTrailingComment = true; + } + + if (token.hasTrailingNewLine()) { + result.hasTrailingNewLine = true; + } + + if (token.hasTrailingSkippedText()) { + result.hasTrailingSkippedText = true; + } + + var trivia = token.leadingTrivia(); + if (trivia.count() > 0) { + result.leadingTrivia = trivia; + } + + trivia = token.trailingTrivia(); + if (trivia.count() > 0) { + result.trailingTrivia = trivia; + } + + return result; + } + Syntax.tokenToJSON = tokenToJSON; + + function value(token) { + return value1(token.tokenKind, token.text()); + } + Syntax.value = value; + + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + + return intChar; + } + + var characterArray = []; + + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + + default: + } + } + } + + characterArray.push(ch); + + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + + return result; + } + + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + + function value1(kind, text) { + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + + if (kind === 13 /* NumericLiteral */) { + return parseFloat(text); + } else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } else { + return massageEscapes(text.substr(1)); + } + } else if (kind === 12 /* RegularExpressionLiteral */) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } catch (e) { + return null; + } + } else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + + function valueText1(kind, text) { + var value = value1(kind, text); + return value === null ? "" : value.toString(); + } + + function valueText(token) { + var value = token.value(); + return value === null ? "" : value.toString(); + } + Syntax.valueText = valueText; + + var EmptyToken = (function () { + function EmptyToken(kind) { + this.tokenKind = kind; + } + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.tokenKind); + }; + + EmptyToken.prototype.kind = function () { + return this.tokenKind; + }; + + EmptyToken.prototype.isToken = function () { + return true; + }; + EmptyToken.prototype.isNode = function () { + return false; + }; + EmptyToken.prototype.isList = function () { + return false; + }; + EmptyToken.prototype.isSeparatedList = function () { + return false; + }; + + EmptyToken.prototype.childCount = function () { + return 0; + }; + + EmptyToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptyToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + EmptyToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + EmptyToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + EmptyToken.prototype.firstToken = function () { + return this; + }; + EmptyToken.prototype.lastToken = function () { + return this; + }; + EmptyToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.width = function () { + return 0; + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.value = function () { + return null; + }; + EmptyToken.prototype.valueText = function () { + return ""; + }; + + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasLeadingComment = function () { + return false; + }; + EmptyToken.prototype.hasLeadingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasLeadingSkippedText = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasTrailingComment = function () { + return false; + }; + EmptyToken.prototype.hasTrailingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasTrailingSkippedText = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + EmptyToken.prototype.realize = function () { + return realizeToken(this); + }; + EmptyToken.prototype.collectTextElements = function (elements) { + }; + + EmptyToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + EmptyToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + return EmptyToken; + })(); + + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + + var RealizedToken = (function () { + function RealizedToken(tokenKind, leadingTrivia, text, value, valueText, trailingTrivia) { + this.tokenKind = tokenKind; + this._leadingTrivia = leadingTrivia; + this._text = text; + this._value = value; + this._valueText = valueText; + this._trailingTrivia = trailingTrivia; + } + RealizedToken.prototype.clone = function () { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.kind = function () { + return this.tokenKind; + }; + RealizedToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + RealizedToken.prototype.firstToken = function () { + return this; + }; + RealizedToken.prototype.lastToken = function () { + return this; + }; + RealizedToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + RealizedToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + RealizedToken.prototype.childCount = function () { + return 0; + }; + + RealizedToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + RealizedToken.prototype.isToken = function () { + return true; + }; + RealizedToken.prototype.isNode = function () { + return false; + }; + RealizedToken.prototype.isList = function () { + return false; + }; + RealizedToken.prototype.isSeparatedList = function () { + return false; + }; + RealizedToken.prototype.isTrivia = function () { + return false; + }; + RealizedToken.prototype.isTriviaList = function () { + return false; + }; + + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this.width() + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.width = function () { + return this.text().length; + }; + + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + + RealizedToken.prototype.value = function () { + return this._value; + }; + RealizedToken.prototype.valueText = function () { + return this._valueText; + }; + + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasLeadingComment = function () { + return this._leadingTrivia.hasComment(); + }; + RealizedToken.prototype.hasLeadingNewLine = function () { + return this._leadingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasLeadingSkippedText = function () { + return this._leadingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingComment = function () { + return this._trailingTrivia.hasComment(); + }; + RealizedToken.prototype.hasTrailingNewLine = function () { + return this._trailingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasTrailingSkippedText = function () { + return this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasSkippedToken = function () { + return this.hasLeadingSkippedText() || this.hasTrailingSkippedText(); + }; + + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + + RealizedToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + RealizedToken.prototype.collectTextElements = function (elements) { + this.leadingTrivia().collectTextElements(elements); + elements.push(this.text()); + this.trailingTrivia().collectTextElements(elements); + }; + + RealizedToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return new RealizedToken(this.tokenKind, leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, trailingTrivia); + }; + return RealizedToken; + })(); + + function token(kind, info) { + if (typeof info === "undefined") { info = null; } + var text = (info !== null && info.text !== undefined) ? info.text : TypeScript.SyntaxFacts.getText(kind); + + return new RealizedToken(kind, TypeScript.Syntax.triviaList(info === null ? null : info.leadingTrivia), text, value1(kind, text), valueText1(kind, text), TypeScript.Syntax.triviaList(info === null ? null : info.trailingTrivia)); + } + Syntax.token = token; + + function identifier(text, info) { + if (typeof info === "undefined") { info = null; } + info = info || {}; + info.text = text; + return token(11 /* IdentifierName */, info); + } + Syntax.identifier = identifier; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTokenReplacer = (function (_super) { + __extends(SyntaxTokenReplacer, _super); + function SyntaxTokenReplacer(token1, token2) { + _super.call(this); + this.token1 = token1; + this.token2 = token2; + } + SyntaxTokenReplacer.prototype.visitToken = function (token) { + if (token === this.token1) { + var result = this.token2; + this.token1 = null; + this.token2 = null; + + return result; + } + + return token; + }; + + SyntaxTokenReplacer.prototype.visitNode = function (node) { + if (this.token1 === null) { + return node; + } + + return _super.prototype.visitNode.call(this, node); + }; + + SyntaxTokenReplacer.prototype.visitList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitList.call(this, list); + }; + + SyntaxTokenReplacer.prototype.visitSeparatedList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitSeparatedList.call(this, list); + }; + return SyntaxTokenReplacer; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxTokenReplacer = SyntaxTokenReplacer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var SyntaxTrivia = (function () { + function SyntaxTrivia(kind, textOrToken) { + this._kind = kind; + this._textOrToken = textOrToken; + } + SyntaxTrivia.prototype.toJSON = function (key) { + var result = {}; + result.kind = TypeScript.SyntaxKind[this._kind]; + + if (this.isSkippedToken()) { + result.skippedToken = this._textOrToken; + } else { + result.text = this._textOrToken; + } + return result; + }; + + SyntaxTrivia.prototype.kind = function () { + return this._kind; + }; + + SyntaxTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + SyntaxTrivia.prototype.fullText = function () { + return this.isSkippedToken() ? this.skippedToken().fullText() : this._textOrToken; + }; + + SyntaxTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + + SyntaxTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + + SyntaxTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + + SyntaxTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + + SyntaxTrivia.prototype.skippedToken = function () { + TypeScript.Debug.assert(this.isSkippedToken()); + return this._textOrToken; + }; + + SyntaxTrivia.prototype.collectTextElements = function (elements) { + elements.push(this.fullText()); + }; + return SyntaxTrivia; + })(); + + function trivia(kind, text) { + return new SyntaxTrivia(kind, text); + } + Syntax.trivia = trivia; + + function skippedTokenTrivia(token) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SyntaxTrivia(8 /* SkippedTokenTrivia */, token); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + + function spaces(count) { + return trivia(4 /* WhitespaceTrivia */, TypeScript.StringUtilities.repeat(" ", count)); + } + Syntax.spaces = spaces; + + function whitespace(text) { + return trivia(4 /* WhitespaceTrivia */, text); + } + Syntax.whitespace = whitespace; + + function multiLineComment(text) { + return trivia(6 /* MultiLineCommentTrivia */, text); + } + Syntax.multiLineComment = multiLineComment; + + function singleLineComment(text) { + return trivia(7 /* SingleLineCommentTrivia */, text); + } + Syntax.singleLineComment = singleLineComment; + + Syntax.spaceTrivia = spaces(1); + Syntax.lineFeedTrivia = trivia(5 /* NewLineTrivia */, "\n"); + Syntax.carriageReturnTrivia = trivia(5 /* NewLineTrivia */, "\r"); + Syntax.carriageReturnLineFeedTrivia = trivia(5 /* NewLineTrivia */, "\r\n"); + + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + + var triviaText = trivia.fullText(); + var currentIndex = 0; + + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + + currentIndex = i + 1; + continue; + } + } + + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax.emptyTriviaList = { + kind: function () { + return 3 /* TriviaList */; + }, + count: function () { + return 0; + }, + syntaxTriviaAt: function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + last: function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + fullWidth: function () { + return 0; + }, + fullText: function () { + return ""; + }, + hasComment: function () { + return false; + }, + hasNewLine: function () { + return false; + }, + hasSkippedToken: function () { + return false; + }, + toJSON: function (key) { + return []; + }, + collectTextElements: function (elements) { + }, + toArray: function () { + return []; + }, + concat: function (trivia) { + return trivia; + } + }; + + function concatTrivia(list1, list2) { + if (list1.count() === 0) { + return list2; + } + + if (list2.count() === 0) { + return list1; + } + + var trivia = list1.toArray(); + trivia.push.apply(trivia, list2.toArray()); + + return triviaList(trivia); + } + + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.collectTextElements = function (elements) { + (this.item).collectTextElements(elements); + }; + + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return SingletonSyntaxTriviaList; + })(); + + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + this.trivia = trivia; + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.trivia[index]; + }; + + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { + return t.fullWidth(); + }); + }; + + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = ""; + + for (var i = 0, n = this.trivia.length; i < n; i++) { + result += this.trivia[i].fullText(); + } + + return result; + }; + + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.toJSON = function (key) { + return this.trivia; + }; + + NormalSyntaxTriviaList.prototype.collectTextElements = function (elements) { + for (var i = 0; i < this.trivia.length; i++) { + (this.trivia[i]).collectTextElements(elements); + } + }; + + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + + NormalSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return NormalSyntaxTriviaList; + })(); + + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return TypeScript.Syntax.emptyTriviaList; + } + + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + + Syntax.spaceTriviaList = triviaList([TypeScript.Syntax.spaceTrivia]); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement.element(); + var parent = positionedElement.parentElement(); + if (parent !== null && (element.kind() === 81 /* LessThanToken */ || element.kind() === 82 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 227 /* TypeArgumentList */: + case 228 /* TypeParameterList */: + case 219 /* CastExpression */: + return true; + } + } + + return false; + }; + + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var token = list.childAt(i); + if (token.tokenKind === kind) { + return token; + } + } + + return null; + }; + + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 147 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + return SyntaxUtilities.containsToken((moduleElement).modifiers, 47 /* ExportKeyword */); + } + + return false; + }; + + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + + var node = positionNode.node(); + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 147 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken((node).modifiers, 64 /* DeclareKeyword */)) { + return true; + } + + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 138 /* GetMemberAccessorDeclaration */: + case 139 /* SetMemberAccessorDeclaration */: + case 136 /* MemberVariableDeclaration */: + if (node.isClassElement() || node.isModuleElement()) { + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode().containingNode()); + + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxVisitor = (function () { + function SyntaxVisitor() { + } + SyntaxVisitor.prototype.defaultVisit = function (node) { + return null; + }; + + SyntaxVisitor.prototype.visitToken = function (token) { + return this.defaultVisit(token); + }; + + SyntaxVisitor.prototype.visitSourceUnit = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExternalModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleNameModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitImportDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExportAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitClassDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInterfaceDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitHeritageClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclarator = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEqualsValueClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPrefixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitOmittedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitQualifiedName = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGenericType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeAnnotation = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBlock = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPostfixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElementAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInvocationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBinaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConditionalExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMethodSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPropertySignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCallSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstraint = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElseClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIfStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExpressionStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetMemberAccessorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetMemberAccessorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitThrowStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitReturnStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectCreationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSwitchStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCaseSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDefaultSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBreakStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitContinueStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForInStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWhileStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWithStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumElement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCastExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimplePropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetAccessorPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetAccessorPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEmptyStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTryStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCatchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFinallyClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitLabeledStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDoStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeOfExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDeleteExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVoidExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDebuggerStatement = function (node) { + return this.defaultVisit(node); + }; + return SyntaxVisitor; + })(); + TypeScript.SyntaxVisitor = SyntaxVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + + SyntaxWalker.prototype.visitNode = function (node) { + node.accept(this); + }; + + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (nodeOrToken.isToken()) { + this.visitToken(nodeOrToken); + } else { + this.visitNode(nodeOrToken); + } + }; + + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + + this.visitToken(token); + }; + + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + + this.visitNode(node); + }; + + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + + this.visitNodeOrToken(nodeOrToken); + }; + + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.visitNodeOrToken(list.childAt(i)); + } + }; + + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + this.visitNodeOrToken(item); + } + }; + + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.moduleOrRequireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNode(node.moduleReference); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.moduleName); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.body); + }; + + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.body); + }; + + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitOptionalToken(node.publicOrPrivateKeyword); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitNode(node.parameter); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitToken(node.constructorKeyword); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitGetMemberAccessorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetMemberAccessorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitGetAccessorPropertyAssignment = function (node) { + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitToken(node.openParenToken); + this.visitToken(node.closeParenToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetAccessorPropertyAssignment = function (node) { + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitToken(node.openParenToken); + this.visitNode(node.parameter); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitToken(node.semicolonToken); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionTrackingWalker = (function (_super) { + __extends(PositionTrackingWalker, _super); + function PositionTrackingWalker() { + _super.apply(this, arguments); + this._position = 0; + } + PositionTrackingWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + PositionTrackingWalker.prototype.position = function () { + return this._position; + }; + + PositionTrackingWalker.prototype.skip = function (element) { + this._position += element.fullWidth(); + }; + return PositionTrackingWalker; + })(TypeScript.SyntaxWalker); + TypeScript.PositionTrackingWalker = PositionTrackingWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxInformationMap = (function (_super) { + __extends(SyntaxInformationMap, _super); + function SyntaxInformationMap(trackParents, trackPreviousToken) { + _super.call(this); + this.trackParents = trackParents; + this.trackPreviousToken = trackPreviousToken; + this.tokenToInformation = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this.elementToPosition = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._previousToken = null; + this._previousTokenInformation = null; + this._currentPosition = 0; + this._elementToParent = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._parentStack = []; + this._parentStack.push(null); + } + SyntaxInformationMap.create = function (node, trackParents, trackPreviousToken) { + var map = new SyntaxInformationMap(trackParents, trackPreviousToken); + map.visitNode(node); + return map; + }; + + SyntaxInformationMap.prototype.visitNode = function (node) { + this.trackParents && this._elementToParent.add(node, TypeScript.ArrayUtilities.last(this._parentStack)); + this.elementToPosition.add(node, this._currentPosition); + + this.trackParents && this._parentStack.push(node); + _super.prototype.visitNode.call(this, node); + this.trackParents && this._parentStack.pop(); + }; + + SyntaxInformationMap.prototype.visitToken = function (token) { + this.trackParents && this._elementToParent.add(token, TypeScript.ArrayUtilities.last(this._parentStack)); + + if (this.trackPreviousToken) { + var tokenInformation = { + previousToken: this._previousToken, + nextToken: null + }; + + if (this._previousTokenInformation !== null) { + this._previousTokenInformation.nextToken = token; + } + + this._previousToken = token; + this._previousTokenInformation = tokenInformation; + + this.tokenToInformation.add(token, tokenInformation); + } + + this.elementToPosition.add(token, this._currentPosition); + this._currentPosition += token.fullWidth(); + }; + + SyntaxInformationMap.prototype.parent = function (element) { + return this._elementToParent.get(element); + }; + + SyntaxInformationMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxInformationMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxInformationMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxInformationMap.prototype.previousToken = function (token) { + return this.tokenInformation(token).previousToken; + }; + + SyntaxInformationMap.prototype.tokenInformation = function (token) { + return this.tokenToInformation.get(token); + }; + + SyntaxInformationMap.prototype.firstTokenInLineContainingToken = function (token) { + var current = token; + while (true) { + var information = this.tokenInformation(current); + if (this.isFirstTokenInLineWorker(information)) { + break; + } + + current = information.previousToken; + } + + return current; + }; + + SyntaxInformationMap.prototype.isFirstTokenInLine = function (token) { + var information = this.tokenInformation(token); + return this.isFirstTokenInLineWorker(information); + }; + + SyntaxInformationMap.prototype.isFirstTokenInLineWorker = function (information) { + return information.previousToken === null || information.previousToken.hasTrailingNewLine(); + }; + return SyntaxInformationMap; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxInformationMap = SyntaxInformationMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNodeInvariantsChecker = (function (_super) { + __extends(SyntaxNodeInvariantsChecker, _super); + function SyntaxNodeInvariantsChecker() { + _super.apply(this, arguments); + this.tokenTable = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + } + SyntaxNodeInvariantsChecker.checkInvariants = function (node) { + node.accept(new SyntaxNodeInvariantsChecker()); + }; + + SyntaxNodeInvariantsChecker.prototype.visitToken = function (token) { + this.tokenTable.add(token, token); + }; + return SyntaxNodeInvariantsChecker; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxNodeInvariantsChecker = SyntaxNodeInvariantsChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } else { + this.skip(node); + } + }; + return DepthLimitedWalker; + })(TypeScript.PositionTrackingWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + var ExpressionPrecedence; + (function (ExpressionPrecedence) { + ExpressionPrecedence[ExpressionPrecedence["CommaExpressionPrecedence"] = 1] = "CommaExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["AssignmentExpressionPrecedence"] = 2] = "AssignmentExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ConditionalExpressionPrecedence"] = 3] = "ConditionalExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ArrowFunctionPrecedence"] = 4] = "ArrowFunctionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["LogicalOrExpressionPrecedence"] = 5] = "LogicalOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["LogicalAndExpressionPrecedence"] = 6] = "LogicalAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 7] = "BitwiseOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 8] = "BitwiseExclusiveOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 9] = "BitwiseAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["EqualityExpressionPrecedence"] = 10] = "EqualityExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["RelationalExpressionPrecedence"] = 11] = "RelationalExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["ShiftExpressionPrecdence"] = 12] = "ShiftExpressionPrecdence"; + ExpressionPrecedence[ExpressionPrecedence["AdditiveExpressionPrecedence"] = 13] = "AdditiveExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 14] = "MultiplicativeExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["UnaryExpressionPrecedence"] = 15] = "UnaryExpressionPrecedence"; + })(ExpressionPrecedence || (ExpressionPrecedence = {})); + + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 1 << 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1 << 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 1 << 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 1 << 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 1 << 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 1 << 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 1 << 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 1 << 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 1 << 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 1 << 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 1 << 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 1 << 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 1 << 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 1 << 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 1 << 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 1 << 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 1 << 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 1 << 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 1 << 18] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; + + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeArgumentList_Types] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + + var SyntaxCursor = (function () { + function SyntaxCursor(sourceUnit) { + this._elements = []; + this._index = 0; + this._pinCount = 0; + sourceUnit.insertChildrenInto(this._elements, 0); + } + SyntaxCursor.prototype.isFinished = function () { + return this._index === this._elements.length; + }; + + SyntaxCursor.prototype.currentElement = function () { + if (this.isFinished()) { + return null; + } + + return this._elements[this._index]; + }; + + SyntaxCursor.prototype.currentNode = function () { + var element = this.currentElement(); + return element !== null && element.isNode() ? element : null; + }; + + SyntaxCursor.prototype.moveToFirstChild = function () { + if (this.isFinished()) { + return; + } + + var element = this._elements[this._index]; + if (element.isToken()) { + return; + } + + var node = element; + + this._elements.splice(this._index, 1); + + node.insertChildrenInto(this._elements, this._index); + }; + + SyntaxCursor.prototype.moveToNextSibling = function () { + if (this.isFinished()) { + return; + } + + if (this._pinCount > 0) { + this._index++; + return; + } + + this._elements.shift(); + }; + + SyntaxCursor.prototype.getAndPinCursorIndex = function () { + this._pinCount++; + return this._index; + }; + + SyntaxCursor.prototype.releaseAndUnpinCursorIndex = function (index) { + this._pinCount--; + if (this._pinCount === 0) { + } + }; + + SyntaxCursor.prototype.rewindToPinnedCursorIndex = function (index) { + this._index = index; + }; + + SyntaxCursor.prototype.pinCount = function () { + return this._pinCount; + }; + + SyntaxCursor.prototype.moveToFirstToken = function () { + var element; + + while (!this.isFinished()) { + element = this.currentElement(); + if (element.isNode()) { + this.moveToFirstChild(); + continue; + } + + return; + } + }; + + SyntaxCursor.prototype.currentToken = function () { + this.moveToFirstToken(); + if (this.isFinished()) { + return null; + } + + var element = this.currentElement(); + + return element; + }; + + SyntaxCursor.prototype.peekToken = function (n) { + this.moveToFirstToken(); + var pin = this.getAndPinCursorIndex(); + try { + for (var i = 0; i < n; i++) { + this.moveToNextSibling(); + this.moveToFirstToken(); + } + + return this.currentToken(); + } finally { + this.rewindToPinnedCursorIndex(pin); + this.releaseAndUnpinCursorIndex(pin); + } + }; + return SyntaxCursor; + })(); + + var NormalParserSource = (function () { + function NormalParserSource(fileName, text, languageVersion) { + this._previousToken = null; + this._absolutePosition = 0; + this._tokenDiagnostics = []; + this.rewindPointPool = []; + this.rewindPointPoolCount = 0; + this.slidingWindow = new TypeScript.SlidingWindow(this, TypeScript.ArrayUtilities.createArray(32, null), null); + this.scanner = new TypeScript.Scanner(fileName, text, languageVersion); + } + NormalParserSource.prototype.languageVersion = function () { + return this.scanner.languageVersion(); + }; + + NormalParserSource.prototype.currentNode = function () { + return null; + }; + + NormalParserSource.prototype.moveToNextNode = function () { + throw TypeScript.Errors.invalidOperation(); + }; + + NormalParserSource.prototype.absolutePosition = function () { + return this._absolutePosition; + }; + + NormalParserSource.prototype.previousToken = function () { + return this._previousToken; + }; + + NormalParserSource.prototype.tokenDiagnostics = function () { + return this._tokenDiagnostics; + }; + + NormalParserSource.prototype.getOrCreateRewindPoint = function () { + if (this.rewindPointPoolCount === 0) { + return {}; + } + + this.rewindPointPoolCount--; + var result = this.rewindPointPool[this.rewindPointPoolCount]; + this.rewindPointPool[this.rewindPointPoolCount] = null; + return result; + }; + + NormalParserSource.prototype.getRewindPoint = function () { + var slidingWindowIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var rewindPoint = this.getOrCreateRewindPoint(); + + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.previousToken = this._previousToken; + rewindPoint.absolutePosition = this._absolutePosition; + + rewindPoint.pinCount = this.slidingWindow.pinCount(); + + return rewindPoint; + }; + + NormalParserSource.prototype.isPinned = function () { + return this.slidingWindow.pinCount() > 0; + }; + + NormalParserSource.prototype.rewind = function (rewindPoint) { + this.slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + + this._previousToken = rewindPoint.previousToken; + this._absolutePosition = rewindPoint.absolutePosition; + }; + + NormalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this.slidingWindow.releaseAndUnpinAbsoluteIndex((rewindPoint).absoluteIndex); + + this.rewindPointPool[this.rewindPointPoolCount] = rewindPoint; + this.rewindPointPoolCount++; + }; + + NormalParserSource.prototype.fetchMoreItems = function (allowRegularExpression, sourceIndex, window, destinationIndex, spaceAvailable) { + window[destinationIndex] = this.scanner.scan(this._tokenDiagnostics, allowRegularExpression); + return 1; + }; + + NormalParserSource.prototype.peekToken = function (n) { + return this.slidingWindow.peekItemN(n); + }; + + NormalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + this._absolutePosition += currentToken.fullWidth(); + this._previousToken = currentToken; + + this.slidingWindow.moveToNextItem(); + }; + + NormalParserSource.prototype.currentToken = function () { + return this.slidingWindow.currentItem(false); + }; + + NormalParserSource.prototype.removeDiagnosticsOnOrAfterPosition = function (position) { + var tokenDiagnosticsLength = this._tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = this._tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } else { + break; + } + } + + this._tokenDiagnostics.length = tokenDiagnosticsLength; + }; + + NormalParserSource.prototype.resetToPosition = function (absolutePosition, previousToken) { + this._absolutePosition = absolutePosition; + this._previousToken = previousToken; + + this.removeDiagnosticsOnOrAfterPosition(absolutePosition); + + this.slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + + this.scanner.setAbsoluteIndex(absolutePosition); + }; + + NormalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + this.resetToPosition(this._absolutePosition, this._previousToken); + + var token = this.slidingWindow.currentItem(true); + + return token; + }; + return NormalParserSource; + })(); + + var IncrementalParserSource = (function () { + function IncrementalParserSource(oldSyntaxTree, textChangeRange, newText) { + this._changeDelta = 0; + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + this._oldSourceUnitCursor = new SyntaxCursor(oldSourceUnit); + + this._changeRange = IncrementalParserSource.extendToAffectedRange(textChangeRange, oldSourceUnit); + + this._normalParserSource = new NormalParserSource(oldSyntaxTree.fileName(), newText, oldSyntaxTree.languageVersion()); + } + IncrementalParserSource.extendToAffectedRange = function (changeRange, sourceUnit) { + var maxLookahead = 1; + + var start = changeRange.span().start(); + + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = sourceUnit.findToken(start); + + var position = token.fullStart(); + + start = TypeScript.MathPrototype.max(0, position - 1); + } + + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + + return new TypeScript.TextChangeRange(finalSpan, finalLength); + }; + + IncrementalParserSource.prototype.languageVersion = function () { + return this._normalParserSource.languageVersion(); + }; + + IncrementalParserSource.prototype.absolutePosition = function () { + return this._normalParserSource.absolutePosition(); + }; + + IncrementalParserSource.prototype.previousToken = function () { + return this._normalParserSource.previousToken(); + }; + + IncrementalParserSource.prototype.tokenDiagnostics = function () { + return this._normalParserSource.tokenDiagnostics(); + }; + + IncrementalParserSource.prototype.getRewindPoint = function () { + var rewindPoint = this._normalParserSource.getRewindPoint(); + var oldSourceUnitCursorIndex = this._oldSourceUnitCursor.getAndPinCursorIndex(); + + rewindPoint.changeDelta = this._changeDelta; + rewindPoint.changeRange = this._changeRange; + rewindPoint.oldSourceUnitCursorIndex = oldSourceUnitCursorIndex; + + return rewindPoint; + }; + + IncrementalParserSource.prototype.rewind = function (rewindPoint) { + this._changeRange = rewindPoint.changeRange; + this._changeDelta = rewindPoint.changeDelta; + this._oldSourceUnitCursor.rewindToPinnedCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + + this._normalParserSource.rewind(rewindPoint); + }; + + IncrementalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this._oldSourceUnitCursor.releaseAndUnpinCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + this._normalParserSource.releaseRewindPoint(rewindPoint); + }; + + IncrementalParserSource.prototype.canReadFromOldSourceUnit = function () { + if (this._normalParserSource.isPinned()) { + return false; + } + + if (this._changeRange !== null && this._changeRange.newSpan().intersectsWithPosition(this.absolutePosition())) { + return false; + } + + this.syncCursorToNewTextIfBehind(); + + return this._changeDelta === 0 && !this._oldSourceUnitCursor.isFinished(); + }; + + IncrementalParserSource.prototype.currentNode = function () { + if (this.canReadFromOldSourceUnit()) { + return this.tryGetNodeFromOldSourceUnit(); + } + + return null; + }; + + IncrementalParserSource.prototype.currentToken = function () { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryGetTokenFromOldSourceUnit(); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.currentToken(); + }; + + IncrementalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + return this._normalParserSource.currentTokenAllowingRegularExpression(); + }; + + IncrementalParserSource.prototype.syncCursorToNewTextIfBehind = function () { + while (true) { + if (this._oldSourceUnitCursor.isFinished()) { + break; + } + + if (this._changeDelta >= 0) { + break; + } + + var currentElement = this._oldSourceUnitCursor.currentElement(); + + if (currentElement.isNode() && (currentElement.fullWidth() > Math.abs(this._changeDelta))) { + this._oldSourceUnitCursor.moveToFirstChild(); + } else { + this._oldSourceUnitCursor.moveToNextSibling(); + + this._changeDelta += currentElement.fullWidth(); + } + } + }; + + IncrementalParserSource.prototype.intersectsWithChangeRangeSpanInOriginalText = function (start, length) { + return this._changeRange !== null && this._changeRange.span().intersectsWith(start, length); + }; + + IncrementalParserSource.prototype.tryGetNodeFromOldSourceUnit = function () { + while (true) { + var node = this._oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + + if (!this.intersectsWithChangeRangeSpanInOriginalText(this.absolutePosition(), node.fullWidth())) { + if (!node.isIncrementallyUnusable()) { + return node; + } + } + + this._oldSourceUnitCursor.moveToFirstChild(); + } + }; + + IncrementalParserSource.prototype.canReuseTokenFromOldSourceUnit = function (position, token) { + if (token !== null) { + if (!this.intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable()) { + return true; + } + } + } + + return false; + }; + + IncrementalParserSource.prototype.tryGetTokenFromOldSourceUnit = function () { + var token = this._oldSourceUnitCursor.currentToken(); + + return this.canReuseTokenFromOldSourceUnit(this.absolutePosition(), token) ? token : null; + }; + + IncrementalParserSource.prototype.peekToken = function (n) { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.peekToken(n); + }; + + IncrementalParserSource.prototype.tryPeekTokenFromOldSourceUnit = function (n) { + var currentPosition = this.absolutePosition(); + for (var i = 0; i < n; i++) { + var interimToken = this._oldSourceUnitCursor.peekToken(i); + if (!this.canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + + currentPosition += interimToken.fullWidth(); + } + + var token = this._oldSourceUnitCursor.peekToken(n); + return this.canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + }; + + IncrementalParserSource.prototype.moveToNextNode = function () { + var currentElement = this._oldSourceUnitCursor.currentElement(); + var currentNode = this._oldSourceUnitCursor.currentNode(); + + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentNode.fullWidth(); + var previousToken = currentNode.lastToken(); + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + }; + + IncrementalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + + if (this._oldSourceUnitCursor.currentToken() === currentToken) { + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentToken.fullWidth(); + var previousToken = currentToken; + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + } else { + this._changeDelta -= currentToken.fullWidth(); + + this._normalParserSource.moveToNextToken(); + + if (this._changeRange !== null) { + var changeRangeSpanInNewText = this._changeRange.newSpan(); + if (this.absolutePosition() >= changeRangeSpanInNewText.end()) { + this._changeDelta += this._changeRange.newLength() - this._changeRange.span().length(); + this._changeRange = null; + } + } + } + }; + return IncrementalParserSource; + })(); + + var ParserImpl = (function () { + function ParserImpl(fileName, lineMap, source, parseOptions) { + this.listParsingState = 0; + this.isInStrictMode = false; + this.diagnostics = []; + this.factory = TypeScript.Syntax.normalModeFactory; + this.mergeTokensStorage = []; + this.arrayPool = []; + this.fileName = fileName; + this.lineMap = lineMap; + this.source = source; + this.parseOptions = parseOptions; + } + ParserImpl.prototype.getRewindPoint = function () { + var rewindPoint = this.source.getRewindPoint(); + + rewindPoint.diagnosticsCount = this.diagnostics.length; + + rewindPoint.isInStrictMode = this.isInStrictMode; + rewindPoint.listParsingState = this.listParsingState; + + return rewindPoint; + }; + + ParserImpl.prototype.rewind = function (rewindPoint) { + this.source.rewind(rewindPoint); + + this.diagnostics.length = rewindPoint.diagnosticsCount; + }; + + ParserImpl.prototype.releaseRewindPoint = function (rewindPoint) { + this.source.releaseRewindPoint(rewindPoint); + }; + + ParserImpl.prototype.currentTokenStart = function () { + return this.source.absolutePosition() + this.currentToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenStart = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.source.absolutePosition() - this.previousToken().fullWidth() + this.previousToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenEnd = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.previousTokenStart() + this.previousToken().width(); + }; + + ParserImpl.prototype.currentNode = function () { + var node = this.source.currentNode(); + + if (node === null || node.parsedInStrictMode() !== this.isInStrictMode) { + return null; + } + + return node; + }; + + ParserImpl.prototype.currentToken = function () { + return this.source.currentToken(); + }; + + ParserImpl.prototype.currentTokenAllowingRegularExpression = function () { + return this.source.currentTokenAllowingRegularExpression(); + }; + + ParserImpl.prototype.peekToken = function (n) { + return this.source.peekToken(n); + }; + + ParserImpl.prototype.eatAnyToken = function () { + var token = this.currentToken(); + this.moveToNextToken(); + return token; + }; + + ParserImpl.prototype.moveToNextToken = function () { + this.source.moveToNextToken(); + }; + + ParserImpl.prototype.previousToken = function () { + return this.source.previousToken(); + }; + + ParserImpl.prototype.eatNode = function () { + var node = this.source.currentNode(); + this.source.moveToNextNode(); + return node; + }; + + ParserImpl.prototype.eatToken = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.tryEatToken = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatToken(kind); + } + + return null; + }; + + ParserImpl.prototype.tryEatKeyword = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatKeyword(kind); + } + + return null; + }; + + ParserImpl.prototype.eatKeyword = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.isIdentifier = function (token) { + var tokenKind = token.tokenKind; + + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + + if (tokenKind >= 51 /* FirstFutureReservedStrictKeyword */) { + if (tokenKind <= 59 /* LastFutureReservedStrictKeyword */) { + return !this.isInStrictMode; + } + + return tokenKind <= 70 /* LastTypeScriptKeyword */; + } + + return false; + }; + + ParserImpl.prototype.eatIdentifierNameToken = function () { + var token = this.currentToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + this.moveToNextToken(); + return token; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)) { + this.moveToNextToken(); + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.eatIdentifierToken = function () { + var token = this.currentToken(); + if (this.isIdentifier(token)) { + this.moveToNextToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + return token; + } + + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.canEatAutomaticSemicolon = function (allowWithoutNewLine) { + var token = this.currentToken(); + + if (token.tokenKind === 10 /* EndOfFileToken */) { + return true; + } + + if (token.tokenKind === 72 /* CloseBraceToken */) { + return true; + } + + if (allowWithoutNewLine) { + return true; + } + + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.canEatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 79 /* SemicolonToken */) { + return true; + } + + return this.canEatAutomaticSemicolon(allowWithoutNewline); + }; + + ParserImpl.prototype.eatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 79 /* SemicolonToken */) { + return this.eatToken(79 /* SemicolonToken */); + } + + if (this.canEatAutomaticSemicolon(allowWithoutNewline)) { + var semicolonToken = TypeScript.Syntax.emptyToken(79 /* SemicolonToken */); + + if (!this.parseOptions.allowAutomaticSemicolonInsertion()) { + this.addDiagnostic(new TypeScript.SyntaxDiagnostic(this.fileName, this.previousTokenEnd(), 0, 11 /* Automatic_semicolon_insertion_not_allowed */, null)); + } + + return semicolonToken; + } + + return this.eatToken(79 /* SemicolonToken */); + }; + + ParserImpl.prototype.isKeyword = function (kind) { + if (kind >= TypeScript.SyntaxKind.FirstKeyword) { + if (kind <= 50 /* LastFutureReservedKeyword */) { + return true; + } + + if (this.isInStrictMode) { + return kind <= 59 /* LastFutureReservedStrictKeyword */; + } + } + + return false; + }; + + ParserImpl.prototype.createMissingToken = function (expectedKind, actual) { + var diagnostic = this.getExpectedTokenDiagnostic(expectedKind, actual); + this.addDiagnostic(diagnostic); + + return TypeScript.Syntax.emptyToken(expectedKind); + }; + + ParserImpl.prototype.getExpectedTokenDiagnostic = function (expectedKind, actual) { + var token = this.currentToken(); + + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + return new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 9 /* _0_expected */, [TypeScript.SyntaxFacts.getText(expectedKind)]); + } else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.tokenKind)) { + return new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 10 /* Identifier_expected__0__is_a_keyword */, [TypeScript.SyntaxFacts.getText(actual.tokenKind)]); + } else { + return new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 7 /* Identifier_expected */, null); + } + } + }; + + ParserImpl.getPrecedence = function (expressionKind) { + switch (expressionKind) { + case 172 /* CommaExpression */: + return 1 /* CommaExpressionPrecedence */; + + case 173 /* AssignmentExpression */: + case 174 /* AddAssignmentExpression */: + case 175 /* SubtractAssignmentExpression */: + case 176 /* MultiplyAssignmentExpression */: + case 177 /* DivideAssignmentExpression */: + case 178 /* ModuloAssignmentExpression */: + case 179 /* AndAssignmentExpression */: + case 180 /* ExclusiveOrAssignmentExpression */: + case 181 /* OrAssignmentExpression */: + case 182 /* LeftShiftAssignmentExpression */: + case 183 /* SignedRightShiftAssignmentExpression */: + case 184 /* UnsignedRightShiftAssignmentExpression */: + return 2 /* AssignmentExpressionPrecedence */; + + case 185 /* ConditionalExpression */: + return 3 /* ConditionalExpressionPrecedence */; + + case 186 /* LogicalOrExpression */: + return 5 /* LogicalOrExpressionPrecedence */; + + case 187 /* LogicalAndExpression */: + return 6 /* LogicalAndExpressionPrecedence */; + + case 188 /* BitwiseOrExpression */: + return 7 /* BitwiseOrExpressionPrecedence */; + + case 189 /* BitwiseExclusiveOrExpression */: + return 8 /* BitwiseExclusiveOrExpressionPrecedence */; + + case 190 /* BitwiseAndExpression */: + return 9 /* BitwiseAndExpressionPrecedence */; + + case 191 /* EqualsWithTypeConversionExpression */: + case 192 /* NotEqualsWithTypeConversionExpression */: + case 193 /* EqualsExpression */: + case 194 /* NotEqualsExpression */: + return 10 /* EqualityExpressionPrecedence */; + + case 195 /* LessThanExpression */: + case 196 /* GreaterThanExpression */: + case 197 /* LessThanOrEqualExpression */: + case 198 /* GreaterThanOrEqualExpression */: + case 199 /* InstanceOfExpression */: + case 200 /* InExpression */: + return 11 /* RelationalExpressionPrecedence */; + + case 201 /* LeftShiftExpression */: + case 202 /* SignedRightShiftExpression */: + case 203 /* UnsignedRightShiftExpression */: + return 12 /* ShiftExpressionPrecdence */; + + case 207 /* AddExpression */: + case 208 /* SubtractExpression */: + return 13 /* AdditiveExpressionPrecedence */; + + case 204 /* MultiplyExpression */: + case 205 /* DivideExpression */: + case 206 /* ModuloExpression */: + return 14 /* MultiplicativeExpressionPrecedence */; + + case 163 /* PlusExpression */: + case 164 /* NegateExpression */: + case 165 /* BitwiseNotExpression */: + case 166 /* LogicalNotExpression */: + case 169 /* DeleteExpression */: + case 170 /* TypeOfExpression */: + case 171 /* VoidExpression */: + case 167 /* PreIncrementExpression */: + case 168 /* PreDecrementExpression */: + return 15 /* UnaryExpressionPrecedence */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ParserImpl.prototype.addSkippedTokenAfterNodeOrToken = function (nodeOrToken, skippedToken) { + if (nodeOrToken.isToken()) { + return this.addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } else if (nodeOrToken.isNode()) { + return this.addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.addSkippedTokenAfterNode = function (node, skippedToken) { + var oldToken = node.lastToken(); + var newToken = this.addSkippedTokenAfterToken(oldToken, skippedToken); + + return node.replaceToken(oldToken, newToken); + }; + + ParserImpl.prototype.addSkippedTokensBeforeNode = function (node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = node.firstToken(); + var newToken = this.addSkippedTokensBeforeToken(oldToken, skippedTokens); + + return node.replaceToken(oldToken, newToken); + } + + return node; + }; + + ParserImpl.prototype.addSkippedTokensBeforeToken = function (token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(leadingTrivia, skippedTokens[i]); + } + + this.addTriviaTo(token.leadingTrivia(), leadingTrivia); + + this.returnArray(skippedTokens); + return token.withLeadingTrivia(TypeScript.Syntax.triviaList(leadingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokensAfterToken = function (token, skippedTokens) { + if (skippedTokens.length === 0) { + this.returnArray(skippedTokens); + return token; + } + + var trailingTrivia = token.trailingTrivia().toArray(); + + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + + this.returnArray(skippedTokens); + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenAfterToken = function (token, skippedToken) { + var trailingTrivia = token.trailingTrivia().toArray(); + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenToTriviaArray = function (array, skippedToken) { + this.addTriviaTo(skippedToken.leadingTrivia(), array); + + var trimmedToken = skippedToken.withLeadingTrivia(TypeScript.Syntax.emptyTriviaList).withTrailingTrivia(TypeScript.Syntax.emptyTriviaList); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken)); + + this.addTriviaTo(skippedToken.trailingTrivia(), array); + }; + + ParserImpl.prototype.addTriviaTo = function (list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + }; + + ParserImpl.prototype.parseSyntaxTree = function (isDeclaration) { + var sourceUnit = this.parseSourceUnit(); + + var allDiagnostics = this.source.tokenDiagnostics().concat(this.diagnostics); + allDiagnostics.sort(function (a, b) { + return a.start() - b.start(); + }); + + return new TypeScript.SyntaxTree(sourceUnit, isDeclaration, allDiagnostics, this.fileName, this.lineMap, this.source.languageVersion(), this.parseOptions); + }; + + ParserImpl.prototype.setStrictMode = function (isInStrictMode) { + this.isInStrictMode = isInStrictMode; + this.factory = isInStrictMode ? TypeScript.Syntax.strictModeFactory : TypeScript.Syntax.normalModeFactory; + }; + + ParserImpl.prototype.parseSourceUnit = function () { + var savedIsInStrictMode = this.isInStrictMode; + + var result = this.parseSyntaxList(1 /* SourceUnit_ModuleElements */, ParserImpl.updateStrictModeState); + var moduleElements = result.list; + + this.setStrictMode(savedIsInStrictMode); + + var sourceUnit = this.factory.sourceUnit(moduleElements, this.currentToken()); + sourceUnit = this.addSkippedTokensBeforeNode(sourceUnit, result.skippedTokens); + + return sourceUnit; + }; + + ParserImpl.updateStrictModeState = function (parser, items) { + if (!parser.isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + + parser.setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + }; + + ParserImpl.prototype.isModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return true; + } + + return this.isImportDeclaration() || this.isExportAssignment() || this.isModuleDeclaration() || this.isInterfaceDeclaration() || this.isClassDeclaration() || this.isEnumDeclaration() || this.isStatement(inErrorRecovery); + }; + + ParserImpl.prototype.parseModuleElement = function () { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return this.eatNode(); + } + + if (this.isImportDeclaration()) { + return this.parseImportDeclaration(); + } else if (this.isExportAssignment()) { + return this.parseExportAssignment(); + } else if (this.isModuleDeclaration()) { + return this.parseModuleDeclaration(); + } else if (this.isInterfaceDeclaration()) { + return this.parseInterfaceDeclaration(); + } else if (this.isClassDeclaration()) { + return this.parseClassDeclaration(); + } else if (this.isEnumDeclaration()) { + return this.parseEnumDeclaration(); + } else if (this.isStatement(false)) { + return this.parseStatement(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isImportDeclaration = function () { + return this.currentToken().tokenKind === 49 /* ImportKeyword */; + }; + + ParserImpl.prototype.parseImportDeclaration = function () { + var importKeyword = this.eatKeyword(49 /* ImportKeyword */); + var identifier = this.eatIdentifierToken(); + var equalsToken = this.eatToken(108 /* EqualsToken */); + var moduleReference = this.parseModuleReference(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.importDeclaration(importKeyword, identifier, equalsToken, moduleReference, semicolonToken); + }; + + ParserImpl.prototype.isExportAssignment = function () { + return this.currentToken().tokenKind === 47 /* ExportKeyword */ && this.peekToken(1).tokenKind === 108 /* EqualsToken */; + }; + + ParserImpl.prototype.parseExportAssignment = function () { + var exportKeyword = this.eatKeyword(47 /* ExportKeyword */); + var equalsToken = this.eatToken(108 /* EqualsToken */); + var identifier = this.eatIdentifierToken(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.exportAssignment(exportKeyword, equalsToken, identifier, semicolonToken); + }; + + ParserImpl.prototype.parseModuleReference = function () { + if (this.isExternalModuleReference()) { + return this.parseExternalModuleReference(); + } else { + return this.parseModuleNameModuleReference(); + } + }; + + ParserImpl.prototype.isExternalModuleReference = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 66 /* ModuleKeyword */ || token0.tokenKind === 67 /* RequireKeyword */) { + return this.peekToken(1).tokenKind === 73 /* OpenParenToken */; + } + + return false; + }; + + ParserImpl.prototype.parseExternalModuleReference = function () { + var moduleOrRequireKeyword = this.eatAnyToken(); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var stringLiteral = this.eatToken(14 /* StringLiteral */); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + return this.factory.externalModuleReference(moduleOrRequireKeyword, openParenToken, stringLiteral, closeParenToken); + }; + + ParserImpl.prototype.parseModuleNameModuleReference = function () { + var name = this.parseName(); + return this.factory.moduleNameModuleReference(name); + }; + + ParserImpl.prototype.parseIdentifierName = function () { + var identifierName = this.eatIdentifierNameToken(); + return identifierName; + }; + + ParserImpl.prototype.isName = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.tryParseTypeArgumentList = function (inExpression) { + if (this.currentToken().kind() !== 81 /* LessThanToken */) { + return null; + } + + var lessThanToken; + var greaterThanToken; + var result; + var typeArguments; + + if (!inExpression) { + lessThanToken = this.eatToken(81 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } + + var rewindPoint = this.getRewindPoint(); + try { + lessThanToken = this.eatToken(81 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + + if (greaterThanToken.fullWidth() === 0 || !this.canFollowTypeArgumentListInExpression(this.currentToken().kind())) { + this.rewind(rewindPoint); + return null; + } + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.canFollowTypeArgumentListInExpression = function (kind) { + switch (kind) { + case 73 /* OpenParenToken */: + case 77 /* DotToken */: + + case 74 /* CloseParenToken */: + case 76 /* CloseBracketToken */: + case 107 /* ColonToken */: + case 79 /* SemicolonToken */: + case 80 /* CommaToken */: + case 106 /* QuestionToken */: + case 85 /* EqualsEqualsToken */: + case 88 /* EqualsEqualsEqualsToken */: + case 87 /* ExclamationEqualsToken */: + case 89 /* ExclamationEqualsEqualsToken */: + case 104 /* AmpersandAmpersandToken */: + case 105 /* BarBarToken */: + case 101 /* CaretToken */: + case 99 /* AmpersandToken */: + case 100 /* BarToken */: + case 72 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseName = function () { + var shouldContinue = this.isIdentifier(this.currentToken()); + var current = this.eatIdentifierToken(); + + while (shouldContinue && this.currentToken().tokenKind === 77 /* DotToken */) { + var dotToken = this.eatToken(77 /* DotToken */); + + var currentToken = this.currentToken(); + var identifierName; + + if (TypeScript.SyntaxFacts.isAnyKeyword(currentToken.tokenKind) && this.previousToken().hasTrailingNewLine() && !currentToken.hasTrailingNewLine() && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.peekToken(1))) { + identifierName = this.createMissingToken(11 /* IdentifierName */, currentToken); + } else { + identifierName = this.eatIdentifierNameToken(); + } + + current = this.factory.qualifiedName(current, dotToken, identifierName); + + shouldContinue = identifierName.fullWidth() > 0; + } + + return current; + }; + + ParserImpl.prototype.isEnumDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 46 /* EnumKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 46 /* EnumKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseEnumDeclaration = function () { + var modifiers = this.parseModifiers(); + var enumKeyword = this.eatKeyword(46 /* EnumKeyword */); + var identifier = this.eatIdentifierToken(); + + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList; + + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(256 /* EnumDeclaration_EnumElements */); + enumElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.enumDeclaration(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken); + }; + + ParserImpl.prototype.isEnumElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return true; + } + + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseEnumElement = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return this.eatNode(); + } + + var propertyName = this.eatPropertyName(); + var equalsValueClause = null; + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.enumElement(propertyName, equalsValueClause); + }; + + ParserImpl.isModifier = function (token) { + switch (token.tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 47 /* ExportKeyword */: + case 64 /* DeclareKeyword */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.modifierCount = function () { + var modifierCount = 0; + while (true) { + if (ParserImpl.isModifier(this.peekToken(modifierCount))) { + modifierCount++; + continue; + } + + break; + } + + return modifierCount; + }; + + ParserImpl.prototype.parseModifiers = function () { + var tokens = this.getArray(); + + while (true) { + if (ParserImpl.isModifier(this.currentToken())) { + tokens.push(this.eatAnyToken()); + continue; + } + + break; + } + + var result = TypeScript.Syntax.list(tokens); + + this.returnZeroOrOneLengthArray(tokens); + + return result; + }; + + ParserImpl.prototype.isClassDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 44 /* ClassKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 44 /* ClassKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseHeritageClauses = function () { + var heritageClauses = TypeScript.Syntax.emptyList; + + if (this.isHeritageClause()) { + var result = this.parseSyntaxList(1024 /* ClassOrInterfaceDeclaration_HeritageClauses */); + heritageClauses = result.list; + TypeScript.Debug.assert(result.skippedTokens.length === 0); + } + + return heritageClauses; + }; + + ParserImpl.prototype.parseClassDeclaration = function () { + var modifiers = this.parseModifiers(); + + var classKeyword = this.eatKeyword(44 /* ClassKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList; + + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(2 /* ClassDeclaration_ClassElements */); + + classElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + return this.factory.classDeclaration(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken); + }; + + ParserImpl.prototype.isConstructorDeclaration = function () { + return this.currentToken().tokenKind === 63 /* ConstructorKeyword */; + }; + + ParserImpl.isPublicOrPrivateKeyword = function (token) { + return token.tokenKind === 57 /* PublicKeyword */ || token.tokenKind === 55 /* PrivateKeyword */; + }; + + ParserImpl.prototype.isMemberAccessorDeclaration = function (inErrorRecovery) { + var index = this.modifierCount(); + + if (this.peekToken(index).tokenKind !== 65 /* GetKeyword */ && this.peekToken(index).tokenKind !== 69 /* SetKeyword */) { + return false; + } + + index++; + return this.isPropertyName(this.peekToken(index), inErrorRecovery); + }; + + ParserImpl.prototype.parseMemberAccessorDeclaration = function () { + var modifiers = this.parseModifiers(); + + if (this.currentToken().tokenKind === 65 /* GetKeyword */) { + return this.parseGetMemberAccessorDeclaration(modifiers); + } else if (this.currentToken().tokenKind === 69 /* SetKeyword */) { + return this.parseSetMemberAccessorDeclaration(modifiers); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseGetMemberAccessorDeclaration = function (modifiers) { + var getKeyword = this.eatKeyword(65 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, false); + + return this.factory.getMemberAccessorDeclaration(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block); + }; + + ParserImpl.prototype.parseSetMemberAccessorDeclaration = function (modifiers) { + var setKeyword = this.eatKeyword(69 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var block = this.parseBlock(false, false); + + return this.factory.setMemberAccessorDeclaration(modifiers, setKeyword, propertyName, parameterList, block); + }; + + ParserImpl.prototype.isClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return true; + } + + return this.isConstructorDeclaration() || this.isMemberFunctionDeclaration(inErrorRecovery) || this.isMemberAccessorDeclaration(inErrorRecovery) || this.isMemberVariableDeclaration(inErrorRecovery) || this.isIndexSignature(); + }; + + ParserImpl.prototype.parseConstructorDeclaration = function () { + var constructorKeyword = this.eatKeyword(63 /* ConstructorKeyword */); + var parameterList = this.parseParameterList(); + + var semicolonToken = null; + var block = null; + + if (this.isBlock()) { + block = this.parseBlock(false, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.constructorDeclaration(constructorKeyword, parameterList, block, semicolonToken); + }; + + ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isCallSignature(index + 1)) { + return true; + } + + if (ParserImpl.isModifier(token)) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberFunctionDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isCallSignature(1)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + var parseBlockEvenWithNoOpenBrace = callSignature !== newCallSignature; + callSignature = newCallSignature; + + var block = null; + var semicolon = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolon = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.memberFunctionDeclaration(modifiers, propertyName, callSignature, block, semicolon); + }; + + ParserImpl.prototype.isDefinitelyMemberVariablePropertyName = function (index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(this.peekToken(index).tokenKind)) { + switch (this.peekToken(index + 1).tokenKind) { + case 79 /* SemicolonToken */: + case 108 /* EqualsToken */: + case 107 /* ColonToken */: + case 72 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } else { + return true; + } + }; + + ParserImpl.prototype.isMemberVariableDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isDefinitelyMemberVariablePropertyName(index)) { + return true; + } + + if (ParserImpl.isModifier(this.peekToken(index))) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberVariableDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isDefinitelyMemberVariablePropertyName(0)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var variableDeclarator = this.parseVariableDeclarator(true, true); + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.memberVariableDeclaration(modifiers, variableDeclarator, semicolon); + }; + + ParserImpl.prototype.parseClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return this.eatNode(); + } + + if (this.isConstructorDeclaration()) { + return this.parseConstructorDeclaration(); + } else if (this.isMemberFunctionDeclaration(inErrorRecovery)) { + return this.parseMemberFunctionDeclaration(); + } else if (this.isMemberAccessorDeclaration(inErrorRecovery)) { + return this.parseMemberAccessorDeclaration(); + } else if (this.isMemberVariableDeclaration(inErrorRecovery)) { + return this.parseMemberVariableDeclaration(); + } else if (this.isIndexSignature()) { + return this.parseIndexSignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.tryAddUnexpectedEqualsGreaterThanToken = function (callSignature) { + var token0 = this.currentToken(); + + var hasEqualsGreaterThanToken = token0.tokenKind === 86 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token0.width(), 16 /* Unexpected_token_ */, []); + this.addDiagnostic(diagnostic); + + var token = this.eatAnyToken(); + return this.addSkippedTokenAfterNode(callSignature, token0); + } + + return callSignature; + }; + + ParserImpl.prototype.isFunctionDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 27 /* FunctionKeyword */; + }; + + ParserImpl.prototype.parseFunctionDeclaration = function () { + var modifiers = this.parseModifiers(); + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = this.eatIdentifierToken(); + var callSignature = this.parseCallSignature(false); + + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + var parseBlockEvenWithNoOpenBrace = callSignature !== newCallSignature; + callSignature = newCallSignature; + + var semicolonToken = null; + var block = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.functionDeclaration(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isModuleDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 66 /* ModuleKeyword */) { + return true; + } + + if (this.currentToken().tokenKind === 66 /* ModuleKeyword */) { + var token1 = this.peekToken(1); + return this.isIdentifier(token1) || token1.tokenKind === 14 /* StringLiteral */; + } + + return false; + }; + + ParserImpl.prototype.parseModuleDeclaration = function () { + var modifiers = this.parseModifiers(); + var moduleKeyword = this.eatKeyword(66 /* ModuleKeyword */); + + var moduleName = null; + var stringLiteral = null; + + if (this.currentToken().tokenKind === 14 /* StringLiteral */) { + stringLiteral = this.eatToken(14 /* StringLiteral */); + } else { + moduleName = this.parseName(); + } + + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var moduleElements = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(4 /* ModuleDeclaration_ModuleElements */); + moduleElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.moduleDeclaration(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken); + }; + + ParserImpl.prototype.isInterfaceDeclaration = function () { + var index = this.modifierCount(); + + if (index > 0 && this.peekToken(index).tokenKind === 52 /* InterfaceKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 52 /* InterfaceKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseInterfaceDeclaration = function () { + var modifiers = this.parseModifiers(); + var interfaceKeyword = this.eatKeyword(52 /* InterfaceKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + + var objectType = this.parseObjectType(); + return this.factory.interfaceDeclaration(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, objectType); + }; + + ParserImpl.prototype.parseObjectType = function () { + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var typeMembers = TypeScript.Syntax.emptySeparatedList; + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(512 /* ObjectType_TypeMembers */); + typeMembers = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + return this.factory.objectType(openBraceToken, typeMembers, closeBraceToken); + }; + + ParserImpl.prototype.isTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return true; + } + + return this.isCallSignature(0) || this.isConstructSignature() || this.isIndexSignature() || this.isMethodSignature(inErrorRecovery) || this.isPropertySignature(inErrorRecovery); + }; + + ParserImpl.prototype.parseTypeMember = function () { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return this.eatNode(); + } + + if (this.isCallSignature(0)) { + return this.parseCallSignature(false); + } else if (this.isConstructSignature()) { + return this.parseConstructSignature(); + } else if (this.isIndexSignature()) { + return this.parseIndexSignature(); + } else if (this.isMethodSignature(false)) { + return this.parseMethodSignature(); + } else if (this.isPropertySignature(false)) { + return this.parsePropertySignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseConstructSignature = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var callSignature = this.parseCallSignature(false); + + return this.factory.constructSignature(newKeyword, callSignature); + }; + + ParserImpl.prototype.parseIndexSignature = function () { + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + var parameter = this.parseParameter(); + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.indexSignature(openBracketToken, parameter, closeBracketToken, typeAnnotation); + }; + + ParserImpl.prototype.parseMethodSignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(106 /* QuestionToken */); + var callSignature = this.parseCallSignature(false); + + return this.factory.methodSignature(propertyName, questionToken, callSignature); + }; + + ParserImpl.prototype.parsePropertySignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(106 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.propertySignature(propertyName, questionToken, typeAnnotation); + }; + + ParserImpl.prototype.isCallSignature = function (tokenIndex) { + var tokenKind = this.peekToken(tokenIndex).tokenKind; + return tokenKind === 73 /* OpenParenToken */ || tokenKind === 81 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructSignature = function () { + if (this.currentToken().tokenKind !== 31 /* NewKeyword */) { + return false; + } + + var token1 = this.peekToken(1); + return token1.tokenKind === 81 /* LessThanToken */ || token1.tokenKind === 73 /* OpenParenToken */; + }; + + ParserImpl.prototype.isIndexSignature = function () { + return this.currentToken().tokenKind === 75 /* OpenBracketToken */; + }; + + ParserImpl.prototype.isMethodSignature = function (inErrorRecovery) { + if (this.isPropertyName(this.currentToken(), inErrorRecovery)) { + if (this.isCallSignature(1)) { + return true; + } + + if (this.peekToken(1).tokenKind === 106 /* QuestionToken */ && this.isCallSignature(2)) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPropertySignature = function (inErrorRecovery) { + var currentToken = this.currentToken(); + + if (ParserImpl.isModifier(currentToken) && !currentToken.hasTrailingNewLine() && this.isPropertyName(this.peekToken(1), inErrorRecovery)) { + return false; + } + + return this.isPropertyName(currentToken, inErrorRecovery); + }; + + ParserImpl.prototype.isHeritageClause = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */; + }; + + ParserImpl.prototype.isNotHeritageClauseTypeName = function () { + if (this.currentToken().tokenKind === 51 /* ImplementsKeyword */ || this.currentToken().tokenKind === 48 /* ExtendsKeyword */) { + return this.isIdentifier(this.peekToken(1)); + } + + return false; + }; + + ParserImpl.prototype.isHeritageClauseTypeName = function () { + if (this.isName()) { + return !this.isNotHeritageClauseTypeName(); + } + + return false; + }; + + ParserImpl.prototype.parseHeritageClause = function () { + var extendsOrImplementsKeyword = this.eatAnyToken(); + TypeScript.Debug.assert(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ || extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + + var result = this.parseSeparatedSyntaxList(2048 /* HeritageClause_TypeNameList */); + var typeNames = result.list; + extendsOrImplementsKeyword = this.addSkippedTokensAfterToken(extendsOrImplementsKeyword, result.skippedTokens); + + return this.factory.heritageClause(extendsOrImplementsKeyword, typeNames); + }; + + ParserImpl.prototype.isStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return true; + } + + switch (this.currentToken().tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = this.peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + } + + return this.isVariableStatement() || this.isLabeledStatement() || this.isFunctionDeclaration() || this.isIfStatement() || this.isBlock() || this.isExpressionStatement() || this.isReturnStatement() || this.isSwitchStatement() || this.isThrowStatement() || this.isBreakStatement() || this.isContinueStatement() || this.isForOrForInStatement() || this.isEmptyStatement(inErrorRecovery) || this.isWhileStatement() || this.isWithStatement() || this.isDoStatement() || this.isTryStatement() || this.isDebuggerStatement(); + }; + + ParserImpl.prototype.parseStatement = function () { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return this.eatNode(); + } + + if (this.isVariableStatement()) { + return this.parseVariableStatement(); + } else if (this.isLabeledStatement()) { + return this.parseLabeledStatement(); + } else if (this.isFunctionDeclaration()) { + return this.parseFunctionDeclaration(); + } else if (this.isIfStatement()) { + return this.parseIfStatement(); + } else if (this.isBlock()) { + return this.parseBlock(false, false); + } else if (this.isReturnStatement()) { + return this.parseReturnStatement(); + } else if (this.isSwitchStatement()) { + return this.parseSwitchStatement(); + } else if (this.isThrowStatement()) { + return this.parseThrowStatement(); + } else if (this.isBreakStatement()) { + return this.parseBreakStatement(); + } else if (this.isContinueStatement()) { + return this.parseContinueStatement(); + } else if (this.isForOrForInStatement()) { + return this.parseForOrForInStatement(); + } else if (this.isEmptyStatement(false)) { + return this.parseEmptyStatement(); + } else if (this.isWhileStatement()) { + return this.parseWhileStatement(); + } else if (this.isWithStatement()) { + return this.parseWithStatement(); + } else if (this.isDoStatement()) { + return this.parseDoStatement(); + } else if (this.isTryStatement()) { + return this.parseTryStatement(); + } else if (this.isDebuggerStatement()) { + return this.parseDebuggerStatement(); + } else { + return this.parseExpressionStatement(); + } + }; + + ParserImpl.prototype.isDebuggerStatement = function () { + return this.currentToken().tokenKind === 19 /* DebuggerKeyword */; + }; + + ParserImpl.prototype.parseDebuggerStatement = function () { + var debuggerKeyword = this.eatKeyword(19 /* DebuggerKeyword */); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.debuggerStatement(debuggerKeyword, semicolonToken); + }; + + ParserImpl.prototype.isDoStatement = function () { + return this.currentToken().tokenKind === 22 /* DoKeyword */; + }; + + ParserImpl.prototype.parseDoStatement = function () { + var doKeyword = this.eatKeyword(22 /* DoKeyword */); + var statement = this.parseStatement(); + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(true); + + return this.factory.doStatement(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + }; + + ParserImpl.prototype.isLabeledStatement = function () { + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 107 /* ColonToken */; + }; + + ParserImpl.prototype.parseLabeledStatement = function () { + var identifier = this.eatIdentifierToken(); + var colonToken = this.eatToken(107 /* ColonToken */); + var statement = this.parseStatement(); + + return this.factory.labeledStatement(identifier, colonToken, statement); + }; + + ParserImpl.prototype.isTryStatement = function () { + return this.currentToken().tokenKind === 38 /* TryKeyword */; + }; + + ParserImpl.prototype.parseTryStatement = function () { + var tryKeyword = this.eatKeyword(38 /* TryKeyword */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 64 /* TryBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + var catchClause = null; + if (this.isCatchClause()) { + catchClause = this.parseCatchClause(); + } + + var finallyClause = null; + if (catchClause === null || this.isFinallyClause()) { + finallyClause = this.parseFinallyClause(); + } + + return this.factory.tryStatement(tryKeyword, block, catchClause, finallyClause); + }; + + ParserImpl.prototype.isCatchClause = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */; + }; + + ParserImpl.prototype.parseCatchClause = function () { + var catchKeyword = this.eatKeyword(17 /* CatchKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var identifier = this.eatIdentifierToken(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 128 /* CatchBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + return this.factory.catchClause(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block); + }; + + ParserImpl.prototype.isFinallyClause = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.parseFinallyClause = function () { + var finallyKeyword = this.eatKeyword(25 /* FinallyKeyword */); + var block = this.parseBlock(false, false); + + return this.factory.finallyClause(finallyKeyword, block); + }; + + ParserImpl.prototype.isWithStatement = function () { + return this.currentToken().tokenKind === 43 /* WithKeyword */; + }; + + ParserImpl.prototype.parseWithStatement = function () { + var withKeyword = this.eatKeyword(43 /* WithKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.withStatement(withKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isWhileStatement = function () { + return this.currentToken().tokenKind === 42 /* WhileKeyword */; + }; + + ParserImpl.prototype.parseWhileStatement = function () { + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.whileStatement(whileKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isEmptyStatement = function (inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + + return this.currentToken().tokenKind === 79 /* SemicolonToken */; + }; + + ParserImpl.prototype.parseEmptyStatement = function () { + var semicolonToken = this.eatToken(79 /* SemicolonToken */); + return this.factory.emptyStatement(semicolonToken); + }; + + ParserImpl.prototype.isForOrForInStatement = function () { + return this.currentToken().tokenKind === 26 /* ForKeyword */; + }; + + ParserImpl.prototype.parseForOrForInStatement = function () { + var forKeyword = this.eatKeyword(26 /* ForKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 40 /* VarKeyword */) { + return this.parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } else if (currentToken.tokenKind === 79 /* SemicolonToken */) { + return this.parseForStatement(forKeyword, openParenToken); + } else { + return this.parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + }; + + ParserImpl.prototype.parseForOrForInStatementWithVariableDeclaration = function (forKeyword, openParenToken) { + var variableDeclaration = this.parseVariableDeclaration(false); + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + }; + + ParserImpl.prototype.parseForInStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var inKeyword = this.eatKeyword(29 /* InKeyword */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.forInStatement(forKeyword, openParenToken, variableDeclaration, initializer, inKeyword, expression, closeParenToken, statement); + }; + + ParserImpl.prototype.parseForOrForInStatementWithInitializer = function (forKeyword, openParenToken) { + var initializer = this.parseExpression(false); + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } else { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + }; + + ParserImpl.prototype.parseForStatement = function (forKeyword, openParenToken) { + var initializer = null; + + if (this.currentToken().tokenKind !== 79 /* SemicolonToken */ && this.currentToken().tokenKind !== 74 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + initializer = this.parseExpression(false); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + }; + + ParserImpl.prototype.parseForStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var firstSemicolonToken = this.eatToken(79 /* SemicolonToken */); + + var condition = null; + if (this.currentToken().tokenKind !== 79 /* SemicolonToken */ && this.currentToken().tokenKind !== 74 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + condition = this.parseExpression(true); + } + + var secondSemicolonToken = this.eatToken(79 /* SemicolonToken */); + + var incrementor = null; + if (this.currentToken().tokenKind !== 74 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + incrementor = this.parseExpression(true); + } + + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + return this.factory.forStatement(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement); + }; + + ParserImpl.prototype.isBreakStatement = function () { + return this.currentToken().tokenKind === 15 /* BreakKeyword */; + }; + + ParserImpl.prototype.parseBreakStatement = function () { + var breakKeyword = this.eatKeyword(15 /* BreakKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.breakStatement(breakKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.isContinueStatement = function () { + return this.currentToken().tokenKind === 18 /* ContinueKeyword */; + }; + + ParserImpl.prototype.parseContinueStatement = function () { + var continueKeyword = this.eatKeyword(18 /* ContinueKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.continueStatement(continueKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.isSwitchStatement = function () { + return this.currentToken().tokenKind === 34 /* SwitchKeyword */; + }; + + ParserImpl.prototype.parseSwitchStatement = function () { + var switchKeyword = this.eatKeyword(34 /* SwitchKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var switchClauses = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(8 /* SwitchStatement_SwitchClauses */); + switchClauses = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + return this.factory.switchStatement(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken); + }; + + ParserImpl.prototype.isCaseSwitchClause = function () { + return this.currentToken().tokenKind === 16 /* CaseKeyword */; + }; + + ParserImpl.prototype.isDefaultSwitchClause = function () { + return this.currentToken().tokenKind === 20 /* DefaultKeyword */; + }; + + ParserImpl.prototype.isSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return true; + } + + return this.isCaseSwitchClause() || this.isDefaultSwitchClause(); + }; + + ParserImpl.prototype.parseSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return this.eatNode(); + } + + if (this.isCaseSwitchClause()) { + return this.parseCaseSwitchClause(); + } else if (this.isDefaultSwitchClause()) { + return this.parseDefaultSwitchClause(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseCaseSwitchClause = function () { + var caseKeyword = this.eatKeyword(16 /* CaseKeyword */); + var expression = this.parseExpression(true); + var colonToken = this.eatToken(107 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.caseSwitchClause(caseKeyword, expression, colonToken, statements); + }; + + ParserImpl.prototype.parseDefaultSwitchClause = function () { + var defaultKeyword = this.eatKeyword(20 /* DefaultKeyword */); + var colonToken = this.eatToken(107 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.defaultSwitchClause(defaultKeyword, colonToken, statements); + }; + + ParserImpl.prototype.isThrowStatement = function () { + return this.currentToken().tokenKind === 36 /* ThrowKeyword */; + }; + + ParserImpl.prototype.parseThrowStatement = function () { + var throwKeyword = this.eatKeyword(36 /* ThrowKeyword */); + + var expression = null; + if (this.canEatExplicitOrAutomaticSemicolon(false)) { + var token = this.createMissingToken(11 /* IdentifierName */, null); + expression = token; + } else { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.throwStatement(throwKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isReturnStatement = function () { + return this.currentToken().tokenKind === 33 /* ReturnKeyword */; + }; + + ParserImpl.prototype.parseReturnStatement = function () { + var returnKeyword = this.eatKeyword(33 /* ReturnKeyword */); + + var expression = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.returnStatement(returnKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isExpressionStatement = function () { + var currentToken = this.currentToken(); + + var kind = currentToken.tokenKind; + if (kind === 71 /* OpenBraceToken */ || kind === 27 /* FunctionKeyword */) { + return false; + } + + return this.isExpression(); + }; + + ParserImpl.prototype.isAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 80 /* CommaToken */) { + return true; + } + + return this.isExpression(); + }; + + ParserImpl.prototype.parseAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 80 /* CommaToken */) { + return this.factory.omittedExpression(); + } + + return this.parseAssignmentExpression(true); + }; + + ParserImpl.prototype.isExpression = function () { + var currentToken = this.currentToken(); + var kind = currentToken.tokenKind; + + switch (kind) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + return true; + + case 75 /* OpenBracketToken */: + case 73 /* OpenParenToken */: + return true; + + case 81 /* LessThanToken */: + return true; + + case 94 /* PlusPlusToken */: + case 95 /* MinusMinusToken */: + case 90 /* PlusToken */: + case 91 /* MinusToken */: + case 103 /* TildeToken */: + case 102 /* ExclamationToken */: + return true; + + case 71 /* OpenBraceToken */: + return true; + + case 86 /* EqualsGreaterThanToken */: + return true; + + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + return true; + + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + return true; + + case 31 /* NewKeyword */: + return true; + + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + return true; + + case 27 /* FunctionKeyword */: + return true; + } + + if (this.isIdentifier(this.currentToken())) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpressionStatement = function () { + var expression = this.parseExpression(true); + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.expressionStatement(expression, semicolon); + }; + + ParserImpl.prototype.isIfStatement = function () { + return this.currentToken().tokenKind === 28 /* IfKeyword */; + }; + + ParserImpl.prototype.parseIfStatement = function () { + var ifKeyword = this.eatKeyword(28 /* IfKeyword */); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var statement = this.parseStatement(); + + var elseClause = null; + if (this.isElseClause()) { + elseClause = this.parseElseClause(); + } + + return this.factory.ifStatement(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause); + }; + + ParserImpl.prototype.isElseClause = function () { + return this.currentToken().tokenKind === 23 /* ElseKeyword */; + }; + + ParserImpl.prototype.parseElseClause = function () { + var elseKeyword = this.eatKeyword(23 /* ElseKeyword */); + var statement = this.parseStatement(); + + return this.factory.elseClause(elseKeyword, statement); + }; + + ParserImpl.prototype.isVariableStatement = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 40 /* VarKeyword */; + }; + + ParserImpl.prototype.parseVariableStatement = function () { + var modifiers = this.parseModifiers(); + var variableDeclaration = this.parseVariableDeclaration(true); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.variableStatement(modifiers, variableDeclaration, semicolonToken); + }; + + ParserImpl.prototype.parseVariableDeclaration = function (allowIn) { + var varKeyword = this.eatKeyword(40 /* VarKeyword */); + + var listParsingState = allowIn ? 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + + var result = this.parseSeparatedSyntaxList(listParsingState); + var variableDeclarators = result.list; + varKeyword = this.addSkippedTokensAfterToken(varKeyword, result.skippedTokens); + + return this.factory.variableDeclaration(varKeyword, variableDeclarators); + }; + + ParserImpl.prototype.isVariableDeclarator = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 224 /* VariableDeclarator */) { + return true; + } + + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.canReuseVariableDeclaratorNode = function (node) { + if (node === null || node.kind() !== 224 /* VariableDeclarator */) { + return false; + } + + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + }; + + ParserImpl.prototype.parseVariableDeclarator = function (allowIn, allowPropertyName) { + if (this.canReuseVariableDeclaratorNode(this.currentNode())) { + return this.eatNode(); + } + + var propertyName = allowPropertyName ? this.eatPropertyName() : this.eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + + if (propertyName.width() > 0) { + typeAnnotation = this.parseOptionalTypeAnnotation(false); + + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(allowIn); + } + } + + return this.factory.variableDeclarator(propertyName, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.isColonValueClause = function () { + return this.currentToken().tokenKind === 107 /* ColonToken */; + }; + + ParserImpl.prototype.isEqualsValueClause = function (inParameter) { + var token0 = this.currentToken(); + if (token0.tokenKind === 108 /* EqualsToken */) { + return true; + } + + if (!this.previousToken().hasTrailingNewLine()) { + if (token0.tokenKind === 86 /* EqualsGreaterThanToken */) { + return false; + } + + if (token0.tokenKind === 71 /* OpenBraceToken */ && inParameter) { + return false; + } + + return this.isExpression(); + } + + return false; + }; + + ParserImpl.prototype.parseEqualsValueClause = function (allowIn) { + var equalsToken = this.eatToken(108 /* EqualsToken */); + var value = this.parseAssignmentExpression(allowIn); + + return this.factory.equalsValueClause(equalsToken, value); + }; + + ParserImpl.prototype.parseExpression = function (allowIn) { + return this.parseSubExpression(0, allowIn); + }; + + ParserImpl.prototype.parseAssignmentExpression = function (allowIn) { + return this.parseSubExpression(2 /* AssignmentExpressionPrecedence */, allowIn); + }; + + ParserImpl.prototype.parseUnaryExpression = function () { + var currentTokenKind = this.currentToken().tokenKind; + if (TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(currentTokenKind)) { + var operatorKind = TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(currentTokenKind); + + var operatorToken = this.eatAnyToken(); + + var operand = this.parseUnaryExpression(); + return this.factory.prefixUnaryExpression(operatorKind, operatorToken, operand); + } else { + return this.parseTerm(false); + } + }; + + ParserImpl.prototype.parseSubExpression = function (precedence, allowIn) { + var leftOperand = this.parseUnaryExpression(); + leftOperand = this.parseBinaryOrConditionalExpressions(precedence, allowIn, leftOperand); + + return leftOperand; + }; + + ParserImpl.prototype.parseBinaryOrConditionalExpressions = function (precedence, allowIn, leftOperand) { + while (true) { + var token0 = this.currentToken(); + var token0Kind = token0.tokenKind; + + if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(token0Kind)) { + if (token0Kind === 29 /* InKeyword */ && !allowIn) { + break; + } + + var mergedToken = this.tryMergeBinaryExpressionTokens(); + var tokenKind = mergedToken === null ? token0Kind : mergedToken.syntaxKind; + + var binaryExpressionKind = TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(tokenKind); + var newPrecedence = ParserImpl.getPrecedence(binaryExpressionKind); + + if (newPrecedence < precedence) { + break; + } + + if (newPrecedence === precedence && !this.isRightAssociative(binaryExpressionKind)) { + break; + } + + var operatorToken = mergedToken === null ? token0 : TypeScript.Syntax.token(mergedToken.syntaxKind).withLeadingTrivia(token0.leadingTrivia()).withTrailingTrivia(this.peekToken(mergedToken.tokenCount - 1).trailingTrivia()); + + var skipCount = mergedToken === null ? 1 : mergedToken.tokenCount; + for (var i = 0; i < skipCount; i++) { + this.eatAnyToken(); + } + + leftOperand = this.factory.binaryExpression(binaryExpressionKind, leftOperand, operatorToken, this.parseSubExpression(newPrecedence, allowIn)); + continue; + } + + if (token0Kind === 106 /* QuestionToken */ && precedence <= 3 /* ConditionalExpressionPrecedence */) { + var questionToken = this.eatToken(106 /* QuestionToken */); + + var whenTrueExpression = this.parseAssignmentExpression(allowIn); + var colon = this.eatToken(107 /* ColonToken */); + + var whenFalseExpression = this.parseAssignmentExpression(allowIn); + leftOperand = this.factory.conditionalExpression(leftOperand, questionToken, whenTrueExpression, colon, whenFalseExpression); + continue; + } + + break; + } + + return leftOperand; + }; + + ParserImpl.prototype.tryMergeBinaryExpressionTokens = function () { + var token0 = this.currentToken(); + + if (token0.tokenKind === 82 /* GreaterThanToken */ && !token0.hasTrailingTrivia()) { + var storage = this.mergeTokensStorage; + storage[0] = 0 /* None */; + storage[1] = 0 /* None */; + storage[2] = 0 /* None */; + + for (var i = 0; i < storage.length; i++) { + var nextToken = this.peekToken(i + 1); + + if (!nextToken.hasLeadingTrivia()) { + storage[i] = nextToken.tokenKind; + } + + if (nextToken.hasTrailingTrivia()) { + break; + } + } + + if (storage[0] === 82 /* GreaterThanToken */) { + if (storage[1] === 82 /* GreaterThanToken */) { + if (storage[2] === 108 /* EqualsToken */) { + return { tokenCount: 4, syntaxKind: 115 /* GreaterThanGreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 3, syntaxKind: 98 /* GreaterThanGreaterThanGreaterThanToken */ }; + } + } else if (storage[1] === 108 /* EqualsToken */) { + return { tokenCount: 3, syntaxKind: 114 /* GreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 2, syntaxKind: 97 /* GreaterThanGreaterThanToken */ }; + } + } else if (storage[0] === 108 /* EqualsToken */) { + return { tokenCount: 2, syntaxKind: 84 /* GreaterThanEqualsToken */ }; + } + } + + return null; + }; + + ParserImpl.prototype.isRightAssociative = function (expressionKind) { + switch (expressionKind) { + case 173 /* AssignmentExpression */: + case 174 /* AddAssignmentExpression */: + case 175 /* SubtractAssignmentExpression */: + case 176 /* MultiplyAssignmentExpression */: + case 177 /* DivideAssignmentExpression */: + case 178 /* ModuloAssignmentExpression */: + case 179 /* AndAssignmentExpression */: + case 180 /* ExclusiveOrAssignmentExpression */: + case 181 /* OrAssignmentExpression */: + case 182 /* LeftShiftAssignmentExpression */: + case 183 /* SignedRightShiftAssignmentExpression */: + case 184 /* UnsignedRightShiftAssignmentExpression */: + return true; + default: + return false; + } + }; + + ParserImpl.prototype.parseTerm = function (inObjectCreation) { + var term = this.parseTermWorker(); + if (term === null) { + return this.eatIdentifierToken(); + } + + return this.parsePostFixExpression(term, inObjectCreation); + }; + + ParserImpl.prototype.parsePostFixExpression = function (expression, inObjectCreation) { + while (true) { + var currentTokenKind = this.currentToken().tokenKind; + switch (currentTokenKind) { + case 73 /* OpenParenToken */: + if (inObjectCreation) { + return expression; + } + + expression = this.factory.invocationExpression(expression, this.parseArgumentList(null)); + continue; + + case 81 /* LessThanToken */: + if (inObjectCreation) { + return expression; + } + + var argumentList = this.tryParseArgumentList(); + if (argumentList !== null) { + expression = this.factory.invocationExpression(expression, argumentList); + continue; + } + + break; + + case 75 /* OpenBracketToken */: + expression = this.parseElementAccessExpression(expression, inObjectCreation); + continue; + + case 94 /* PlusPlusToken */: + case 95 /* MinusMinusToken */: + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + break; + } + + expression = this.factory.postfixUnaryExpression(TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(currentTokenKind), expression, this.eatAnyToken()); + continue; + + case 77 /* DotToken */: + expression = this.factory.memberAccessExpression(expression, this.eatToken(77 /* DotToken */), this.eatIdentifierNameToken()); + continue; + } + + return expression; + } + }; + + ParserImpl.prototype.tryParseArgumentList = function () { + var typeArgumentList = null; + + if (this.currentToken().tokenKind === 81 /* LessThanToken */) { + var rewindPoint = this.getRewindPoint(); + try { + typeArgumentList = this.tryParseTypeArgumentList(true); + var token0 = this.currentToken(); + + var isOpenParen = token0.tokenKind === 73 /* OpenParenToken */; + var isDot = token0.tokenKind === 77 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + if (typeArgumentList === null || !isOpenParenOrDot) { + this.rewind(rewindPoint); + return null; + } + + if (isDot) { + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token0.width(), 138 /* A_parameter_list_must_follow_a_generic_type_argument_list______expected */, null); + this.addDiagnostic(diagnostic); + + return this.factory.argumentList(typeArgumentList, TypeScript.Syntax.emptyToken(73 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.emptyToken(74 /* CloseParenToken */)); + } + } finally { + this.releaseRewindPoint(rewindPoint); + } + } + + if (this.currentToken().tokenKind === 73 /* OpenParenToken */) { + return this.parseArgumentList(typeArgumentList); + } + + return null; + }; + + ParserImpl.prototype.parseArgumentList = function (typeArgumentList) { + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var arguments = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.fullWidth() > 0) { + var result = this.parseSeparatedSyntaxList(16384 /* ArgumentList_AssignmentExpressions */); + arguments = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + return this.factory.argumentList(typeArgumentList, openParenToken, arguments, closeParenToken); + }; + + ParserImpl.prototype.parseElementAccessExpression = function (expression, inObjectCreation) { + var start = this.currentTokenStart(); + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + var argumentExpression; + + if (this.currentToken().tokenKind === 76 /* CloseBracketToken */ && inObjectCreation) { + var end = this.currentTokenStart() + this.currentToken().width(); + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, start, end - start, 137 /* _new_T____cannot_be_used_to_create_an_array__Use__new_Array_T_____instead */, null); + this.addDiagnostic(diagnostic); + + argumentExpression = TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } else { + argumentExpression = this.parseExpression(true); + } + + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + + return this.factory.elementAccessExpression(expression, openBracketToken, argumentExpression, closeBracketToken); + }; + + ParserImpl.prototype.parseTermWorker = function () { + var currentToken = this.currentToken(); + + if (currentToken.tokenKind === 86 /* EqualsGreaterThanToken */) { + return this.parseSimpleArrowFunctionExpression(); + } + + if (this.isIdentifier(currentToken)) { + if (this.isSimpleArrowFunctionExpression()) { + return this.parseSimpleArrowFunctionExpression(); + } else { + var identifier = this.eatIdentifierToken(); + return identifier; + } + } + + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + return this.parseThisExpression(); + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.parseLiteralExpression(); + + case 32 /* NullKeyword */: + return this.parseLiteralExpression(); + + case 31 /* NewKeyword */: + return this.parseObjectCreationExpression(); + + case 27 /* FunctionKeyword */: + return this.parseFunctionExpression(); + + case 50 /* SuperKeyword */: + return this.parseSuperExpression(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeOfExpression(); + + case 21 /* DeleteKeyword */: + return this.parseDeleteExpression(); + + case 41 /* VoidKeyword */: + return this.parseVoidExpression(); + + case 13 /* NumericLiteral */: + return this.parseLiteralExpression(); + + case 12 /* RegularExpressionLiteral */: + return this.parseLiteralExpression(); + + case 14 /* StringLiteral */: + return this.parseLiteralExpression(); + + case 75 /* OpenBracketToken */: + return this.parseArrayLiteralExpression(); + + case 71 /* OpenBraceToken */: + return this.parseObjectLiteralExpression(); + + case 73 /* OpenParenToken */: + return this.parseParenthesizedOrArrowFunctionExpression(); + + case 81 /* LessThanToken */: + return this.parseCastOrArrowFunctionExpression(); + + case 119 /* SlashToken */: + case 120 /* SlashEqualsToken */: + var result = this.tryReparseDivideAsRegularExpression(); + if (result !== null) { + return result; + } + break; + } + + return null; + }; + + ParserImpl.prototype.tryReparseDivideAsRegularExpression = function () { + var currentToken = this.currentToken(); + + if (this.previousToken() !== null) { + var previousTokenKind = this.previousToken().tokenKind; + switch (previousTokenKind) { + case 11 /* IdentifierName */: + return null; + + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return null; + + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 94 /* PlusPlusToken */: + case 95 /* MinusMinusToken */: + case 76 /* CloseBracketToken */: + case 72 /* CloseBraceToken */: + return null; + } + } + + currentToken = this.currentTokenAllowingRegularExpression(); + + if (currentToken.tokenKind === 119 /* SlashToken */ || currentToken.tokenKind === 120 /* SlashEqualsToken */) { + return null; + } else if (currentToken.tokenKind === 12 /* RegularExpressionLiteral */) { + return this.parseLiteralExpression(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseTypeOfExpression = function () { + var typeOfKeyword = this.eatKeyword(39 /* TypeOfKeyword */); + var expression = this.parseUnaryExpression(); + + return this.factory.typeOfExpression(typeOfKeyword, expression); + }; + + ParserImpl.prototype.parseDeleteExpression = function () { + var deleteKeyword = this.eatKeyword(21 /* DeleteKeyword */); + var expression = this.parseUnaryExpression(); + + return this.factory.deleteExpression(deleteKeyword, expression); + }; + + ParserImpl.prototype.parseVoidExpression = function () { + var voidKeyword = this.eatKeyword(41 /* VoidKeyword */); + var expression = this.parseUnaryExpression(); + + return this.factory.voidExpression(voidKeyword, expression); + }; + + ParserImpl.prototype.parseSuperExpression = function () { + var superKeyword = this.eatKeyword(50 /* SuperKeyword */); + return superKeyword; + }; + + ParserImpl.prototype.parseFunctionExpression = function () { + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = null; + + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionExpression(functionKeyword, identifier, callSignature, block); + }; + + ParserImpl.prototype.parseObjectCreationExpression = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + + var expression = this.parseTerm(true); + var argumentList = this.tryParseArgumentList(); + + return this.factory.objectCreationExpression(newKeyword, expression, argumentList); + }; + + ParserImpl.prototype.parseCastOrArrowFunctionExpression = function () { + var rewindPoint = this.getRewindPoint(); + try { + var arrowFunction = this.tryParseArrowFunctionExpression(); + if (arrowFunction !== null) { + return arrowFunction; + } + + this.rewind(rewindPoint); + return this.parseCastExpression(); + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.parseCastExpression = function () { + var lessThanToken = this.eatToken(81 /* LessThanToken */); + var type = this.parseType(); + var greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + var expression = this.parseUnaryExpression(); + + return this.factory.castExpression(lessThanToken, type, greaterThanToken, expression); + }; + + ParserImpl.prototype.parseParenthesizedOrArrowFunctionExpression = function () { + var result = this.tryParseArrowFunctionExpression(); + if (result !== null) { + return result; + } + + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + + return this.factory.parenthesizedExpression(openParenToken, expression, closeParenToken); + }; + + ParserImpl.prototype.tryParseArrowFunctionExpression = function () { + var tokenKind = this.currentToken().tokenKind; + + if (this.isDefinitelyArrowFunctionExpression()) { + return this.parseParenthesizedArrowFunctionExpression(false); + } + + if (!this.isPossiblyArrowFunctionExpression()) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + try { + var arrowFunction = this.parseParenthesizedArrowFunctionExpression(true); + if (arrowFunction === null) { + this.rewind(rewindPoint); + } + return arrowFunction; + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.parseParenthesizedArrowFunctionExpression = function (requireArrow) { + var currentToken = this.currentToken(); + + var callSignature = this.parseCallSignature(true); + + if (requireArrow && this.currentToken().tokenKind !== 86 /* EqualsGreaterThanToken */) { + return null; + } + + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var body = this.parseArrowFunctionBody(); + + return this.factory.parenthesizedArrowFunctionExpression(callSignature, equalsGreaterThanToken, body); + }; + + ParserImpl.prototype.parseArrowFunctionBody = function () { + if (this.isBlock()) { + return this.parseBlock(false, false); + } else { + return this.parseAssignmentExpression(true); + } + }; + + ParserImpl.prototype.isSimpleArrowFunctionExpression = function () { + if (this.currentToken().tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 86 /* EqualsGreaterThanToken */; + }; + + ParserImpl.prototype.parseSimpleArrowFunctionExpression = function () { + var identifier = this.eatIdentifierToken(); + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var body = this.parseArrowFunctionBody(); + + return this.factory.simpleArrowFunctionExpression(identifier, equalsGreaterThanToken, body); + }; + + ParserImpl.prototype.isBlock = function () { + return this.currentToken().tokenKind === 71 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isDefinitelyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 73 /* OpenParenToken */) { + return false; + } + + var token1 = this.peekToken(1); + var token2; + + if (token1.tokenKind === 74 /* CloseParenToken */) { + token2 = this.peekToken(2); + return token2.tokenKind === 107 /* ColonToken */ || token2.tokenKind === 86 /* EqualsGreaterThanToken */ || token2.tokenKind === 71 /* OpenBraceToken */; + } + + if (token1.tokenKind === 78 /* DotDotDotToken */) { + return true; + } + + if (!this.isIdentifier(token1)) { + return false; + } + + token2 = this.peekToken(2); + if (token2.tokenKind === 107 /* ColonToken */) { + return true; + } + + var token3 = this.peekToken(3); + if (token2.tokenKind === 106 /* QuestionToken */) { + if (token3.tokenKind === 107 /* ColonToken */ || token3.tokenKind === 74 /* CloseParenToken */ || token3.tokenKind === 80 /* CommaToken */) { + return true; + } + } + + if (token2.tokenKind === 74 /* CloseParenToken */) { + if (token3.tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPossiblyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 73 /* OpenParenToken */) { + return true; + } + + var token1 = this.peekToken(1); + + if (!this.isIdentifier(token1)) { + return false; + } + + var token2 = this.peekToken(2); + if (token2.tokenKind === 108 /* EqualsToken */) { + return true; + } + + if (token2.tokenKind === 80 /* CommaToken */) { + return true; + } + + if (token2.tokenKind === 74 /* CloseParenToken */) { + var token3 = this.peekToken(3); + if (token3.tokenKind === 107 /* ColonToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseObjectLiteralExpression = function () { + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var result = this.parseSeparatedSyntaxList(32768 /* ObjectLiteralExpression_PropertyAssignments */); + var propertyAssignments = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.objectLiteralExpression(openBraceToken, propertyAssignments, closeBraceToken); + }; + + ParserImpl.prototype.parsePropertyAssignment = function () { + if (this.isGetAccessorPropertyAssignment(false)) { + return this.parseGetAccessorPropertyAssignment(); + } else if (this.isSetAccessorPropertyAssignment(false)) { + return this.parseSetAccessorPropertyAssignment(); + } else if (this.isFunctionPropertyAssignment(false)) { + return this.parseFunctionPropertyAssignment(); + } else if (this.isSimplePropertyAssignment(false)) { + return this.parseSimplePropertyAssignment(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isPropertyAssignment = function (inErrorRecovery) { + return this.isGetAccessorPropertyAssignment(inErrorRecovery) || this.isSetAccessorPropertyAssignment(inErrorRecovery) || this.isFunctionPropertyAssignment(inErrorRecovery) || this.isSimplePropertyAssignment(inErrorRecovery); + }; + + ParserImpl.prototype.isGetAccessorPropertyAssignment = function (inErrorRecovery) { + return this.currentToken().tokenKind === 65 /* GetKeyword */ && this.isPropertyName(this.peekToken(1), inErrorRecovery); + }; + + ParserImpl.prototype.parseGetAccessorPropertyAssignment = function () { + var getKeyword = this.eatKeyword(65 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, true); + + return this.factory.getAccessorPropertyAssignment(getKeyword, propertyName, openParenToken, closeParenToken, typeAnnotation, block); + }; + + ParserImpl.prototype.isSetAccessorPropertyAssignment = function (inErrorRecovery) { + return this.currentToken().tokenKind === 69 /* SetKeyword */ && this.isPropertyName(this.peekToken(1), inErrorRecovery); + }; + + ParserImpl.prototype.parseSetAccessorPropertyAssignment = function () { + var setKeyword = this.eatKeyword(69 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var parameter = this.parseParameter(); + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + var block = this.parseBlock(false, true); + + return this.factory.setAccessorPropertyAssignment(setKeyword, propertyName, openParenToken, parameter, closeParenToken, block); + }; + + ParserImpl.prototype.eatPropertyName = function () { + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.currentToken()) ? this.eatIdentifierNameToken() : this.eatAnyToken(); + }; + + ParserImpl.prototype.isFunctionPropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery) && this.isCallSignature(1); + }; + + ParserImpl.prototype.parseFunctionPropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionPropertyAssignment(propertyName, callSignature, block); + }; + + ParserImpl.prototype.isSimplePropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseSimplePropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var colonToken = this.eatToken(107 /* ColonToken */); + var expression = this.parseAssignmentExpression(true); + + return this.factory.simplePropertyAssignment(propertyName, colonToken, expression); + }; + + ParserImpl.prototype.isPropertyName = function (token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return this.isIdentifier(token); + } else { + return true; + } + } + + switch (token.tokenKind) { + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseArrayLiteralExpression = function () { + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + + var result = this.parseSeparatedSyntaxList(65536 /* ArrayLiteralExpression_AssignmentExpressions */); + var expressions = result.list; + openBracketToken = this.addSkippedTokensAfterToken(openBracketToken, result.skippedTokens); + + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + + return this.factory.arrayLiteralExpression(openBracketToken, expressions, closeBracketToken); + }; + + ParserImpl.prototype.parseLiteralExpression = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.parseThisExpression = function () { + var thisKeyword = this.eatKeyword(35 /* ThisKeyword */); + return thisKeyword; + }; + + ParserImpl.prototype.parseBlock = function (parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = this.eatToken(71 /* OpenBraceToken */); + + var statements = TypeScript.Syntax.emptyList; + + if (parseBlockEvenWithNoOpenBrace || openBraceToken.width() > 0) { + var savedIsInStrictMode = this.isInStrictMode; + + var processItems = checkForStrictMode ? ParserImpl.updateStrictModeState : null; + var result = this.parseSyntaxList(32 /* Block_Statements */, processItems); + statements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + this.setStrictMode(savedIsInStrictMode); + } + + var closeBraceToken = this.eatToken(72 /* CloseBraceToken */); + + return this.factory.block(openBraceToken, statements, closeBraceToken); + }; + + ParserImpl.prototype.parseCallSignature = function (requireCompleteTypeParameterList) { + var typeParameterList = this.parseOptionalTypeParameterList(requireCompleteTypeParameterList); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.callSignature(typeParameterList, parameterList, typeAnnotation); + }; + + ParserImpl.prototype.parseOptionalTypeParameterList = function (requireCompleteTypeParameterList) { + if (this.currentToken().tokenKind !== 81 /* LessThanToken */) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + try { + var lessThanToken = this.eatToken(81 /* LessThanToken */); + + var result = this.parseSeparatedSyntaxList(524288 /* TypeParameterList_TypeParameters */); + var typeParameterList = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + var greaterThanToken = this.eatToken(82 /* GreaterThanToken */); + + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + this.rewind(rewindPoint); + return null; + } + + return this.factory.typeParameterList(lessThanToken, typeParameterList, greaterThanToken); + } finally { + this.releaseRewindPoint(rewindPoint); + } + }; + + ParserImpl.prototype.isTypeParameter = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.parseTypeParameter = function () { + var identifier = this.eatIdentifierToken(); + var constraint = this.parseOptionalConstraint(); + + return this.factory.typeParameter(identifier, constraint); + }; + + ParserImpl.prototype.parseOptionalConstraint = function () { + if (this.currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + + var extendsKeyword = this.eatKeyword(48 /* ExtendsKeyword */); + var type = this.parseType(); + + return this.factory.constraint(extendsKeyword, type); + }; + + ParserImpl.prototype.parseParameterList = function () { + var openParenToken = this.eatToken(73 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(131072 /* ParameterList_Parameters */); + parameters = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(74 /* CloseParenToken */); + return this.factory.parameterList(openParenToken, parameters, closeParenToken); + }; + + ParserImpl.prototype.isTypeAnnotation = function () { + return this.currentToken().tokenKind === 107 /* ColonToken */; + }; + + ParserImpl.prototype.parseOptionalTypeAnnotation = function (allowStringLiteral) { + return this.isTypeAnnotation() ? this.parseTypeAnnotation(allowStringLiteral) : null; + }; + + ParserImpl.prototype.parseTypeAnnotation = function (allowStringLiteral) { + var colonToken = this.eatToken(107 /* ColonToken */); + var type = allowStringLiteral && this.currentToken().tokenKind === 14 /* StringLiteral */ ? this.eatToken(14 /* StringLiteral */) : this.parseType(); + + return this.factory.typeAnnotation(colonToken, type); + }; + + ParserImpl.prototype.isType = function () { + return this.isPredefinedType() || this.isTypeLiteral() || this.isName(); + }; + + ParserImpl.prototype.parseType = function () { + var type = this.parseNonArrayType(); + + while (this.currentToken().tokenKind === 75 /* OpenBracketToken */) { + var openBracketToken = this.eatToken(75 /* OpenBracketToken */); + var closeBracketToken = this.eatToken(76 /* CloseBracketToken */); + + type = this.factory.arrayType(type, openBracketToken, closeBracketToken); + } + + return type; + }; + + ParserImpl.prototype.parseNonArrayType = function () { + if (this.isPredefinedType()) { + return this.parsePredefinedType(); + } else if (this.isTypeLiteral()) { + return this.parseTypeLiteral(); + } else { + return this.parseNameOrGenericType(); + } + }; + + ParserImpl.prototype.parseNameOrGenericType = function () { + var name = this.parseName(); + var typeArgumentList = this.tryParseTypeArgumentList(false); + + return typeArgumentList === null ? name : this.factory.genericType(name, typeArgumentList); + }; + + ParserImpl.prototype.parseTypeLiteral = function () { + if (this.isObjectType()) { + return this.parseObjectType(); + } else if (this.isFunctionType()) { + return this.parseFunctionType(); + } else if (this.isConstructorType()) { + return this.parseConstructorType(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseFunctionType = function () { + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var returnType = this.parseType(); + + return this.factory.functionType(typeParameterList, parameterList, equalsGreaterThanToken, returnType); + }; + + ParserImpl.prototype.parseConstructorType = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(86 /* EqualsGreaterThanToken */); + var type = this.parseType(); + + return this.factory.constructorType(newKeyword, null, parameterList, equalsGreaterThanToken, type); + }; + + ParserImpl.prototype.isTypeLiteral = function () { + return this.isObjectType() || this.isFunctionType() || this.isConstructorType(); + }; + + ParserImpl.prototype.isObjectType = function () { + return this.currentToken().tokenKind === 71 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isFunctionType = function () { + var tokenKind = this.currentToken().tokenKind; + return tokenKind === 73 /* OpenParenToken */ || tokenKind === 81 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructorType = function () { + return this.currentToken().tokenKind === 31 /* NewKeyword */; + }; + + ParserImpl.prototype.parsePredefinedType = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.isPredefinedType = function () { + switch (this.currentToken().tokenKind) { + case 60 /* AnyKeyword */: + case 68 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 62 /* BoolKeyword */: + case 70 /* StringKeyword */: + case 41 /* VoidKeyword */: + return true; + } + + return false; + }; + + ParserImpl.prototype.isParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return true; + } + + var token = this.currentToken(); + if (token.tokenKind === 78 /* DotDotDotToken */) { + return true; + } + + if (ParserImpl.isPublicOrPrivateKeyword(token)) { + return true; + } + + return this.isIdentifier(token); + }; + + ParserImpl.prototype.parseParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return this.eatNode(); + } + + var dotDotDotToken = this.tryEatToken(78 /* DotDotDotToken */); + + var publicOrPrivateToken = null; + if (ParserImpl.isPublicOrPrivateKeyword(this.currentToken())) { + publicOrPrivateToken = this.eatAnyToken(); + } + + var identifier = this.eatIdentifierToken(); + var questionToken = this.tryEatToken(106 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(true); + + var equalsValueClause = null; + if (this.isEqualsValueClause(true)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.parameter(dotDotDotToken, publicOrPrivateToken, identifier, questionToken, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.parseSyntaxList = function (currentListType, processItems) { + if (typeof processItems === "undefined") { processItems = null; } + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSyntaxListWorker(currentListType, processItems); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.parseSeparatedSyntaxList = function (currentListType) { + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSeparatedSyntaxListWorker(currentListType); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { + this.reportUnexpectedTokenDiagnostic(currentListType); + + for (var state = 262144 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + if ((this.listParsingState & state) !== 0) { + if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { + return true; + } + } + } + + var skippedToken = this.currentToken(); + + this.moveToNextToken(); + + this.addSkippedTokenToList(items, skippedTokens, skippedToken); + + return false; + }; + + ParserImpl.prototype.addSkippedTokenToList = function (items, skippedTokens, skippedToken) { + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + var lastToken = item.lastToken(); + if (lastToken.fullWidth() > 0) { + items[i] = this.addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + + skippedTokens.push(skippedToken); + }; + + ParserImpl.prototype.tryParseExpectedListItem = function (currentListType, inErrorRecovery, items, processItems) { + if (this.isExpectedListItem(currentListType, inErrorRecovery)) { + var item = this.parseExpectedListItem(currentListType); + + items.push(item); + + if (processItems !== null) { + processItems(this, items); + } + } + }; + + ParserImpl.prototype.listIsTerminated = function (currentListType) { + return this.isExpectedListTerminator(currentListType) || this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.getArray = function () { + if (this.arrayPool.length > 0) { + return this.arrayPool.pop(); + } + + return []; + }; + + ParserImpl.prototype.returnZeroOrOneLengthArray = function (array) { + if (array.length <= 1) { + this.returnArray(array); + } + }; + + ParserImpl.prototype.returnArray = function (array) { + array.length = 0; + this.arrayPool.push(array); + }; + + ParserImpl.prototype.parseSyntaxListWorker = function (currentListType, processItems) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + + while (true) { + var oldItemsCount = items.length; + this.tryParseExpectedListItem(currentListType, false, items, processItems); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } + } + } + + var result = TypeScript.Syntax.list(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.parseSeparatedSyntaxListWorker = function (currentListType) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + TypeScript.Debug.assert(items.length === 0); + TypeScript.Debug.assert(skippedTokens.length === 0); + TypeScript.Debug.assert(skippedTokens !== items); + + var separatorKind = this.separatorKind(currentListType); + var allowAutomaticSemicolonInsertion = separatorKind === 79 /* SemicolonToken */; + + var inErrorRecovery = false; + var listWasTerminated = false; + while (true) { + var oldItemsCount = items.length; + + this.tryParseExpectedListItem(currentListType, inErrorRecovery, items, null); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } else { + inErrorRecovery = true; + continue; + } + } + + inErrorRecovery = false; + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === separatorKind || currentToken.tokenKind === 80 /* CommaToken */) { + items.push(this.eatAnyToken()); + continue; + } + + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + if (allowAutomaticSemicolonInsertion && this.canEatAutomaticSemicolon(false)) { + items.push(this.eatExplicitOrAutomaticSemicolon(false)); + + continue; + } + + items.push(this.eatToken(separatorKind)); + + inErrorRecovery = true; + } + + var result = TypeScript.Syntax.separatedList(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.separatorKind = function (currentListType) { + switch (currentListType) { + case 2048 /* HeritageClause_TypeNameList */: + case 16384 /* ArgumentList_AssignmentExpressions */: + case 256 /* EnumDeclaration_EnumElements */: + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + case 131072 /* ParameterList_Parameters */: + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + case 262144 /* TypeArgumentList_Types */: + case 524288 /* TypeParameterList_TypeParameters */: + return 80 /* CommaToken */; + + case 512 /* ObjectType_TypeMembers */: + return 79 /* SemicolonToken */; + + case 1 /* SourceUnit_ModuleElements */: + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + case 2 /* ClassDeclaration_ClassElements */: + case 4 /* ModuleDeclaration_ModuleElements */: + case 8 /* SwitchStatement_SwitchClauses */: + case 16 /* SwitchClause_Statements */: + case 32 /* Block_Statements */: + default: + throw TypeScript.Errors.notYetImplemented(); + } + }; + + ParserImpl.prototype.reportUnexpectedTokenDiagnostic = function (listType) { + var token = this.currentToken(); + + var diagnostic = new TypeScript.SyntaxDiagnostic(this.fileName, this.currentTokenStart(), token.width(), 12 /* Unexpected_token__0_expected */, [this.getExpectedListElementType(listType)]); + this.addDiagnostic(diagnostic); + }; + + ParserImpl.prototype.addDiagnostic = function (diagnostic) { + if (this.diagnostics.length > 0 && this.diagnostics[this.diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + + this.diagnostics.push(diagnostic); + }; + + ParserImpl.prototype.isExpectedListTerminator = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isExpectedSourceUnit_ModuleElementsTerminator(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isExpectedClassDeclaration_ClassElementsTerminator(); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isExpectedModuleDeclaration_ModuleElementsTerminator(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isExpectedSwitchStatement_SwitchClausesTerminator(); + + case 16 /* SwitchClause_Statements */: + return this.isExpectedSwitchClause_StatementsTerminator(); + + case 32 /* Block_Statements */: + return this.isExpectedBlock_StatementsTerminator(); + + case 64 /* TryBlock_Statements */: + return this.isExpectedTryBlock_StatementsTerminator(); + + case 128 /* CatchBlock_Statements */: + return this.isExpectedCatchBlock_StatementsTerminator(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.isExpectedEnumDeclaration_EnumElementsTerminator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isExpectedObjectType_TypeMembersTerminator(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpressionsTerminator(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isExpectedHeritageClause_TypeNameListTerminator(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + + case 131072 /* ParameterList_Parameters */: + return this.isExpectedParameterList_ParametersTerminator(); + + case 262144 /* TypeArgumentList_Types */: + return this.isExpectedTypeArgumentList_TypesTerminator(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isExpectedTypeParameterList_TypeParametersTerminator(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedSourceUnit_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.isExpectedEnumDeclaration_EnumElementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedModuleDeclaration_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectType_TypeMembersTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedLiteralExpression_AssignmentExpressionsTerminator = function () { + return this.currentToken().tokenKind === 76 /* CloseBracketToken */; + }; + + ParserImpl.prototype.isExpectedTypeArgumentList_TypesTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 82 /* GreaterThanToken */) { + return true; + } + + if (this.canFollowTypeArgumentListInExpression(token.tokenKind)) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedTypeParameterList_TypeParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 82 /* GreaterThanToken */) { + return true; + } + + if (token.tokenKind === 73 /* OpenParenToken */ || token.tokenKind === 71 /* OpenBraceToken */ || token.tokenKind === 48 /* ExtendsKeyword */ || token.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedParameterList_ParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 74 /* CloseParenToken */) { + return true; + } + + if (token.tokenKind === 71 /* OpenBraceToken */) { + return true; + } + + if (token.tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator = function () { + if (this.currentToken().tokenKind === 79 /* SemicolonToken */ || this.currentToken().tokenKind === 74 /* CloseParenToken */) { + return true; + } + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator = function () { + if (this.previousToken().tokenKind === 80 /* CommaToken */) { + return false; + } + + if (this.currentToken().tokenKind === 86 /* EqualsGreaterThanToken */) { + return true; + } + + return this.canEatExplicitOrAutomaticSemicolon(false); + }; + + ParserImpl.prototype.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 71 /* OpenBraceToken */ || token0.tokenKind === 72 /* CloseBraceToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedHeritageClause_TypeNameListTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + if (this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpressionsTerminator = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 74 /* CloseParenToken */ || token0.tokenKind === 79 /* SemicolonToken */; + }; + + ParserImpl.prototype.isExpectedClassDeclaration_ClassElementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchStatement_SwitchClausesTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchClause_StatementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */ || this.isSwitchClause(); + }; + + ParserImpl.prototype.isExpectedBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 72 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedTryBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */ || this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedCatchBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.isStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.isStatement(inErrorRecovery); + + case 64 /* TryBlock_Statements */: + case 128 /* CatchBlock_Statements */: + return false; + + case 256 /* EnumDeclaration_EnumElements */: + return this.isEnumElement(inErrorRecovery); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isVariableDeclarator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpression(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isHeritageClauseTypeName(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isPropertyAssignment(inErrorRecovery); + + case 131072 /* ParameterList_Parameters */: + return this.isParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.isType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isTypeParameter(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isAssignmentOrOmittedExpression(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpression = function () { + if (this.isExpression()) { + return true; + } + + if (this.currentToken().tokenKind === 80 /* CommaToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpectedListItem = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.parseModuleElement(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.parseHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.parseClassElement(false); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.parseModuleElement(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.parseSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.parseStatement(); + + case 32 /* Block_Statements */: + return this.parseStatement(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.parseEnumElement(); + + case 512 /* ObjectType_TypeMembers */: + return this.parseTypeMember(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.parseAssignmentExpression(true); + + case 2048 /* HeritageClause_TypeNameList */: + return this.parseNameOrGenericType(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.parseVariableDeclarator(true, false); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.parseVariableDeclarator(false, false); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.parsePropertyAssignment(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.parseAssignmentOrOmittedExpression(); + + case 131072 /* ParameterList_Parameters */: + return this.parseParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.parseType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.parseTypeParameter(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.getExpectedListElementType = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return TypeScript.Strings.module__class__interface__enum__import_or_statement; + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + + case 2 /* ClassDeclaration_ClassElements */: + return TypeScript.Strings.constructor__function__accessor_or_variable; + + case 4 /* ModuleDeclaration_ModuleElements */: + return TypeScript.Strings.module__class__interface__enum__import_or_statement; + + case 8 /* SwitchStatement_SwitchClauses */: + return TypeScript.Strings.case_or_default_clause; + + case 16 /* SwitchClause_Statements */: + return TypeScript.Strings.statement; + + case 32 /* Block_Statements */: + return TypeScript.Strings.statement; + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.Strings.identifier; + + case 256 /* EnumDeclaration_EnumElements */: + return TypeScript.Strings.identifier; + + case 512 /* ObjectType_TypeMembers */: + return TypeScript.Strings.call__construct__index__property_or_function_signature; + + case 16384 /* ArgumentList_AssignmentExpressions */: + return TypeScript.Strings.expression; + + case 2048 /* HeritageClause_TypeNameList */: + return TypeScript.Strings.type_name; + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.Strings.property_or_accessor; + + case 131072 /* ParameterList_Parameters */: + return TypeScript.Strings.parameter; + + case 262144 /* TypeArgumentList_Types */: + return TypeScript.Strings.type; + + case 524288 /* TypeParameterList_TypeParameters */: + return TypeScript.Strings.type_parameter; + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.Strings.expression; + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + return ParserImpl; + })(); + + function parse(fileName, text, isDeclaration, languageVersion, options) { + var source = new NormalParserSource(fileName, text, languageVersion); + + return new ParserImpl(fileName, text.lineMap(), source, options).parseSyntaxTree(isDeclaration); + } + Parser.parse = parse; + + function incrementalParse(oldSyntaxTree, textChangeRange, newText) { + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + + var source = new IncrementalParserSource(oldSyntaxTree, textChangeRange, newText); + + return new ParserImpl(oldSyntaxTree.fileName(), newText.lineMap(), source, oldSyntaxTree.parseOptions()).parseSyntaxTree(oldSyntaxTree.isDeclaration()); + } + Parser.incrementalParse = incrementalParse; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTree = (function () { + function SyntaxTree(sourceUnit, isDeclaration, diagnostics, fileName, lineMap, languageVersion, parseOtions) { + this._allDiagnostics = null; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = lineMap; + this._languageVersion = languageVersion; + this._parseOptions = parseOtions; + } + SyntaxTree.prototype.toJSON = function (key) { + var result = {}; + + result.isDeclaration = this._isDeclaration; + result.languageVersion = TypeScript.LanguageVersion[this._languageVersion]; + result.parseOptions = this._parseOptions; + + if (this.diagnostics().length > 0) { + result.diagnostics = this.diagnostics(); + } + + result.sourceUnit = this._sourceUnit; + result.lineMap = this._lineMap; + + return result; + }; + + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + + var diagnostics = []; + this.sourceUnit().accept(new GrammarCheckerWalker(this, diagnostics)); + + return diagnostics; + }; + + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + this._allDiagnostics = this.computeDiagnostics(); + } + + return this._allDiagnostics; + }; + + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + + SyntaxTree.prototype.languageVersion = function () { + return this._languageVersion; + }; + + SyntaxTree.prototype.parseOptions = function () { + return this._parseOptions; + }; + + SyntaxTree.prototype.structuralEquals = function (tree) { + return TypeScript.ArrayUtilities.sequenceEquals(this.diagnostics(), tree.diagnostics(), TypeScript.SyntaxDiagnostic.equals) && this.sourceUnit().structuralEquals(tree.sourceUnit()); + }; + return SyntaxTree; + })(); + TypeScript.SyntaxTree = SyntaxTree; + + var GrammarCheckerWalker = (function (_super) { + __extends(GrammarCheckerWalker, _super); + function GrammarCheckerWalker(syntaxTree, diagnostics) { + _super.call(this); + this.syntaxTree = syntaxTree; + this.diagnostics = diagnostics; + this.inAmbientDeclaration = false; + this.inBlock = false; + this.currentConstructor = null; + } + GrammarCheckerWalker.prototype.childFullStart = function (parent, child) { + return this.position() + TypeScript.Syntax.childOffset(parent, child); + }; + + GrammarCheckerWalker.prototype.childStart = function (parent, child) { + return this.childFullStart(parent, child) + child.leadingTriviaWidth(); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic = function (start, length, diagnosticCode, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.SyntaxDiagnostic(this.syntaxTree.fileName(), start, length, diagnosticCode, args)); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic1 = function (elementFullStart, element, diagnosticCode, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.SyntaxDiagnostic(this.syntaxTree.fileName(), elementFullStart + element.leadingTriviaWidth(), element.width(), diagnosticCode, args)); + }; + + GrammarCheckerWalker.prototype.visitCatchClause = function (node) { + if (node.typeAnnotation) { + this.pushDiagnostic(this.childStart(node, node.typeAnnotation), node.typeAnnotation.width(), 17 /* A_catch_clause_variable_cannot_have_a_type_annotation */); + } + + _super.prototype.visitCatchClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkParameterListOrder = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + var seenOptionalParameter = false; + var parameterCount = node.parameters.nonSeparatorCount(); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameterIndex = i / 2; + var parameter = node.parameters.childAt(i); + + if (parameter.dotDotDotToken) { + if (parameterIndex !== (parameterCount - 1)) { + this.pushDiagnostic1(parameterFullStart, parameter, 18 /* Rest_parameter_must_be_last_in_list */); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 56 /* Rest_parameter_cannot_be_optional */); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 57 /* Rest_parameter_cannot_have_initializer */); + return true; + } + } else if (parameter.questionToken || parameter.equalsValueClause) { + seenOptionalParameter = true; + + if (parameter.questionToken && parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 19 /* Parameter_cannot_have_question_mark_and_initializer */); + return true; + } + } else { + if (seenOptionalParameter) { + this.pushDiagnostic1(parameterFullStart, parameter, 20 /* Required_parameter_cannot_follow_optional_parameter */); + return true; + } + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterListAcessibilityModifiers = function (node) { + if (this.currentConstructor !== null && this.currentConstructor.parameterList === node && this.currentConstructor.block && !this.inAmbientDeclaration) { + return false; + } + + var parameterFullStart = this.childFullStart(node, node.parameters); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameter = node.parameters.childAt(i); + + if (parameter.publicOrPrivateKeyword) { + var keywordFullStart = parameterFullStart + TypeScript.Syntax.childOffset(parameter, parameter.publicOrPrivateKeyword); + this.pushDiagnostic1(keywordFullStart, parameter.publicOrPrivateKeyword, 43 /* Overload_and_ambient_signatures_cannot_specify_parameter_properties */); + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForTrailingSeparator = function (parent, list) { + if (list.childCount() === 0 || list.childCount() % 2 === 1) { + return false; + } + + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i === n - 1) { + this.pushDiagnostic1(currentElementFullStart, child, 13 /* Trailing_separator_not_allowed */); + } + + currentElementFullStart += child.fullWidth(); + } + + return true; + }; + + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, expected) { + if (list.childCount() > 0) { + return false; + } + + var listFullStart = this.childFullStart(parent, list); + var tokenAtStart = this.syntaxTree.sourceUnit().findToken(listFullStart); + + this.pushDiagnostic1(listFullStart, tokenAtStart.token(), 12 /* Unexpected_token__0_expected */, [expected]); + + return true; + }; + + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingSeparator(node, node.parameters)) { + this.skip(node); + return; + } + + _super.prototype.visitParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingSeparator(node, node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, TypeScript.Strings.type_name)) { + this.skip(node); + return; + } + + _super.prototype.visitHeritageClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.arguments)) { + this.skip(node); + return; + } + + _super.prototype.visitArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForTrailingSeparator(node, node.variableDeclarators) || this.checkForAtLeastOneElement(node, node.variableDeclarators, TypeScript.Strings.identifier)) { + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, TypeScript.Strings.identifier)) { + this.skip(node); + return; + } + + _super.prototype.visitTypeArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, TypeScript.Strings.identifier)) { + this.skip(node); + return; + } + + _super.prototype.visitTypeParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameter); + var parameter = node.parameter; + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 21 /* Index_signatures_cannot_have_rest_parameters */); + return true; + } else if (parameter.publicOrPrivateKeyword) { + this.pushDiagnostic1(parameterFullStart, parameter, 22 /* Index_signature_parameter_cannot_have_accessibility_modifiers */); + return true; + } else if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 23 /* Index_signature_parameter_cannot_have_a_question_mark */); + return true; + } else if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 24 /* Index_signature_parameter_cannot_have_an_initializer */); + return true; + } else if (!parameter.typeAnnotation) { + this.pushDiagnostic1(parameterFullStart, parameter, 26 /* Index_signature_parameter_must_have_a_type_annotation */); + return true; + } else if (parameter.typeAnnotation.type.kind() !== 70 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 68 /* NumberKeyword */) { + this.pushDiagnostic1(parameterFullStart, parameter, 27 /* Index_signature_parameter_type_must_be__string__or__number_ */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + this.skip(node); + return; + } + + if (!node.typeAnnotation) { + this.pushDiagnostic1(this.position(), node, 25 /* Index_signature_must_have_a_type_annotation */); + this.skip(node); + return; + } + + _super.prototype.visitIndexSignature.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + var seenImplementsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 28 /* _extends__clause_already_seen */); + return true; + } + + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 29 /* _extends__clause_must_precede__implements__clause */); + return true; + } + + if (heritageClause.typeNames.nonSeparatorCount() > 1) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 30 /* Class_can_only_extend_single_type */); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 31 /* _implements__clause_already_seen */); + return true; + } + + seenImplementsClause = true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 64 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, 41 /* _declare__modifier_not_allowed_for_code_already_in_an_ambient_context */); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, typeKeyword, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 64 /* DeclareKeyword */)) { + this.pushDiagnostic1(this.childFullStart(moduleElement, typeKeyword), typeKeyword.firstToken(), 49 /* _declare__modifier_required_for_top_level_element */); + return true; + } + } + }; + + GrammarCheckerWalker.prototype.checkFunctionOverloads = function (node, moduleElements) { + if (!this.inAmbientDeclaration && !this.syntaxTree.isDeclaration()) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + + var inFunctionOverloadChain = false; + var functionOverloadChainName = null; + + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (moduleElement.kind() !== 129 /* FunctionDeclaration */) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + + var functionDeclaration = moduleElement; + if (functionDeclaration.identifier.valueText() !== functionOverloadChainName) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, 46 /* Function_overload_name_must_be__0_ */, [functionOverloadChainName]); + return true; + } + } + + if (moduleElement.kind() === 129 /* FunctionDeclaration */) { + functionDeclaration = moduleElement; + if (!TypeScript.SyntaxUtilities.containsToken(functionDeclaration.modifiers, 64 /* DeclareKeyword */)) { + inFunctionOverloadChain = functionDeclaration.block === null; + functionOverloadChainName = functionDeclaration.identifier.valueText(); + + if (lastElement && inFunctionOverloadChain) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + } else { + inFunctionOverloadChain = false; + functionOverloadChainName = ""; + } + } + + moduleElementFullStart += moduleElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkClassOverloads = function (node) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */)) { + var classElementFullStart = this.childFullStart(node, node.classElements); + + var inFunctionOverloadChain = false; + var inConstructorOverloadChain = false; + + var functionOverloadChainName = null; + var memberFunctionDeclaration = null; + + for (var i = 0, n = node.classElements.childCount(); i < n; i++) { + var classElement = node.classElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (classElement.kind() !== 135 /* MemberFunctionDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + + memberFunctionDeclaration = classElement; + if (memberFunctionDeclaration.propertyName.valueText() !== functionOverloadChainName) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, 46 /* Function_overload_name_must_be__0_ */, [functionOverloadChainName]); + return true; + } + } else if (inConstructorOverloadChain) { + if (classElement.kind() !== 137 /* ConstructorDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 45 /* Constructor_implementation_expected */); + return true; + } + } + + if (classElement.kind() === 135 /* MemberFunctionDeclaration */) { + memberFunctionDeclaration = classElement; + + inFunctionOverloadChain = memberFunctionDeclaration.block === null; + functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); + + if (lastElement && inFunctionOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 44 /* Function_implementation_expected */); + return true; + } + } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = classElement; + + inConstructorOverloadChain = constructorDeclaration.block === null; + if (lastElement && inConstructorOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), 45 /* Constructor_implementation_expected */); + return true; + } + } + + classElementFullStart += classElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForReservedName = function (parent, name, code) { + var nameFullStart = this.childFullStart(parent, name); + var token; + var tokenFullStart; + + var current = name; + while (current !== null) { + if (current.kind() === 122 /* QualifiedName */) { + var qualifiedName = current; + token = qualifiedName.right; + tokenFullStart = nameFullStart + this.childFullStart(qualifiedName, token); + current = qualifiedName.left; + } else { + TypeScript.Debug.assert(current.kind() === 11 /* IdentifierName */); + token = current; + tokenFullStart = nameFullStart; + current = null; + } + + switch (token.valueText()) { + case "any": + case "number": + case "bool": + case "string": + case "void": + this.pushDiagnostic(tokenFullStart + token.leadingTriviaWidth(), token.width(), code, [token.valueText()]); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, 60 /* Class_name_cannot_be__0_ */) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.classKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node) || this.checkClassOverloads(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 28 /* _extends__clause_already_seen */); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, 36 /* Interface_declaration_cannot_have__implements__clause */); + return true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + var modifierFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 64 /* DeclareKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, 48 /* _declare__modifier_cannot_appear_on_an_interface_declaration */); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, 61 /* Interface_name_cannot_be__0_ */) || this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + this.skip(node); + return; + } + + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var modifierFullStart = this.position(); + + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var modifier = list.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 32 /* Accessibility_modifier_already_seen */); + return true; + } + + if (seenStaticModifier) { + var previousToken = list.childAt(i - 1); + this.pushDiagnostic1(modifierFullStart, modifier, 33 /* _0__modifier_must_precede__1__modifier */, [modifier.text(), previousToken.text()]); + return true; + } + + seenAccessibilityModifier = true; + } else if (modifier.tokenKind === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 34 /* _0__modifier_already_seen */, [modifier.text()]); + return true; + } + + seenStaticModifier = true; + } else { + this.pushDiagnostic1(modifierFullStart, modifier, 35 /* _0__modifier_cannot_appear_on_a_class_element */, [modifier.text()]); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkGetMemberAccessorParameter = function (node) { + var getKeywordFullStart = this.childFullStart(node, node.getKeyword); + if (node.parameterList.parameters.childCount() !== 0) { + this.pushDiagnostic1(getKeywordFullStart, node.getKeyword, 55 /* _get__accessor_cannot_have_parameters */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, node, languageVersion, code) { + if (this.syntaxTree.languageVersion() < languageVersion) { + var nodeFullStart = this.childFullStart(parent, node); + this.pushDiagnostic1(nodeFullStart, node, code); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitGetMemberAccessorDeclaration = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */) || this.checkClassElementModifiers(node.modifiers) || this.checkGetMemberAccessorParameter(node)) { + this.skip(node); + return; + } + + _super.prototype.visitGetMemberAccessorDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkSetMemberAccessorParameter = function (node) { + var setKeywordFullStart = this.childFullStart(node, node.setKeyword); + if (node.parameterList.parameters.childCount() !== 1) { + this.pushDiagnostic1(setKeywordFullStart, node.setKeyword, 50 /* _set__accessor_must_have_only_one_parameter */); + return true; + } + + var parameterListFullStart = this.childFullStart(node, node.parameterList); + var parameterFullStart = parameterListFullStart + TypeScript.Syntax.childOffset(node.parameterList, node.parameterList.openParenToken); + var parameter = node.parameterList.parameters.childAt(0); + + if (parameter.publicOrPrivateKeyword) { + this.pushDiagnostic1(parameterFullStart, parameter, 51 /* _set__accessor_parameter_cannot_have_accessibility_modifier */); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 52 /* _set__accessor_parameter_cannot_be_optional */); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, 53 /* _set__accessor_parameter_cannot_have_initializer */); + return true; + } + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, 54 /* _set__accessor_cannot_have_rest_parameter */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSetMemberAccessorDeclaration = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */) || this.checkClassElementModifiers(node.modifiers) || this.checkSetMemberAccessorParameter(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSetMemberAccessorDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitGetAccessorPropertyAssignment = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */)) { + this.skip(node); + return; + } + + _super.prototype.visitGetAccessorPropertyAssignment.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSetAccessorPropertyAssignment = function (node) { + if (this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, 59 /* Accessors_are_only_available_when_targeting_EcmaScript5_and_higher */)) { + this.skip(node); + return; + } + + _super.prototype.visitSetAccessorPropertyAssignment.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, 62 /* Enum_name_cannot_be__0_ */) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.enumKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var enumElementFullStart = this.childFullStart(node, node.enumElements); + + var seenComputedValue = false; + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + var child = node.enumElements.childAt(i); + + if (i % 2 === 0) { + var enumElement = child; + + if (!enumElement.equalsValueClause && seenComputedValue) { + this.pushDiagnostic1(enumElementFullStart, enumElement, 64 /* Enum_member_must_have_initializer */, null); + return true; + } + + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + if (value.kind() !== 13 /* NumericLiteral */) { + seenComputedValue = true; + } + } + } + + enumElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic1(this.position(), node, 37 /* _super__invocation_cannot_have_type_arguments */); + } + + _super.prototype.visitInvocationExpression.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var modifierFullStart = this.position(); + var seenExportModifier = false; + var seenDeclareModifier = false; + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */ || modifier.tokenKind === 58 /* StaticKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, 47 /* _0__modifier_cannot_appear_on_a_module_element */, [modifier.text()]); + return true; + } + + if (modifier.tokenKind === 64 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 32 /* Accessibility_modifier_already_seen */); + return; + } + + seenDeclareModifier = true; + } else if (modifier.tokenKind === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 34 /* _0__modifier_already_seen */, [modifier.text()]); + return; + } + + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, 33 /* _0__modifier_must_precede__1__modifier */, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(64 /* DeclareKeyword */)]); + return; + } + + seenExportModifier = true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + if (node.stringLiteral === null) { + var currentElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.pushDiagnostic1(currentElementFullStart, importDeclaration, 201 /* Import_declarations_in_an_internal_module_cannot_reference_an_external_module */, null); + } + } + + currentElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForReservedName(node, node.moduleName, 63 /* Module_name_cannot_be__0_ */) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.moduleKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (!TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) && this.checkFunctionOverloads(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (node.stringLiteral && !this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */)) { + var stringLiteralFullStart = this.childFullStart(node, node.stringLiteral); + this.pushDiagnostic1(stringLiteralFullStart, node.stringLiteral, 38 /* Non_ambient_modules_cannot_use_quoted_names */); + this.skip(node); + return; + } + + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExports = function (node, moduleElements) { + var seenExportedElement = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (TypeScript.SyntaxUtilities.hasExportKeyword(child)) { + seenExportedElement = true; + break; + } + } + + var moduleElementFullStart = this.childFullStart(node, moduleElements); + if (seenExportedElement) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, 67 /* Export_assignment_not_allowed_in_module_with_exported_element */); + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForMultipleExportAssignments = function (node, moduleElements) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + var seenExportAssignment = false; + var errorFound = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + if (child.kind() === 134 /* ExportAssignment */) { + if (seenExportAssignment) { + this.pushDiagnostic1(moduleElementFullStart, child, 68 /* Module_cannot_have_multiple_export_assignments */); + errorFound = true; + } + seenExportAssignment = true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return errorFound; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + var moduleElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, 66 /* Export_assignments_cannot_be_used_in_internal_modules */); + + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), 40 /* Implementations_are_not_allowed_in_ambient_contexts */); + this.skip(node); + return; + } + + if (this.checkFunctionOverloads(node, node.statements)) { + this.skip(node); + return; + } + + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), 39 /* Statements_are_not_allowed_in_ambient_contexts */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitBreakStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitContinueStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDebuggerStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDoStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitEmptyStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitExpressionStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForInStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIfStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitLabeledStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitReturnStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSwitchStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitThrowStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitTryStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWhileStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWithStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock && modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(parent, modifiers); + this.pushDiagnostic1(modifierFullStart, modifiers.childAt(0), 58 /* Modifiers_cannot_appear_here */); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.functionKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic1(currentElementFullStart, child, 9 /* _0_expected */, [TypeScript.SyntaxFacts.getText(kind)]); + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 79 /* SemicolonToken */)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitEqualsValueClause = function (node) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic1(this.position(), node.firstToken(), 42 /* Initializers_are_not_allowed_in_ambient_contexts */); + this.skip(node); + return; + } + + _super.prototype.visitEqualsValueClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + var savedCurrentConstructor = this.currentConstructor; + this.currentConstructor = node; + _super.prototype.visitConstructorDeclaration.call(this, node); + this.currentConstructor = savedCurrentConstructor; + }; + + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { + if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + _super.prototype.visitSourceUnit.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExternalModuleReference = function (node) { + if (node.moduleOrRequireKeyword.tokenKind === 66 /* ModuleKeyword */ && !this.syntaxTree.parseOptions().allowModuleKeywordInExternalModuleReference()) { + this.pushDiagnostic1(this.position(), node.moduleOrRequireKeyword, 65 /* _module_______is_deprecated__Use__require_______instead */); + this.skip(node); + return; + } + + _super.prototype.visitExternalModuleReference.call(this, node); + }; + return GrammarCheckerWalker; + })(TypeScript.PositionTrackingWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpanWalker = (function (_super) { + __extends(TextSpanWalker, _super); + function TextSpanWalker(textSpan) { + _super.call(this); + this.textSpan = textSpan; + this._position = 0; + } + TextSpanWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + TextSpanWalker.prototype.visitNode = function (node) { + var nodeSpan = new TypeScript.TextSpan(this.position(), node.fullWidth()); + + if (nodeSpan.intersectsWithTextSpan(this.textSpan)) { + node.accept(this); + } else { + this._position += node.fullWidth(); + } + }; + + TextSpanWalker.prototype.position = function () { + return this._position; + }; + return TextSpanWalker; + })(TypeScript.SyntaxWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + + var lo = 0; + var hi = map.length; + var mid; + + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + + if (code < map[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + + return false; + }; + + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + Unicode.unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + + Unicode.unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) !== 0; + } + TypeScript.hasFlag = hasFlag; + + function withoutFlag(val, flag) { + return val & ~flag; + } + TypeScript.withoutFlag = withoutFlag; + + (function (ASTFlags) { + ASTFlags[ASTFlags["None"] = 0] = "None"; + ASTFlags[ASTFlags["SingleLine"] = 1 << 1] = "SingleLine"; + ASTFlags[ASTFlags["OptionalName"] = 1 << 2] = "OptionalName"; + ASTFlags[ASTFlags["TypeReference"] = 1 << 3] = "TypeReference"; + ASTFlags[ASTFlags["EnumElement"] = 1 << 4] = "EnumElement"; + ASTFlags[ASTFlags["EnumMapElement"] = 1 << 5] = "EnumMapElement"; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + + (function (DeclFlags) { + DeclFlags[DeclFlags["None"] = 0] = "None"; + DeclFlags[DeclFlags["Exported"] = 1] = "Exported"; + DeclFlags[DeclFlags["Private"] = 1 << 1] = "Private"; + DeclFlags[DeclFlags["Public"] = 1 << 2] = "Public"; + DeclFlags[DeclFlags["Ambient"] = 1 << 3] = "Ambient"; + DeclFlags[DeclFlags["Static"] = 1 << 4] = "Static"; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + + (function (ModuleFlags) { + ModuleFlags[ModuleFlags["None"] = 0] = "None"; + ModuleFlags[ModuleFlags["Exported"] = 1] = "Exported"; + ModuleFlags[ModuleFlags["Private"] = 1 << 1] = "Private"; + ModuleFlags[ModuleFlags["Public"] = 1 << 2] = "Public"; + ModuleFlags[ModuleFlags["Ambient"] = 1 << 3] = "Ambient"; + ModuleFlags[ModuleFlags["Static"] = 1 << 4] = "Static"; + ModuleFlags[ModuleFlags["IsEnum"] = 1 << 7] = "IsEnum"; + ModuleFlags[ModuleFlags["IsWholeFile"] = 1 << 8] = "IsWholeFile"; + ModuleFlags[ModuleFlags["IsDynamic"] = 1 << 9] = "IsDynamic"; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + + (function (VariableFlags) { + VariableFlags[VariableFlags["None"] = 0] = "None"; + VariableFlags[VariableFlags["Exported"] = 1] = "Exported"; + VariableFlags[VariableFlags["Private"] = 1 << 1] = "Private"; + VariableFlags[VariableFlags["Public"] = 1 << 2] = "Public"; + VariableFlags[VariableFlags["Ambient"] = 1 << 3] = "Ambient"; + VariableFlags[VariableFlags["Static"] = 1 << 4] = "Static"; + VariableFlags[VariableFlags["Property"] = 1 << 8] = "Property"; + VariableFlags[VariableFlags["ClassProperty"] = 1 << 11] = "ClassProperty"; + VariableFlags[VariableFlags["Constant"] = 1 << 12] = "Constant"; + + VariableFlags[VariableFlags["EnumElement"] = 1 << 13] = "EnumElement"; + })(TypeScript.VariableFlags || (TypeScript.VariableFlags = {})); + var VariableFlags = TypeScript.VariableFlags; + + (function (FunctionFlags) { + FunctionFlags[FunctionFlags["None"] = 0] = "None"; + FunctionFlags[FunctionFlags["Exported"] = 1] = "Exported"; + FunctionFlags[FunctionFlags["Private"] = 1 << 1] = "Private"; + FunctionFlags[FunctionFlags["Public"] = 1 << 2] = "Public"; + FunctionFlags[FunctionFlags["Ambient"] = 1 << 3] = "Ambient"; + FunctionFlags[FunctionFlags["Static"] = 1 << 4] = "Static"; + FunctionFlags[FunctionFlags["GetAccessor"] = 1 << 5] = "GetAccessor"; + FunctionFlags[FunctionFlags["SetAccessor"] = 1 << 6] = "SetAccessor"; + FunctionFlags[FunctionFlags["Signature"] = 1 << 7] = "Signature"; + FunctionFlags[FunctionFlags["Method"] = 1 << 8] = "Method"; + FunctionFlags[FunctionFlags["CallMember"] = 1 << 9] = "CallMember"; + FunctionFlags[FunctionFlags["ConstructMember"] = 1 << 10] = "ConstructMember"; + FunctionFlags[FunctionFlags["IsFatArrowFunction"] = 1 << 11] = "IsFatArrowFunction"; + FunctionFlags[FunctionFlags["IndexerMember"] = 1 << 12] = "IndexerMember"; + FunctionFlags[FunctionFlags["IsFunctionExpression"] = 1 << 13] = "IsFunctionExpression"; + FunctionFlags[FunctionFlags["IsFunctionProperty"] = 1 << 14] = "IsFunctionProperty"; + })(TypeScript.FunctionFlags || (TypeScript.FunctionFlags = {})); + var FunctionFlags = TypeScript.FunctionFlags; + + function ToDeclFlags(fncOrVarOrModuleFlags) { + return fncOrVarOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["InconsistantPropertyAccesibility"] = 1 << 7] = "InconsistantPropertyAccesibility"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 0] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 1] = "Asynchronous"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (NodeType) { + NodeType[NodeType["None"] = 0] = "None"; + NodeType[NodeType["List"] = 1] = "List"; + NodeType[NodeType["Script"] = 2] = "Script"; + + NodeType[NodeType["TrueLiteral"] = 3] = "TrueLiteral"; + NodeType[NodeType["FalseLiteral"] = 4] = "FalseLiteral"; + NodeType[NodeType["StringLiteral"] = 5] = "StringLiteral"; + NodeType[NodeType["RegularExpressionLiteral"] = 6] = "RegularExpressionLiteral"; + NodeType[NodeType["NumericLiteral"] = 7] = "NumericLiteral"; + NodeType[NodeType["NullLiteral"] = 8] = "NullLiteral"; + + NodeType[NodeType["TypeParameter"] = 9] = "TypeParameter"; + NodeType[NodeType["GenericType"] = 10] = "GenericType"; + NodeType[NodeType["TypeRef"] = 11] = "TypeRef"; + + NodeType[NodeType["FunctionDeclaration"] = 12] = "FunctionDeclaration"; + NodeType[NodeType["ClassDeclaration"] = 13] = "ClassDeclaration"; + NodeType[NodeType["InterfaceDeclaration"] = 14] = "InterfaceDeclaration"; + NodeType[NodeType["ModuleDeclaration"] = 15] = "ModuleDeclaration"; + NodeType[NodeType["ImportDeclaration"] = 16] = "ImportDeclaration"; + NodeType[NodeType["VariableDeclarator"] = 17] = "VariableDeclarator"; + NodeType[NodeType["VariableDeclaration"] = 18] = "VariableDeclaration"; + NodeType[NodeType["Parameter"] = 19] = "Parameter"; + + NodeType[NodeType["Name"] = 20] = "Name"; + NodeType[NodeType["ArrayLiteralExpression"] = 21] = "ArrayLiteralExpression"; + NodeType[NodeType["ObjectLiteralExpression"] = 22] = "ObjectLiteralExpression"; + NodeType[NodeType["OmittedExpression"] = 23] = "OmittedExpression"; + NodeType[NodeType["VoidExpression"] = 24] = "VoidExpression"; + NodeType[NodeType["CommaExpression"] = 25] = "CommaExpression"; + NodeType[NodeType["PlusExpression"] = 26] = "PlusExpression"; + NodeType[NodeType["NegateExpression"] = 27] = "NegateExpression"; + NodeType[NodeType["DeleteExpression"] = 28] = "DeleteExpression"; + NodeType[NodeType["ThisExpression"] = 29] = "ThisExpression"; + NodeType[NodeType["SuperExpression"] = 30] = "SuperExpression"; + NodeType[NodeType["InExpression"] = 31] = "InExpression"; + NodeType[NodeType["MemberAccessExpression"] = 32] = "MemberAccessExpression"; + NodeType[NodeType["InstanceOfExpression"] = 33] = "InstanceOfExpression"; + NodeType[NodeType["TypeOfExpression"] = 34] = "TypeOfExpression"; + NodeType[NodeType["ElementAccessExpression"] = 35] = "ElementAccessExpression"; + NodeType[NodeType["InvocationExpression"] = 36] = "InvocationExpression"; + NodeType[NodeType["ObjectCreationExpression"] = 37] = "ObjectCreationExpression"; + NodeType[NodeType["AssignmentExpression"] = 38] = "AssignmentExpression"; + NodeType[NodeType["AddAssignmentExpression"] = 39] = "AddAssignmentExpression"; + NodeType[NodeType["SubtractAssignmentExpression"] = 40] = "SubtractAssignmentExpression"; + NodeType[NodeType["DivideAssignmentExpression"] = 41] = "DivideAssignmentExpression"; + NodeType[NodeType["MultiplyAssignmentExpression"] = 42] = "MultiplyAssignmentExpression"; + NodeType[NodeType["ModuloAssignmentExpression"] = 43] = "ModuloAssignmentExpression"; + NodeType[NodeType["AndAssignmentExpression"] = 44] = "AndAssignmentExpression"; + NodeType[NodeType["ExclusiveOrAssignmentExpression"] = 45] = "ExclusiveOrAssignmentExpression"; + NodeType[NodeType["OrAssignmentExpression"] = 46] = "OrAssignmentExpression"; + NodeType[NodeType["LeftShiftAssignmentExpression"] = 47] = "LeftShiftAssignmentExpression"; + NodeType[NodeType["SignedRightShiftAssignmentExpression"] = 48] = "SignedRightShiftAssignmentExpression"; + NodeType[NodeType["UnsignedRightShiftAssignmentExpression"] = 49] = "UnsignedRightShiftAssignmentExpression"; + NodeType[NodeType["ConditionalExpression"] = 50] = "ConditionalExpression"; + NodeType[NodeType["LogicalOrExpression"] = 51] = "LogicalOrExpression"; + NodeType[NodeType["LogicalAndExpression"] = 52] = "LogicalAndExpression"; + NodeType[NodeType["BitwiseOrExpression"] = 53] = "BitwiseOrExpression"; + NodeType[NodeType["BitwiseExclusiveOrExpression"] = 54] = "BitwiseExclusiveOrExpression"; + NodeType[NodeType["BitwiseAndExpression"] = 55] = "BitwiseAndExpression"; + NodeType[NodeType["EqualsWithTypeConversionExpression"] = 56] = "EqualsWithTypeConversionExpression"; + NodeType[NodeType["NotEqualsWithTypeConversionExpression"] = 57] = "NotEqualsWithTypeConversionExpression"; + NodeType[NodeType["EqualsExpression"] = 58] = "EqualsExpression"; + NodeType[NodeType["NotEqualsExpression"] = 59] = "NotEqualsExpression"; + NodeType[NodeType["LessThanExpression"] = 60] = "LessThanExpression"; + NodeType[NodeType["LessThanOrEqualExpression"] = 61] = "LessThanOrEqualExpression"; + NodeType[NodeType["GreaterThanExpression"] = 62] = "GreaterThanExpression"; + NodeType[NodeType["GreaterThanOrEqualExpression"] = 63] = "GreaterThanOrEqualExpression"; + NodeType[NodeType["AddExpression"] = 64] = "AddExpression"; + NodeType[NodeType["SubtractExpression"] = 65] = "SubtractExpression"; + NodeType[NodeType["MultiplyExpression"] = 66] = "MultiplyExpression"; + NodeType[NodeType["DivideExpression"] = 67] = "DivideExpression"; + NodeType[NodeType["ModuloExpression"] = 68] = "ModuloExpression"; + NodeType[NodeType["LeftShiftExpression"] = 69] = "LeftShiftExpression"; + NodeType[NodeType["SignedRightShiftExpression"] = 70] = "SignedRightShiftExpression"; + NodeType[NodeType["UnsignedRightShiftExpression"] = 71] = "UnsignedRightShiftExpression"; + NodeType[NodeType["BitwiseNotExpression"] = 72] = "BitwiseNotExpression"; + NodeType[NodeType["LogicalNotExpression"] = 73] = "LogicalNotExpression"; + NodeType[NodeType["PreIncrementExpression"] = 74] = "PreIncrementExpression"; + NodeType[NodeType["PreDecrementExpression"] = 75] = "PreDecrementExpression"; + NodeType[NodeType["PostIncrementExpression"] = 76] = "PostIncrementExpression"; + NodeType[NodeType["PostDecrementExpression"] = 77] = "PostDecrementExpression"; + NodeType[NodeType["CastExpression"] = 78] = "CastExpression"; + NodeType[NodeType["ParenthesizedExpression"] = 79] = "ParenthesizedExpression"; + NodeType[NodeType["Member"] = 80] = "Member"; + + NodeType[NodeType["Block"] = 81] = "Block"; + NodeType[NodeType["BreakStatement"] = 82] = "BreakStatement"; + NodeType[NodeType["ContinueStatement"] = 83] = "ContinueStatement"; + NodeType[NodeType["DebuggerStatement"] = 84] = "DebuggerStatement"; + NodeType[NodeType["DoStatement"] = 85] = "DoStatement"; + NodeType[NodeType["EmptyStatement"] = 86] = "EmptyStatement"; + NodeType[NodeType["ExportAssignment"] = 87] = "ExportAssignment"; + NodeType[NodeType["ExpressionStatement"] = 88] = "ExpressionStatement"; + NodeType[NodeType["ForInStatement"] = 89] = "ForInStatement"; + NodeType[NodeType["ForStatement"] = 90] = "ForStatement"; + NodeType[NodeType["IfStatement"] = 91] = "IfStatement"; + NodeType[NodeType["LabeledStatement"] = 92] = "LabeledStatement"; + NodeType[NodeType["ReturnStatement"] = 93] = "ReturnStatement"; + NodeType[NodeType["SwitchStatement"] = 94] = "SwitchStatement"; + NodeType[NodeType["ThrowStatement"] = 95] = "ThrowStatement"; + NodeType[NodeType["TryStatement"] = 96] = "TryStatement"; + NodeType[NodeType["VariableStatement"] = 97] = "VariableStatement"; + NodeType[NodeType["WhileStatement"] = 98] = "WhileStatement"; + NodeType[NodeType["WithStatement"] = 99] = "WithStatement"; + + NodeType[NodeType["CaseClause"] = 100] = "CaseClause"; + NodeType[NodeType["CatchClause"] = 101] = "CatchClause"; + + NodeType[NodeType["Comment"] = 102] = "Comment"; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + + for (var k in this.table) { + if (this.table[k] !== undefined) { + result.push(k); + } + } + + return result; + }; + + StringHashTable.prototype.add = function (key, data) { + if (this.table[key] !== undefined) { + return false; + } + + this.table[key] = data; + this.itemCount++; + return true; + }; + + StringHashTable.prototype.addOrUpdate = function (key, data) { + if (this.table[key] !== undefined) { + this.table[key] = data; + return false; + } + + this.table[key] = data; + this.itemCount++; + return true; + }; + + StringHashTable.prototype.map = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + + if (data !== undefined) { + fn(k, this.table[k], context); + } + } + }; + + StringHashTable.prototype.every = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + + if (data !== undefined) { + if (!fn(k, this.table[k], context)) { + return false; + } + } + } + + return true; + }; + + StringHashTable.prototype.some = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + + if (data !== undefined) { + if (fn(k, this.table[k], context)) { + return true; + } + } + } + + return false; + }; + + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + return data === undefined ? null : data; + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + + var IdentiferNameHashTable = (function (_super) { + __extends(IdentiferNameHashTable, _super); + function IdentiferNameHashTable() { + _super.apply(this, arguments); + } + IdentiferNameHashTable.prototype.getAllKeys = function () { + var result = []; + + _super.prototype.map.call(this, function (k, v, c) { + if (v !== undefined) { + result.push(k.substring(1)); + } + }, null); + + return result; + }; + + IdentiferNameHashTable.prototype.add = function (key, data) { + return _super.prototype.add.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.addOrUpdate = function (key, data) { + return _super.prototype.addOrUpdate.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.map = function (fn, context) { + return _super.prototype.map.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.every = function (fn, context) { + return _super.prototype.every.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.some = function (fn, context) { + return _super.prototype.some.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.lookup = function (key) { + return _super.prototype.lookup.call(this, "#" + key); + }; + return IdentiferNameHashTable; + })(StringHashTable); + TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; + this.limChar = -1; + this.trailingTriviaWidth = 0; + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + + TypeScript.astID = 0; + + function structuralEqualsNotIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, false); + } + TypeScript.structuralEqualsNotIncludingPosition = structuralEqualsNotIncludingPosition; + + function structuralEqualsIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, true); + } + TypeScript.structuralEqualsIncludingPosition = structuralEqualsIncludingPosition; + + function structuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.nodeType === ast2.nodeType && ast1.structuralEquals(ast2, includingPosition); + } + + function astArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? structuralEqualsIncludingPosition : structuralEqualsNotIncludingPosition); + } + + var AST = (function () { + function AST(nodeType) { + this.nodeType = nodeType; + this.minChar = -1; + this.limChar = -1; + this.trailingTriviaWidth = 0; + this._flags = 0 /* None */; + this.typeCheckPhase = -1; + this.astID = TypeScript.astID++; + this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.docComments = null; + } + AST.prototype.shouldEmit = function () { + return true; + }; + + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + + AST.prototype.getFlags = function () { + return this._flags; + }; + + AST.prototype.setFlags = function (flags) { + this._flags = flags; + }; + + AST.prototype.getLength = function () { + return this.limChar - this.minChar; + }; + + AST.prototype.getID = function () { + return this.astID; + }; + + AST.prototype.isDeclaration = function () { + return false; + }; + + AST.prototype.isStatement = function () { + return false; + }; + + AST.prototype.emit = function (emitter) { + emitter.emitComments(this, true); + emitter.recordSourceMappingStart(this); + this.emitWorker(emitter); + emitter.recordSourceMappingEnd(this); + emitter.emitComments(this, false); + }; + + AST.prototype.emitWorker = function (emitter) { + throw new Error("please implement in derived class"); + }; + + AST.prototype.getDocComments = function () { + if (!this.isDeclaration() || !this.preComments || this.preComments.length === 0) { + return []; + } + + if (!this.docComments) { + var preCommentsLength = this.preComments.length; + var docComments = []; + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (this.preComments[i].isDocComment()) { + var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; + if (prevDocComment === null || (this.preComments[i].limLine === prevDocComment.minLine || this.preComments[i].limLine + 1 === prevDocComment.minLine)) { + docComments.push(this.preComments[i]); + continue; + } + } + break; + } + + this.docComments = docComments.reverse(); + } + + return this.docComments; + }; + + AST.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.minChar !== ast.minChar || this.limChar !== ast.limChar) { + return false; + } + } + + return this._flags === ast._flags && astArrayStructuralEquals(this.preComments, ast.preComments, includingPosition) && astArrayStructuralEquals(this.postComments, ast.postComments, includingPosition); + }; + return AST; + })(); + TypeScript.AST = AST; + + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, 1 /* List */); + this.members = []; + } + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + + ASTList.prototype.emit = function (emitter) { + emitter.recordSourceMappingStart(this); + emitter.emitModuleElements(this); + emitter.recordSourceMappingEnd(this); + }; + + ASTList.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + return Expression; + })(AST); + TypeScript.Expression = Expression; + + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(actualText) { + _super.call(this, 20 /* Name */); + this.actualText = actualText; + this.setText(actualText); + } + Identifier.prototype.setText = function (actualText) { + this.actualText = actualText; + this.text = actualText; + }; + + Identifier.prototype.isMissing = function () { + return false; + }; + + Identifier.prototype.emit = function (emitter) { + emitter.emitName(this, true); + }; + + Identifier.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.text === ast.text && this.actualText === ast.actualText && this.isMissing() === ast.isMissing(); + }; + return Identifier; + })(Expression); + TypeScript.Identifier = Identifier; + + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + + MissingIdentifier.prototype.emit = function (emitter) { + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + + var LiteralExpression = (function (_super) { + __extends(LiteralExpression, _super); + function LiteralExpression(nodeType) { + _super.call(this, nodeType); + } + LiteralExpression.prototype.emitWorker = function (emitter) { + switch (this.nodeType) { + case 8 /* NullLiteral */: + emitter.writeToOutput("null"); + break; + case 4 /* FalseLiteral */: + emitter.writeToOutput("false"); + break; + case 3 /* TrueLiteral */: + emitter.writeToOutput("true"); + break; + default: + throw new Error("please implement in derived class"); + } + }; + + LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return LiteralExpression; + })(Expression); + TypeScript.LiteralExpression = LiteralExpression; + + var ThisExpression = (function (_super) { + __extends(ThisExpression, _super); + function ThisExpression() { + _super.call(this, 29 /* ThisExpression */); + } + ThisExpression.prototype.emitWorker = function (emitter) { + if (emitter.thisFunctionDeclaration && (TypeScript.hasFlag(emitter.thisFunctionDeclaration.getFunctionFlags(), 2048 /* IsFatArrowFunction */))) { + emitter.writeToOutput("_this"); + } else { + emitter.writeToOutput("this"); + } + }; + + ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return ThisExpression; + })(Expression); + TypeScript.ThisExpression = ThisExpression; + + var SuperExpression = (function (_super) { + __extends(SuperExpression, _super); + function SuperExpression() { + _super.call(this, 30 /* SuperExpression */); + } + SuperExpression.prototype.emitWorker = function (emitter) { + emitter.emitSuperReference(); + }; + + SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return SuperExpression; + })(Expression); + TypeScript.SuperExpression = SuperExpression; + + var ParenthesizedExpression = (function (_super) { + __extends(ParenthesizedExpression, _super); + function ParenthesizedExpression(expression) { + _super.call(this, 79 /* ParenthesizedExpression */); + this.expression = expression; + } + ParenthesizedExpression.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("("); + this.expression.emit(emitter); + emitter.writeToOutput(")"); + }; + + ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ParenthesizedExpression; + })(Expression); + TypeScript.ParenthesizedExpression = ParenthesizedExpression; + + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.castTerm = null; + } + UnaryExpression.prototype.emitWorker = function (emitter) { + switch (this.nodeType) { + case 76 /* PostIncrementExpression */: + this.operand.emit(emitter); + emitter.writeToOutput("++"); + break; + case 73 /* LogicalNotExpression */: + emitter.writeToOutput("!"); + this.operand.emit(emitter); + break; + case 77 /* PostDecrementExpression */: + this.operand.emit(emitter); + emitter.writeToOutput("--"); + break; + case 22 /* ObjectLiteralExpression */: + emitter.emitObjectLiteral(this); + break; + case 21 /* ArrayLiteralExpression */: + emitter.emitArrayLiteral(this); + break; + case 72 /* BitwiseNotExpression */: + emitter.writeToOutput("~"); + this.operand.emit(emitter); + break; + case 27 /* NegateExpression */: + emitter.writeToOutput("-"); + if (this.operand.nodeType === 27 /* NegateExpression */ || this.operand.nodeType === 75 /* PreDecrementExpression */) { + emitter.writeToOutput(" "); + } + this.operand.emit(emitter); + break; + case 26 /* PlusExpression */: + emitter.writeToOutput("+"); + if (this.operand.nodeType === 26 /* PlusExpression */ || this.operand.nodeType === 74 /* PreIncrementExpression */) { + emitter.writeToOutput(" "); + } + this.operand.emit(emitter); + break; + case 74 /* PreIncrementExpression */: + emitter.writeToOutput("++"); + this.operand.emit(emitter); + break; + case 75 /* PreDecrementExpression */: + emitter.writeToOutput("--"); + this.operand.emit(emitter); + break; + case 34 /* TypeOfExpression */: + emitter.writeToOutput("typeof "); + this.operand.emit(emitter); + break; + case 28 /* DeleteExpression */: + emitter.writeToOutput("delete "); + this.operand.emit(emitter); + break; + case 24 /* VoidExpression */: + emitter.writeToOutput("void "); + this.operand.emit(emitter); + break; + case 78 /* CastExpression */: + this.operand.emit(emitter); + break; + default: + throw new Error("please implement in derived class"); + } + }; + + UnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.castTerm, ast.castTerm, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, typeArguments, arguments) { + _super.call(this, nodeType); + this.target = target; + this.typeArguments = typeArguments; + this.arguments = arguments; + } + CallExpression.prototype.emitWorker = function (emitter) { + if (this.nodeType === 37 /* ObjectCreationExpression */) { + emitter.emitNew(this.target, this.arguments); + } else { + emitter.emitCall(this, this.target, this.arguments); + } + }; + + CallExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.target, ast.target, includingPosition) && structuralEquals(this.typeArguments, ast.typeArguments, includingPosition) && structuralEquals(this.arguments, ast.arguments, includingPosition); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.getTextForBinaryToken = function (nodeType) { + switch (nodeType) { + case 25 /* CommaExpression */: + return ","; + case 38 /* AssignmentExpression */: + return "="; + case 39 /* AddAssignmentExpression */: + return "+="; + case 40 /* SubtractAssignmentExpression */: + return "-="; + case 42 /* MultiplyAssignmentExpression */: + return "*="; + case 41 /* DivideAssignmentExpression */: + return "/="; + case 43 /* ModuloAssignmentExpression */: + return "%="; + case 44 /* AndAssignmentExpression */: + return "&="; + case 45 /* ExclusiveOrAssignmentExpression */: + return "^="; + case 46 /* OrAssignmentExpression */: + return "|="; + case 47 /* LeftShiftAssignmentExpression */: + return "<<="; + case 48 /* SignedRightShiftAssignmentExpression */: + return ">>="; + case 49 /* UnsignedRightShiftAssignmentExpression */: + return ">>>="; + case 51 /* LogicalOrExpression */: + return "||"; + case 52 /* LogicalAndExpression */: + return "&&"; + case 53 /* BitwiseOrExpression */: + return "|"; + case 54 /* BitwiseExclusiveOrExpression */: + return "^"; + case 55 /* BitwiseAndExpression */: + return "&"; + case 56 /* EqualsWithTypeConversionExpression */: + return "=="; + case 57 /* NotEqualsWithTypeConversionExpression */: + return "!="; + case 58 /* EqualsExpression */: + return "==="; + case 59 /* NotEqualsExpression */: + return "!=="; + case 60 /* LessThanExpression */: + return "<"; + case 62 /* GreaterThanExpression */: + return ">"; + case 61 /* LessThanOrEqualExpression */: + return "<="; + case 63 /* GreaterThanOrEqualExpression */: + return ">="; + case 33 /* InstanceOfExpression */: + return "instanceof"; + case 31 /* InExpression */: + return "in"; + case 69 /* LeftShiftExpression */: + return "<<"; + case 70 /* SignedRightShiftExpression */: + return ">>"; + case 71 /* UnsignedRightShiftExpression */: + return ">>>"; + case 66 /* MultiplyExpression */: + return "*"; + case 67 /* DivideExpression */: + return "/"; + case 68 /* ModuloExpression */: + return "%"; + case 64 /* AddExpression */: + return "+"; + case 65 /* SubtractExpression */: + return "-"; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + BinaryExpression.prototype.emitWorker = function (emitter) { + switch (this.nodeType) { + case 32 /* MemberAccessExpression */: + if (!emitter.tryEmitConstant(this)) { + this.operand1.emit(emitter); + emitter.writeToOutput("."); + emitter.emitName(this.operand2, false); + } + break; + case 35 /* ElementAccessExpression */: + emitter.emitIndex(this.operand1, this.operand2); + break; + + case 80 /* Member */: + if (this.operand2.nodeType === 12 /* FunctionDeclaration */ && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 32 /* GetAccessor */)) { + emitter.writeToOutput("get "); + } else { + emitter.writeToOutput("set "); + } + this.operand1.emit(emitter); + } else { + this.operand1.emit(emitter); + emitter.writeToOutputTrimmable(": "); + } + this.operand2.emit(emitter); + break; + case 25 /* CommaExpression */: + this.operand1.emit(emitter); + emitter.writeToOutput(", "); + this.operand2.emit(emitter); + break; + default: { + this.operand1.emit(emitter); + var binOp = BinaryExpression.getTextForBinaryToken(this.nodeType); + if (binOp === "instanceof") { + emitter.writeToOutput(" instanceof "); + } else if (binOp === "in") { + emitter.writeToOutput(" in "); + } else { + emitter.writeToOutputTrimmable(" " + binOp + " "); + } + this.operand2.emit(emitter); + } + } + }; + + BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand1, ast.operand1, includingPosition) && structuralEquals(this.operand2, ast.operand2, includingPosition); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, 50 /* ConditionalExpression */); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.emitWorker = function (emitter) { + this.operand1.emit(emitter); + emitter.writeToOutput(" ? "); + this.operand2.emit(emitter); + emitter.writeToOutput(" : "); + this.operand3.emit(emitter); + }; + + ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand1, ast.operand1, includingPosition) && structuralEquals(this.operand2, ast.operand2, includingPosition) && structuralEquals(this.operand3, ast.operand3, includingPosition); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, text) { + _super.call(this, 7 /* NumericLiteral */); + this.value = value; + this.text = text; + } + NumberLiteral.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.text); + }; + + NumberLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.value === ast.value && this.text === ast.text; + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(text) { + _super.call(this, 6 /* RegularExpressionLiteral */); + this.text = text; + } + RegexLiteral.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.text); + }; + + RegexLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.text === ast.text; + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(actualText, text) { + _super.call(this, 5 /* StringLiteral */); + this.actualText = actualText; + this.text = text; + } + StringLiteral.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.actualText); + }; + + StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.actualText === ast.actualText; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, 16 /* ImportDeclaration */); + this.id = id; + this.alias = alias; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + + ImportDeclaration.prototype.isDeclaration = function () { + return true; + }; + + ImportDeclaration.prototype.emit = function (emitter) { + if (emitter.importStatementShouldBeEmitted(this)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + + emitter.recordSourceMappingStart(this); + emitter.emitComments(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + var aliasAST = this.alias.nodeType === 11 /* TypeRef */ ? (this.alias).term : this.alias; + + emitter.emitJavascript(aliasAST, false); + emitter.writeToOutput(";"); + + emitter.emitComments(this, false); + emitter.recordSourceMappingEnd(this); + + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (typeof aliasAST === "undefined") { aliasAST = this.alias; } + if (aliasAST.nodeType === 20 /* Name */) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + + ImportDeclaration.prototype.firstAliasedModToString = function () { + if (this.alias.nodeType === 20 /* Name */) { + return (this.alias).actualText; + } else { + var dotExpr = this.alias; + var firstMod = (dotExpr.term).operand1; + return firstMod.actualText; + } + }; + + ImportDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.id, ast.id, includingPosition) && structuralEquals(this.alias, ast.alias, includingPosition); + }; + return ImportDeclaration; + })(AST); + TypeScript.ImportDeclaration = ImportDeclaration; + + var ExportAssignment = (function (_super) { + __extends(ExportAssignment, _super); + function ExportAssignment(id) { + _super.call(this, 87 /* ExportAssignment */); + this.id = id; + } + ExportAssignment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.id, ast.id, includingPosition); + }; + + ExportAssignment.prototype.emit = function (emitter) { + emitter.setExportAssignmentIdentifier(this.id.actualText); + }; + return ExportAssignment; + })(AST); + TypeScript.ExportAssignment = ExportAssignment; + + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType) { + _super.call(this, nodeType); + this.id = id; + this.init = null; + this.isImplicitlyInitialized = false; + this.typeExpr = null; + this._varFlags = 0 /* None */; + } + BoundDecl.prototype.isDeclaration = function () { + return true; + }; + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + + BoundDecl.prototype.getVarFlags = function () { + return this._varFlags; + }; + + BoundDecl.prototype.setVarFlags = function (flags) { + this._varFlags = flags; + }; + + BoundDecl.prototype.isProperty = function () { + return TypeScript.hasFlag(this.getVarFlags(), 256 /* Property */); + }; + + BoundDecl.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._varFlags === ast._varFlags && structuralEquals(this.init, ast.init, includingPosition) && structuralEquals(this.typeExpr, ast.typeExpr, includingPosition) && structuralEquals(this.id, ast.id, includingPosition); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + + var VariableDeclarator = (function (_super) { + __extends(VariableDeclarator, _super); + function VariableDeclarator(id) { + _super.call(this, id, 17 /* VariableDeclarator */); + } + VariableDeclarator.prototype.isExported = function () { + return TypeScript.hasFlag(this.getVarFlags(), 1 /* Exported */); + }; + + VariableDeclarator.prototype.isStatic = function () { + return TypeScript.hasFlag(this.getVarFlags(), 16 /* Static */); + }; + + VariableDeclarator.prototype.emit = function (emitter) { + emitter.emitVariableDeclarator(this); + }; + return VariableDeclarator; + })(BoundDecl); + TypeScript.VariableDeclarator = VariableDeclarator; + + var Parameter = (function (_super) { + __extends(Parameter, _super); + function Parameter(id) { + _super.call(this, id, 19 /* Parameter */); + this.isOptional = false; + } + Parameter.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + + Parameter.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(this.id.actualText); + }; + + Parameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.isOptional === ast.isOptional; + }; + return Parameter; + })(BoundDecl); + TypeScript.Parameter = Parameter; + + var FunctionDeclaration = (function (_super) { + __extends(FunctionDeclaration, _super); + function FunctionDeclaration(name, block, isConstructor, typeArguments, arguments, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.block = block; + this.isConstructor = isConstructor; + this.typeArguments = typeArguments; + this.arguments = arguments; + this.hint = null; + this._functionFlags = 0 /* None */; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.classDecl = null; + } + FunctionDeclaration.prototype.isDeclaration = function () { + return true; + }; + + FunctionDeclaration.prototype.getFunctionFlags = function () { + return this._functionFlags; + }; + + FunctionDeclaration.prototype.setFunctionFlags = function (flags) { + this._functionFlags = flags; + }; + + FunctionDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._functionFlags === ast._functionFlags && this.hint === ast.hint && this.variableArgList === ast.variableArgList && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && this.isConstructor === ast.isConstructor && structuralEquals(this.typeArguments, ast.typeArguments, includingPosition) && structuralEquals(this.arguments, ast.arguments, includingPosition); + }; + + FunctionDeclaration.prototype.shouldEmit = function () { + return !TypeScript.hasFlag(this.getFunctionFlags(), 128 /* Signature */) && !TypeScript.hasFlag(this.getFunctionFlags(), 8 /* Ambient */); + }; + + FunctionDeclaration.prototype.emit = function (emitter) { + emitter.emitFunction(this); + }; + + FunctionDeclaration.prototype.getNameText = function () { + if (this.name) { + return this.name.actualText; + } else { + return this.hint; + } + }; + + FunctionDeclaration.prototype.isMethod = function () { + return (this.getFunctionFlags() & 256 /* Method */) !== 0 /* None */; + }; + + FunctionDeclaration.prototype.isCallMember = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 512 /* CallMember */); + }; + FunctionDeclaration.prototype.isConstructMember = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 1024 /* ConstructMember */); + }; + FunctionDeclaration.prototype.isIndexerMember = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 4096 /* IndexerMember */); + }; + FunctionDeclaration.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FunctionDeclaration.prototype.isAccessor = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 32 /* GetAccessor */) || TypeScript.hasFlag(this.getFunctionFlags(), 64 /* SetAccessor */); + }; + FunctionDeclaration.prototype.isGetAccessor = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 32 /* GetAccessor */); + }; + FunctionDeclaration.prototype.isSetAccessor = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 64 /* SetAccessor */); + }; + FunctionDeclaration.prototype.isStatic = function () { + return TypeScript.hasFlag(this.getFunctionFlags(), 16 /* Static */); + }; + + FunctionDeclaration.prototype.isSignature = function () { + return (this.getFunctionFlags() & 128 /* Signature */) !== 0 /* None */; + }; + return FunctionDeclaration; + })(AST); + TypeScript.FunctionDeclaration = FunctionDeclaration; + + var Script = (function (_super) { + __extends(Script, _super); + function Script() { + _super.call(this, 2 /* Script */); + this.moduleElements = null; + this.referencedFiles = []; + this.requiresExtendsBlock = false; + this.isDeclareFile = false; + this.topLevelMod = null; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + } + Script.prototype.emit = function (emitter) { + if (!this.isDeclareFile) { + emitter.emitScriptElements(this, this.requiresExtendsBlock); + } + }; + + Script.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return Script; + })(AST); + TypeScript.Script = Script; + + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + } + NamedDeclaration.prototype.isDeclaration = function () { + return true; + }; + + NamedDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.members, ast.members, includingPosition); + }; + return NamedDeclaration; + })(AST); + TypeScript.NamedDeclaration = NamedDeclaration; + + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, endingToken) { + _super.call(this, 15 /* ModuleDeclaration */, name, members); + this.endingToken = endingToken; + this._moduleFlags = 0 /* None */; + this.amdDependencies = []; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.getModuleFlags = function () { + return this._moduleFlags; + }; + + ModuleDeclaration.prototype.setModuleFlags = function (flags) { + this._moduleFlags = flags; + }; + + ModuleDeclaration.prototype.structuralEquals = function (ast, includePosition) { + if (_super.prototype.structuralEquals.call(this, ast, includePosition)) { + return this._moduleFlags === ast._moduleFlags; + } + + return false; + }; + + ModuleDeclaration.prototype.isEnum = function () { + return TypeScript.hasFlag(this.getModuleFlags(), 128 /* IsEnum */); + }; + ModuleDeclaration.prototype.isWholeFile = function () { + return TypeScript.hasFlag(this.getModuleFlags(), 256 /* IsWholeFile */); + }; + + ModuleDeclaration.prototype.shouldEmit = function () { + if (TypeScript.hasFlag(this.getModuleFlags(), 8 /* Ambient */)) { + return false; + } + + if (TypeScript.hasFlag(this.getModuleFlags(), 128 /* IsEnum */)) { + return true; + } + + for (var i = 0, n = this.members.members.length; i < n; i++) { + var member = this.members.members[i]; + + if (member.nodeType === 15 /* ModuleDeclaration */) { + if ((member).shouldEmit()) { + return true; + } + } else if (member.nodeType !== 14 /* InterfaceDeclaration */) { + return true; + } + } + + return false; + }; + + ModuleDeclaration.prototype.emit = function (emitter) { + if (this.shouldEmit()) { + emitter.emitComments(this, true); + emitter.emitModule(this); + emitter.emitComments(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, typeParameters, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.typeParameters = typeParameters; + this.extendsList = extendsList; + this.implementsList = implementsList; + this._varFlags = 0 /* None */; + } + TypeDeclaration.prototype.getVarFlags = function () { + return this._varFlags; + }; + + TypeDeclaration.prototype.setVarFlags = function (flags) { + this._varFlags = flags; + }; + + TypeDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._varFlags === ast._varFlags && structuralEquals(this.typeParameters, ast.typeParameters, includingPosition) && structuralEquals(this.extendsList, ast.extendsList, includingPosition) && structuralEquals(this.implementsList, ast.implementsList, includingPosition); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, typeParameters, members, extendsList, implementsList) { + _super.call(this, 13 /* ClassDeclaration */, name, typeParameters, extendsList, implementsList, members); + this.constructorDecl = null; + this.endingToken = null; + } + ClassDeclaration.prototype.shouldEmit = function () { + return !TypeScript.hasFlag(this.getVarFlags(), 8 /* Ambient */); + }; + + ClassDeclaration.prototype.emit = function (emitter) { + emitter.emitClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, typeParameters, members, extendsList, implementsList) { + _super.call(this, 14 /* InterfaceDeclaration */, name, typeParameters, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.shouldEmit = function () { + return false; + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + } + Statement.prototype.isStatement = function () { + return true; + }; + + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + return Statement; + })(AST); + TypeScript.Statement = Statement; + + var ThrowStatement = (function (_super) { + __extends(ThrowStatement, _super); + function ThrowStatement(expression) { + _super.call(this, 95 /* ThrowStatement */); + this.expression = expression; + } + ThrowStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("throw "); + this.expression.emit(emitter); + emitter.writeToOutput(";"); + }; + + ThrowStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ThrowStatement; + })(Statement); + TypeScript.ThrowStatement = ThrowStatement; + + var ExpressionStatement = (function (_super) { + __extends(ExpressionStatement, _super); + function ExpressionStatement(expression) { + _super.call(this, 88 /* ExpressionStatement */); + this.expression = expression; + } + ExpressionStatement.prototype.emitWorker = function (emitter) { + this.expression.emit(emitter); + emitter.writeToOutput(";"); + }; + + ExpressionStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ExpressionStatement; + })(Statement); + TypeScript.ExpressionStatement = ExpressionStatement; + + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(identifier, statement) { + _super.call(this, 92 /* LabeledStatement */); + this.identifier = identifier; + this.statement = statement; + } + LabeledStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.identifier); + emitter.writeToOutput(this.identifier.actualText); + emitter.recordSourceMappingEnd(this.identifier); + emitter.writeLineToOutput(":"); + emitter.emitJavascript(this.statement, true); + }; + + LabeledStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + + var VariableDeclaration = (function (_super) { + __extends(VariableDeclaration, _super); + function VariableDeclaration(declarators) { + _super.call(this, 18 /* VariableDeclaration */); + this.declarators = declarators; + } + VariableDeclaration.prototype.emit = function (emitter) { + emitter.emitVariableDeclaration(this); + }; + + VariableDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declarators, ast.declarators, includingPosition); + }; + return VariableDeclaration; + })(AST); + TypeScript.VariableDeclaration = VariableDeclaration; + + var VariableStatement = (function (_super) { + __extends(VariableStatement, _super); + function VariableStatement(declaration) { + _super.call(this, 97 /* VariableStatement */); + this.declaration = declaration; + } + VariableStatement.prototype.shouldEmit = function () { + if (TypeScript.hasFlag(this.getFlags(), 32 /* EnumMapElement */)) { + return false; + } + + var varDecl = this.declaration.declarators.members[0]; + return !TypeScript.hasFlag(varDecl.getVarFlags(), 8 /* Ambient */) || varDecl.init !== null; + }; + + VariableStatement.prototype.emitWorker = function (emitter) { + if (TypeScript.hasFlag(this.getFlags(), 16 /* EnumElement */)) { + emitter.emitEnumElement(this.declaration.declarators.members[0]); + } else { + this.declaration.emit(emitter); + emitter.writeToOutput(";"); + } + }; + + VariableStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declaration, ast.declaration, includingPosition); + }; + return VariableStatement; + })(Statement); + TypeScript.VariableStatement = VariableStatement; + + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements) { + _super.call(this, 81 /* Block */); + this.statements = statements; + this.closeBraceSpan = null; + } + Block.prototype.emitWorker = function (emitter) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + if (this.statements) { + emitter.emitModuleElements(this.statements); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + }; + + Block.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return Block; + })(Statement); + TypeScript.Block = Block; + + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + + Jump.prototype.emitWorker = function (emitter) { + if (this.nodeType === 82 /* BreakStatement */) { + emitter.writeToOutput("break"); + } else { + emitter.writeToOutput("continue"); + } + if (this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.writeToOutput(";"); + }; + + Jump.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.target === ast.target; + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond, body) { + _super.call(this, 98 /* WhileStatement */); + this.cond = cond; + this.body = body; + } + WhileStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("while ("); + this.cond.emit(emitter); + emitter.writeToOutput(")"); + emitter.emitBlockOrStatement(this.body); + }; + + WhileStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + + var DoStatement = (function (_super) { + __extends(DoStatement, _super); + function DoStatement(body, cond) { + _super.call(this, 85 /* DoStatement */); + this.body = body; + this.cond = cond; + this.whileSpan = null; + } + DoStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("do"); + emitter.emitBlockOrStatement(this.body); + emitter.recordSourceMappingStart(this.whileSpan); + emitter.writeToOutput(" while"); + emitter.recordSourceMappingEnd(this.whileSpan); + emitter.writeToOutput('('); + this.cond.emit(emitter); + emitter.writeToOutput(")"); + emitter.writeToOutput(";"); + }; + + DoStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.body, ast.body, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition); + }; + return DoStatement; + })(Statement); + TypeScript.DoStatement = DoStatement; + + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond, thenBod, elseBod) { + _super.call(this, 91 /* IfStatement */); + this.cond = cond; + this.thenBod = thenBod; + this.elseBod = elseBod; + this.statement = new ASTSpan(); + } + IfStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if ("); + this.cond.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + + emitter.emitBlockOrStatement(this.thenBod); + + if (this.elseBod) { + if (this.elseBod.nodeType === 91 /* IfStatement */) { + emitter.writeToOutput(" else "); + this.elseBod.emit(emitter); + } else { + emitter.writeToOutput(" else"); + emitter.emitBlockOrStatement(this.elseBod); + } + } + }; + + IfStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition) && structuralEquals(this.thenBod, ast.thenBod, includingPosition) && structuralEquals(this.elseBod, ast.elseBod, includingPosition); + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement(returnExpression) { + _super.call(this, 93 /* ReturnStatement */); + this.returnExpression = returnExpression; + } + ReturnStatement.prototype.emitWorker = function (emitter) { + if (this.returnExpression) { + emitter.writeToOutput("return "); + this.returnExpression.emit(emitter); + emitter.writeToOutput(";"); + } else { + emitter.writeToOutput("return;"); + } + }; + + ReturnStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.returnExpression, ast.returnExpression, includingPosition); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj, body) { + _super.call(this, 89 /* ForInStatement */); + this.lval = lval; + this.obj = obj; + this.body = body; + this.statement = new ASTSpan(); + } + ForInStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for ("); + this.lval.emit(emitter); + emitter.writeToOutput(" in "); + this.obj.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitBlockOrStatement(this.body); + }; + + ForInStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.lval, ast.lval, includingPosition) && structuralEquals(this.obj, ast.obj, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init, cond, incr, body) { + _super.call(this, 90 /* ForStatement */); + this.init = init; + this.cond = cond; + this.incr = incr; + this.body = body; + } + ForStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("for ("); + if (this.init) { + if (this.init.nodeType !== 1 /* List */) { + this.init.emit(emitter); + } else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitCommaSeparatedList(this.init); + } + } + + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, false); + emitter.writeToOutput(")"); + emitter.emitBlockOrStatement(this.body); + }; + + ForStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.init, ast.init, includingPosition) && structuralEquals(this.cond, ast.cond, includingPosition) && structuralEquals(this.incr, ast.incr, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr, body) { + _super.call(this, 99 /* WithStatement */); + this.expr = expr; + this.body = body; + } + WithStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("with ("); + if (this.expr) { + this.expr.emit(emitter); + } + + emitter.writeToOutput(")"); + emitter.emitBlockOrStatement(this.body); + }; + + WithStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expr, ast.expr, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, 94 /* SwitchStatement */); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.emitWorker = function (emitter) { + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch ("); + this.val.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + + var lastEmittedNode = null; + for (var i = 0, n = this.caseList.members.length; i < n; i++) { + var caseExpr = this.caseList.members[i]; + + emitter.emitSpaceBetweenConstructs(lastEmittedNode, caseExpr); + emitter.emitJavascript(caseExpr, true); + + lastEmittedNode = caseExpr; + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + }; + + SwitchStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.caseList, ast.caseList, includingPosition) && structuralEquals(this.val, ast.val, includingPosition); + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + + var CaseClause = (function (_super) { + __extends(CaseClause, _super); + function CaseClause() { + _super.call(this, 100 /* CaseClause */); + this.expr = null; + this.colonSpan = new ASTSpan(); + } + CaseClause.prototype.emitWorker = function (emitter) { + if (this.expr) { + emitter.writeToOutput("case "); + this.expr.emit(emitter); + } else { + emitter.writeToOutput("default"); + } + emitter.recordSourceMappingStart(this.colonSpan); + emitter.writeToOutput(":"); + emitter.recordSourceMappingEnd(this.colonSpan); + + if (this.body.members.length === 1 && this.body.members[0].nodeType === 81 /* Block */) { + this.body.members[0].emit(emitter); + emitter.writeLineToOutput(""); + } else { + emitter.writeLineToOutput(""); + emitter.indenter.increaseIndent(); + this.body.emit(emitter); + emitter.indenter.decreaseIndent(); + } + }; + + CaseClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expr, ast.expr, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return CaseClause; + })(AST); + TypeScript.CaseClause = CaseClause; + + var TypeParameter = (function (_super) { + __extends(TypeParameter, _super); + function TypeParameter(name, constraint) { + _super.call(this, 9 /* TypeParameter */); + this.name = name; + this.constraint = constraint; + } + TypeParameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.constraint, ast.constraint, includingPosition); + }; + return TypeParameter; + })(AST); + TypeScript.TypeParameter = TypeParameter; + + var GenericType = (function (_super) { + __extends(GenericType, _super); + function GenericType(name, typeArguments) { + _super.call(this, 10 /* GenericType */); + this.name = name; + this.typeArguments = typeArguments; + } + GenericType.prototype.emit = function (emitter) { + this.name.emit(emitter); + }; + + GenericType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.typeArguments, ast.typeArguments, includingPosition); + }; + return GenericType; + })(AST); + TypeScript.GenericType = GenericType; + + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, 11 /* TypeRef */); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter) { + throw new Error("should not emit a type ref"); + }; + + TypeReference.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.term, ast.term, includingPosition) && this.arrayCount === ast.arrayCount; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + + var TryStatement = (function (_super) { + __extends(TryStatement, _super); + function TryStatement(tryBody, catchClause, finallyBody) { + _super.call(this, 96 /* TryStatement */); + this.tryBody = tryBody; + this.catchClause = catchClause; + this.finallyBody = finallyBody; + } + TryStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("try "); + this.tryBody.emit(emitter); + emitter.emitJavascript(this.catchClause, false); + + if (this.finallyBody) { + emitter.writeToOutput(" finally"); + this.finallyBody.emit(emitter); + } + }; + + TryStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.tryBody, ast.tryBody, includingPosition) && structuralEquals(this.catchClause, ast.catchClause, includingPosition) && structuralEquals(this.finallyBody, ast.finallyBody, includingPosition); + }; + return TryStatement; + })(Statement); + TypeScript.TryStatement = TryStatement; + + var CatchClause = (function (_super) { + __extends(CatchClause, _super); + function CatchClause(param, body) { + _super.call(this, 101 /* CatchClause */); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + } + CatchClause.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + this.param.id.emit(emitter); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + this.body.emit(emitter); + }; + + CatchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.param, ast.param, includingPosition) && structuralEquals(this.body, ast.body, includingPosition); + }; + return CatchClause; + })(AST); + TypeScript.CatchClause = CatchClause; + + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, 84 /* DebuggerStatement */); + } + DebuggerStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput("debugger;"); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; + + var OmittedExpression = (function (_super) { + __extends(OmittedExpression, _super); + function OmittedExpression() { + _super.call(this, 23 /* OmittedExpression */); + } + OmittedExpression.prototype.emitWorker = function (emitter) { + }; + + OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return OmittedExpression; + })(Expression); + TypeScript.OmittedExpression = OmittedExpression; + + var EmptyStatement = (function (_super) { + __extends(EmptyStatement, _super); + function EmptyStatement() { + _super.call(this, 86 /* EmptyStatement */); + } + EmptyStatement.prototype.emitWorker = function (emitter) { + emitter.writeToOutput(";"); + }; + + EmptyStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return EmptyStatement; + })(Statement); + TypeScript.EmptyStatement = EmptyStatement; + + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, 102 /* Comment */); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + this.docCommentText = null; + } + Comment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this.minLine === ast.minLine && this.content === ast.content && this.isBlockComment === ast.isBlockComment && this.endsLine === ast.endsLine; + }; + + Comment.prototype.getText = function () { + if (this.text === null) { + if (this.isBlockComment) { + this.text = this.content.split("\n"); + for (var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } else { + this.text = [(this.content.replace(/^\s+|\s+$/g, ''))]; + } + } + + return this.text; + }; + + Comment.prototype.isDocComment = function () { + if (this.isBlockComment) { + return this.content.charAt(2) === "*" && this.content.charAt(3) !== "/"; + } + + return false; + }; + + Comment.prototype.getDocCommentTextValue = function () { + if (this.docCommentText === null) { + this.docCommentText = Comment.cleanJSDocComment(this.content); + } + + return this.docCommentText; + }; + + Comment.consumeLeadingSpace = function (line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if (maxSpacesToRemove !== undefined) { + endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); + } + + for (; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if (charCode !== 32 /* space */ && charCode !== 9 /* tab */) { + return startIndex; + } + } + + if (endIndex !== line.length) { + return endIndex; + } + + return -1; + }; + + Comment.isSpaceChar = function (line, index) { + var length = line.length; + if (index < length) { + var charCode = line.charCodeAt(index); + + return charCode === 32 /* space */ || charCode === 9 /* tab */; + } + + return index === length; + }; + + Comment.cleanDocCommentLine = function (line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); + if (nonSpaceIndex !== -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if (jsDocStyleComment && line.charAt(nonSpaceIndex) === '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + + if (nonSpaceIndex !== -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + + return { + minChar: nonSpaceIndex, + limChar: line.charAt(line.length - 1) === "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + + return null; + }; + + Comment.cleanJSDocComment = function (content, spacesToRemove) { + var docCommentLines = []; + content = content.replace("/**", ""); + if (content.length >= 2 && content.charAt(content.length - 1) === "/" && content.charAt(content.length - 2) === "*") { + content = content.substring(0, content.length - 2); + } + var lines = content.split("\n"); + var inParamTag = false; + for (var l = 0; l < lines.length; l++) { + var line = lines[l]; + var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); + if (!cleanLinePos) { + continue; + } + + var docCommentText = ""; + var prevPos = cleanLinePos.minChar; + for (var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + + if (line.indexOf("param", i + 1) === i + 1 && Comment.isSpaceChar(line, i + 6)) { + if (!wasInParamtag) { + docCommentText += line.substring(prevPos, i); + } + + prevPos = i; + inParamTag = true; + } else if (wasInParamtag) { + prevPos = i; + inParamTag = false; + } + } + + if (!inParamTag) { + docCommentText += line.substring(prevPos, cleanLinePos.limChar); + } + + var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); + if (newCleanPos) { + if (spacesToRemove === undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + + return docCommentLines.join("\n"); + }; + + Comment.getDocCommentText = function (comments) { + var docCommentText = []; + for (var c = 0; c < comments.length; c++) { + var commentText = comments[c].getDocCommentTextValue(); + if (commentText !== "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + + Comment.getParameterDocCommentText = function (param, fncDocComments) { + if (fncDocComments.length === 0 || !fncDocComments[0].isBlockComment) { + return ""; + } + + for (var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].content; + for (var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if (!Comment.isSpaceChar(commentContents, j)) { + continue; + } + + j = Comment.consumeLeadingSpace(commentContents, j); + if (j === -1) { + break; + } + + if (commentContents.charCodeAt(j) === 123 /* openBrace */) { + j++; + + var charCode = 0; + for (var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + break; + } else { + continue; + } + } + + if (charCode === 64 /* at */) { + break; + } + } + + if (j === commentContents.length) { + break; + } + + if (charCode === 64 /* at */) { + continue; + } + + j = Comment.consumeLeadingSpace(commentContents, j + 1); + if (j === -1) { + break; + } + } + + if (param !== commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { + continue; + } + + j = Comment.consumeLeadingSpace(commentContents, j + param.length); + if (j === -1) { + return ""; + } + + var endOfParam = commentContents.indexOf("@", j); + var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); + + var paramSpacesToRemove = undefined; + var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; + if (paramLineIndex !== 0) { + if (paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) === "\r") { + paramLineIndex++; + } + } + var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); + if (startSpaceRemovalIndex !== j && commentContents.charAt(startSpaceRemovalIndex) === "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + + return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + + return ""; + }; + return Comment; + })(AST); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if (preAst === undefined) { + preAst = ast; + } + if (this.options.goChildren) { + this.childrenWalkers[ast.nodeType](ast, parent, this); + } else { + this.options.goChildren = true; + } + + if (this.post) { + var postAst = this.post(preAst, parent, this); + if (postAst === undefined) { + postAst = preAst; + } + return postAst; + } else { + return preAst; + } + }; + return AstWalker; + })(); + + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if (!options) { + options = new AstWalkOptions(); + } + + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[0 /* None */] = ChildrenWalkers.walkNone; + this.childrenWalkers[86 /* EmptyStatement */] = ChildrenWalkers.walkNone; + this.childrenWalkers[23 /* OmittedExpression */] = ChildrenWalkers.walkNone; + this.childrenWalkers[3 /* TrueLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[4 /* FalseLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[29 /* ThisExpression */] = ChildrenWalkers.walkNone; + this.childrenWalkers[30 /* SuperExpression */] = ChildrenWalkers.walkNone; + this.childrenWalkers[5 /* StringLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[6 /* RegularExpressionLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[8 /* NullLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[21 /* ArrayLiteralExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[22 /* ObjectLiteralExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[24 /* VoidExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[25 /* CommaExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[26 /* PlusExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[27 /* NegateExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[28 /* DeleteExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[31 /* InExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[32 /* MemberAccessExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[33 /* InstanceOfExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[34 /* TypeOfExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[7 /* NumericLiteral */] = ChildrenWalkers.walkNone; + this.childrenWalkers[20 /* Name */] = ChildrenWalkers.walkNone; + this.childrenWalkers[9 /* TypeParameter */] = ChildrenWalkers.walkTypeParameterChildren; + this.childrenWalkers[10 /* GenericType */] = ChildrenWalkers.walkGenericTypeChildren; + this.childrenWalkers[11 /* TypeRef */] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[35 /* ElementAccessExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[36 /* InvocationExpression */] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[37 /* ObjectCreationExpression */] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[38 /* AssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[39 /* AddAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[40 /* SubtractAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[41 /* DivideAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[42 /* MultiplyAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[43 /* ModuloAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[44 /* AndAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[45 /* ExclusiveOrAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[46 /* OrAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[47 /* LeftShiftAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[48 /* SignedRightShiftAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[49 /* UnsignedRightShiftAssignmentExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[50 /* ConditionalExpression */] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[51 /* LogicalOrExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[52 /* LogicalAndExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[53 /* BitwiseOrExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[54 /* BitwiseExclusiveOrExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[55 /* BitwiseAndExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[56 /* EqualsWithTypeConversionExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[57 /* NotEqualsWithTypeConversionExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[58 /* EqualsExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[59 /* NotEqualsExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[60 /* LessThanExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[61 /* LessThanOrEqualExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[62 /* GreaterThanExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[63 /* GreaterThanOrEqualExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[64 /* AddExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[65 /* SubtractExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[66 /* MultiplyExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[67 /* DivideExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[68 /* ModuloExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[69 /* LeftShiftExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[70 /* SignedRightShiftExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[71 /* UnsignedRightShiftExpression */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[72 /* BitwiseNotExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[73 /* LogicalNotExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[74 /* PreIncrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[75 /* PreDecrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[76 /* PostIncrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[77 /* PostDecrementExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[78 /* CastExpression */] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[79 /* ParenthesizedExpression */] = ChildrenWalkers.walkParenthesizedExpressionChildren; + this.childrenWalkers[12 /* FunctionDeclaration */] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[80 /* Member */] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[17 /* VariableDeclarator */] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[18 /* VariableDeclaration */] = ChildrenWalkers.walkVariableDeclarationChildren; + this.childrenWalkers[19 /* Parameter */] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[93 /* ReturnStatement */] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[82 /* BreakStatement */] = ChildrenWalkers.walkNone; + this.childrenWalkers[83 /* ContinueStatement */] = ChildrenWalkers.walkNone; + this.childrenWalkers[95 /* ThrowStatement */] = ChildrenWalkers.walkThrowStatementChildren; + this.childrenWalkers[90 /* ForStatement */] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[89 /* ForInStatement */] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[91 /* IfStatement */] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[98 /* WhileStatement */] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[85 /* DoStatement */] = ChildrenWalkers.walkDoStatementChildren; + this.childrenWalkers[81 /* Block */] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[100 /* CaseClause */] = ChildrenWalkers.walkCaseClauseChildren; + this.childrenWalkers[94 /* SwitchStatement */] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[96 /* TryStatement */] = ChildrenWalkers.walkTryStatementChildren; + this.childrenWalkers[101 /* CatchClause */] = ChildrenWalkers.walkCatchClauseChildren; + this.childrenWalkers[1 /* List */] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[2 /* Script */] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[13 /* ClassDeclaration */] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[14 /* InterfaceDeclaration */] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[15 /* ModuleDeclaration */] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[16 /* ImportDeclaration */] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[87 /* ExportAssignment */] = ChildrenWalkers.walkExportAssignmentChildren; + this.childrenWalkers[99 /* WithStatement */] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[88 /* ExpressionStatement */] = ChildrenWalkers.walkExpressionStatementChildren; + this.childrenWalkers[92 /* LabeledStatement */] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[97 /* VariableStatement */] = ChildrenWalkers.walkVariableStatementChildren; + this.childrenWalkers[102 /* Comment */] = ChildrenWalkers.walkNone; + this.childrenWalkers[84 /* DebuggerStatement */] = ChildrenWalkers.walkNone; + + for (var e in TypeScript.NodeType) { + if (TypeScript.NodeType.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.NodeType[e])) { + if (this.childrenWalkers[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + + var globalAstWalkerFactory; + + function getAstWalkerFactory() { + if (!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + + for (var i = 0; i < len; i++) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + + function walkThrowStatementChildren(preAst, parent, walker) { + if (preAst.expression) { + preAst.expression = walker.walk(preAst.expression, preAst); + } + } + ChildrenWalkers.walkThrowStatementChildren = walkThrowStatementChildren; + + function walkUnaryExpressionChildren(preAst, parent, walker) { + if (preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if (preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + + function walkParenthesizedExpressionChildren(preAst, parent, walker) { + if (preAst.expression) { + preAst.expression = walker.walk(preAst.expression, preAst); + } + } + ChildrenWalkers.walkParenthesizedExpressionChildren = walkParenthesizedExpressionChildren; + + function walkBinaryExpressionChildren(preAst, parent, walker) { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if (preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + + function walkTypeParameterChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + + if (preAst.constraint) { + preAst.constraint = walker.walk(preAst.constraint, preAst); + } + } + ChildrenWalkers.walkTypeParameterChildren = walkTypeParameterChildren; + + function walkGenericTypeChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + + if (preAst.typeArguments) { + preAst.typeArguments = walker.walk(preAst.typeArguments, preAst); + } + } + ChildrenWalkers.walkGenericTypeChildren = walkGenericTypeChildren; + + function walkTypeReferenceChildren(preAst, parent, walker) { + if (preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + + function walkCallExpressionChildren(preAst, parent, walker) { + preAst.target = walker.walk(preAst.target, preAst); + + if (preAst.typeArguments) { + preAst.typeArguments = walker.walk(preAst.typeArguments, preAst); + } + + if (preAst.arguments) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if (preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if (preAst.operand3) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + + function walkFuncDeclChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if (preAst.typeArguments) { + preAst.typeArguments = walker.walk(preAst.typeArguments, preAst); + } + if (preAst.arguments) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if (preAst.returnTypeAnnotation) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if (preAst.block) { + preAst.block = walker.walk(preAst.block, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + + function walkBoundDeclChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if (preAst.typeExpr) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + + function walkReturnStatementChildren(preAst, parent, walker) { + if (preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + + function walkForStatementChildren(preAst, parent, walker) { + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + + if (preAst.cond) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + + if (preAst.incr) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + preAst.obj = walker.walk(preAst.obj, preAst); + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.thenBod) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if (preAst.elseBod) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + + function walkDoStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoStatementChildren = walkDoStatementChildren; + + function walkBlockChildren(preAst, parent, walker) { + if (preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + + function walkVariableDeclarationChildren(preAst, parent, walker) { + if (preAst.declarators) { + preAst.declarators = walker.walk(preAst.declarators, preAst); + } + } + ChildrenWalkers.walkVariableDeclarationChildren = walkVariableDeclarationChildren; + + function walkCaseClauseChildren(preAst, parent, walker) { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseClauseChildren = walkCaseClauseChildren; + + function walkSwitchStatementChildren(preAst, parent, walker) { + if (preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + + if (preAst.caseList) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + + function walkTryStatementChildren(preAst, parent, walker) { + if (preAst.tryBody) { + preAst.tryBody = walker.walk(preAst.tryBody, preAst); + } + if (preAst.catchClause) { + preAst.catchClause = walker.walk(preAst.catchClause, preAst); + } + if (preAst.finallyBody) { + preAst.finallyBody = walker.walk(preAst.finallyBody, preAst); + } + } + ChildrenWalkers.walkTryStatementChildren = walkTryStatementChildren; + + function walkCatchClauseChildren(preAst, parent, walker) { + if (preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchClauseChildren = walkCatchClauseChildren; + + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if (preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + + if (preAst.typeParameters) { + preAst.typeParameters = walker.walk(preAst.typeParameters, preAst); + } + + if (preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + + if (preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + + function walkScriptChildren(preAst, parent, walker) { + if (preAst.moduleElements) { + preAst.moduleElements = walker.walk(preAst.moduleElements, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + + if (preAst.typeParameters) { + preAst.typeParameters = walker.walk(preAst.typeParameters, preAst); + } + + if (preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + + if (preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + + function walkImportDeclChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + + function walkExportAssignmentChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + } + ChildrenWalkers.walkExportAssignmentChildren = walkExportAssignmentChildren; + + function walkWithStatementChildren(preAst, parent, walker) { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + + function walkExpressionStatementChildren(preAst, parent, walker) { + preAst.expression = walker.walk(preAst.expression, preAst); + } + ChildrenWalkers.walkExpressionStatementChildren = walkExpressionStatementChildren; + + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.identifier = walker.walk(preAst.identifier, preAst); + preAst.statement = walker.walk(preAst.statement, preAst); + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + + function walkVariableStatementChildren(preAst, parent, walker) { + preAst.declaration = walker.walk(preAst.declaration, preAst); + } + ChildrenWalkers.walkVariableStatementChildren = walkVariableStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + + function AstWalkerCallback(pre, ast, callback) { + var nodeType = ast.nodeType; + var callbackString = TypeScript.NodeType[nodeType] + "Callback"; + if (callback[callbackString]) { + return callback[callbackString](pre, ast); + } + + if (callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + + return true; + } + })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); + var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function (items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + }; + + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + + while (this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + + AstPath.prototype.push = function (ast) { + while (this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + + AstPath.prototype.up = function () { + if (this.top <= -1) + throw new Error("Invalid call to 'up'"); + this.top--; + }; + + AstPath.prototype.down = function () { + if (this.top === this.ast.length - 1) + throw new Error("Invalid call to 'down'"); + this.top++; + }; + + AstPath.prototype.nodeType = function () { + if (this.ast() === null) + return 0 /* None */; + return this.ast().nodeType; + }; + + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + + AstPath.prototype.count = function () { + return this.top + 1; + }; + + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + + AstPath.prototype.isNameOfClass = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 13 /* ClassDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isNameOfInterface = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 14 /* InterfaceDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isNameOfArgument = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 19 /* Parameter */) && ((this.parent()).id === this.ast()); + }; + + AstPath.prototype.isNameOfVariable = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 17 /* VariableDeclarator */) && ((this.parent()).id === this.ast()); + }; + + AstPath.prototype.isNameOfModule = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 15 /* ModuleDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isNameOfFunction = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === 20 /* Name */) && (this.parent().nodeType === 12 /* FunctionDeclaration */) && ((this.parent()).name === this.ast()); + }; + + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === 12 /* FunctionDeclaration */ && (this.asts[this.top - 1]).block === this.asts[this.top - 0]; + }; + + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === 1 /* List */ && this.asts[this.top - 1].nodeType === 12 /* FunctionDeclaration */ && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + + AstPath.prototype.isTargetOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === 36 /* InvocationExpression */ && (this.asts[this.top - 1]).target === this.asts[this.top]; + }; + + AstPath.prototype.isTargetOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === 37 /* ObjectCreationExpression */ && (this.asts[this.top - 1]).target === this.asts[this.top]; + }; + + AstPath.prototype.isInClassImplementsList = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.parent().nodeType === 13 /* ClassDeclaration */) && (this.isMemberOfList((this.parent()).implementsList, this.ast())); + }; + + AstPath.prototype.isInInterfaceExtendsList = function () { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.parent().nodeType === 14 /* InterfaceDeclaration */) && (this.isMemberOfList((this.parent()).extendsList, this.ast())); + }; + + AstPath.prototype.isMemberOfMemberAccessExpression = function () { + if (this.count() > 1 && this.parent().nodeType === 32 /* MemberAccessExpression */ && (this.parent()).operand2 === this.asts[this.top]) { + return true; + } + + return false; + }; + + AstPath.prototype.isCallExpression = function () { + return this.count() >= 1 && (this.asts[this.top - 0].nodeType === 36 /* InvocationExpression */ || this.asts[this.top - 0].nodeType === 37 /* ObjectCreationExpression */); + }; + + AstPath.prototype.isCallExpressionTarget = function () { + if (this.count() < 2) { + return false; + } + + var current = this.top; + + var nodeType = this.asts[current].nodeType; + if (nodeType === 29 /* ThisExpression */ || nodeType === 30 /* SuperExpression */ || nodeType === 20 /* Name */) { + current--; + } + + while (current >= 0) { + if (current < this.top && this.asts[current].nodeType === 32 /* MemberAccessExpression */ && (this.asts[current]).operand2 === this.asts[current + 1]) { + current--; + continue; + } + + break; + } + + return current < this.top && (this.asts[current].nodeType === 36 /* InvocationExpression */ || this.asts[current].nodeType === 37 /* ObjectCreationExpression */) && this.asts[current + 1] === (this.asts[current]).target; + }; + + AstPath.prototype.isDeclaration = function () { + if (this.ast() !== null) { + switch (this.ast().nodeType) { + case 13 /* ClassDeclaration */: + case 14 /* InterfaceDeclaration */: + case 15 /* ModuleDeclaration */: + case 12 /* FunctionDeclaration */: + case 17 /* VariableDeclarator */: + return true; + } + } + + return false; + }; + + AstPath.prototype.isMemberOfList = function (list, item) { + if (list && list.members) { + for (var i = 0, n = list.members.length; i < n; i++) { + if (list.members[i] === item) { + return true; + } + } + } + + return false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + + function isValidAstNode(ast) { + if (ast === null) + return false; + + if (ast.minChar === -1 || ast.limChar === -1) + return false; + + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + + (function (GetAstPathOptions) { + GetAstPathOptions[GetAstPathOptions["Default"] = 0] = "Default"; + GetAstPathOptions[GetAstPathOptions["EdgeInclusive"] = 1] = "EdgeInclusive"; + + GetAstPathOptions[GetAstPathOptions["DontPruneSearchBasedOnPosition"] = 1 << 1] = "DontPruneSearchBasedOnPosition"; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + + function getAstPathToPosition(script, pos, useTrailingTriviaAsLimChar, options) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof options === "undefined") { options = 0 /* Default */; } + var lookInComments = function (comments) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar + (useTrailingTriviaAsLimChar ? comments[i].trailingTriviaWidth : 0); + if (!comments[i].isBlockComment) { + limChar++; + } + if (pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + + var pre = function (cur, parent, walker) { + if (isValidAstNode(cur)) { + var inclusive = TypeScript.hasFlag(options, 1 /* EdgeInclusive */) || cur.nodeType === 20 /* Name */ || cur.nodeType === 32 /* MemberAccessExpression */ || cur.nodeType === 11 /* TypeRef */ || pos === script.limChar + script.trailingTriviaWidth; + + var minChar = cur.minChar; + var limChar = cur.limChar + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + var previous = ctx.path.ast(); + if (previous === null || (cur.minChar >= previous.minChar && (cur.limChar + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth : 0)) <= (previous.limChar + (useTrailingTriviaAsLimChar ? previous.trailingTriviaWidth : 0)))) { + ctx.path.push(cur); + } else { + } + } + + if (pos < limChar) { + lookInComments(cur.preComments); + } + if (pos >= minChar) { + lookInComments(cur.postComments); + } + + if (!TypeScript.hasFlag(options, 2 /* DontPruneSearchBasedOnPosition */)) { + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { + } + Base64Format.encode = function (inValue) { + if (inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + + Base64Format.decodeChar = function (inChar) { + if (inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + return Base64Format; + })(); + + var Base64VLQFormat = (function () { + function Base64VLQFormat() { + } + Base64VLQFormat.encode = function (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 + Base64Format.encode(currentDigit); + } while(inValue > 0); + + return encodedStr; + }; + + Base64VLQFormat.decode = function (inString) { + var result = 0; + var negative = false; + + var shift = 0; + for (var i = 0; i < inString.length; i++) { + var byte = Base64Format.decodeChar(inString[i]); + if (i === 0) { + if ((byte & 1) === 1) { + negative = true; + } + result = (byte >> 1) & 15; + } else { + result = result | ((byte & 31) << shift); + } + + shift += (i === 0) ? 4 : 5; + + if ((byte & 32) === 32) { + } else { + return { value: negative ? -(result) : result, rest: inString.substr(i + 1) }; + } + } + + throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceMapPosition = (function () { + function SourceMapPosition() { + } + return SourceMapPosition; + })(); + TypeScript.SourceMapPosition = SourceMapPosition; + + var SourceMapping = (function () { + function SourceMapping() { + this.start = new SourceMapPosition(); + this.end = new SourceMapPosition(); + this.nameIndex = -1; + this.childMappings = []; + } + return SourceMapping; + })(); + TypeScript.SourceMapping = SourceMapping; + + var SourceMapper = (function () { + function SourceMapper(tsFileName, jsFileName, sourceMapFileName, jsFile, sourceMapOut, emitFullPathOfSourceMap) { + this.sourceMapFileName = sourceMapFileName; + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.sourceMappings = []; + this.currentMappings = []; + this.names = []; + this.currentNameIndex = []; + this.currentMappings.push(this.sourceMappings); + + jsFileName = TypeScript.switchToForwardSlashes(jsFileName); + this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); + + var removalIndex = jsFileName.lastIndexOf(this.jsFileName); + var fixedPath = jsFileName.substring(0, removalIndex); + + if (emitFullPathOfSourceMap) { + if (jsFileName.indexOf("://") === -1) { + jsFileName = "file:///" + jsFileName; + } + this.jsFileName = jsFileName; + } + + this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); + } + SourceMapper.emitSourceMapping = function (allSourceMappers) { + var sourceMapper = allSourceMappers[0]; + sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); + + var sourceMapOut = sourceMapper.sourceMapOut; + var mappingsString = ""; + var tsFiles = []; + + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var namesList = []; + var namesCount = 0; + var emitComma = false; + + var recordedPosition = null; + for (var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { + sourceMapper = allSourceMappers[sourceMapperIndex]; + + var currentSourceIndex = tsFiles.length; + tsFiles.push(sourceMapper.tsFileName); + + if (sourceMapper.names.length > 0) { + namesList.push.apply(namesList, sourceMapper.names); + } + + var recordSourceMapping = function (mappedPosition, nameIndex) { + if (recordedPosition !== null && recordedPosition.emittedColumn === mappedPosition.emittedColumn && recordedPosition.emittedLine === mappedPosition.emittedLine) { + return; + } + + if (prevEmittedLine !== mappedPosition.emittedLine) { + while (prevEmittedLine < mappedPosition.emittedLine) { + prevEmittedColumn = 0; + mappingsString = mappingsString + ";"; + prevEmittedLine++; + } + emitComma = false; + } else if (emitComma) { + mappingsString = mappingsString + ","; + } + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); + prevSourceIndex = currentSourceIndex; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); + prevSourceLine = mappedPosition.sourceLine - 1; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); + prevSourceColumn = mappedPosition.sourceColumn; + + if (nameIndex >= 0) { + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); + prevNameIndex = namesCount + nameIndex; + } + + emitComma = true; + recordedPosition = mappedPosition; + }; + + var recordSourceMappingSiblings = function (sourceMappings) { + for (var i = 0; i < sourceMappings.length; i++) { + var sourceMapping = sourceMappings[i]; + recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); + recordSourceMappingSiblings(sourceMapping.childMappings); + recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); + } + }; + + recordSourceMappingSiblings(sourceMapper.sourceMappings); + namesCount = namesCount + sourceMapper.names.length; + } + + sourceMapOut.Write(JSON.stringify({ + version: 3, + file: sourceMapper.jsFileName, + sources: tsFiles, + names: namesList, + mappings: mappingsString + })); + + sourceMapOut.Close(); + }; + SourceMapper.MapFileExtension = ".map"; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer[EmitContainer["Prog"] = 0] = "Prog"; + EmitContainer[EmitContainer["Module"] = 1] = "Module"; + EmitContainer[EmitContainer["DynamicModule"] = 2] = "DynamicModule"; + EmitContainer[EmitContainer["Class"] = 3] = "Class"; + EmitContainer[EmitContainer["Constructor"] = 4] = "Constructor"; + EmitContainer[EmitContainer["Function"] = 5] = "Function"; + EmitContainer[EmitContainer["Args"] = 6] = "Args"; + EmitContainer[EmitContainer["Interface"] = 7] = "Interface"; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.container = 0 /* Prog */; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + + var EmitOptions = (function () { + function EmitOptions(compilationSettings) { + this.compilationSettings = compilationSettings; + this.ioHost = null; + this.outputMany = true; + this.commonDirectoryPath = ""; + } + EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { + if (this.outputMany) { + var updatedFileName = fileName; + if (this.compilationSettings.outputOption !== "") { + updatedFileName = fileName.replace(this.commonDirectoryPath, ""); + updatedFileName = this.compilationSettings.outputOption + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(this.compilationSettings.outputOption, true); + } + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + Indenter.prototype.increaseIndent = function () { + this.indentAmt += Indenter.indentStep; + }; + + Indenter.prototype.decreaseIndent = function () { + this.indentAmt -= Indenter.indentStep; + }; + + Indenter.prototype.getIndent = function () { + var indentString = Indenter.indentStrings[this.indentAmt]; + if (indentString === undefined) { + indentString = ""; + for (var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { + indentString += Indenter.indentStepString; + } + Indenter.indentStrings[this.indentAmt] = indentString; + } + return indentString; + }; + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + + var Emitter = (function () { + function Emitter(emittingFileName, outfile, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.thisFunctionDeclaration = null; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.modAliasId = null; + this.firstModAlias = null; + this.allSourceMappers = []; + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.varListCountStack = [0]; + this.pullTypeChecker = null; + this.declStack = []; + this.resolvingContext = new TypeScript.PullTypeResolutionContext(); + this.exportAssignmentIdentifier = null; + this.document = null; + TypeScript.globalSemanticInfoChain = semanticInfoChain; + TypeScript.globalBinder.semanticInfoChain = semanticInfoChain; + this.pullTypeChecker = new TypeScript.PullTypeChecker(emitOptions.compilationSettings, semanticInfoChain); + } + Emitter.prototype.pushDecl = function (decl) { + if (decl) { + this.declStack[this.declStack.length] = decl; + } + }; + + Emitter.prototype.popDecl = function (decl) { + if (decl) { + this.declStack.length--; + } + }; + + Emitter.prototype.getEnclosingDecl = function () { + var declStackLen = this.declStack.length; + var enclosingDecl = declStackLen > 0 ? this.declStack[declStackLen - 1] : null; + return enclosingDecl; + }; + + Emitter.prototype.setTypeCheckerUnit = function (fileName) { + if (!this.pullTypeChecker.resolver) { + this.pullTypeChecker.setUnit(fileName); + return; + } + + this.pullTypeChecker.resolver.setUnitPath(fileName); + }; + + Emitter.prototype.setExportAssignmentIdentifier = function (id) { + this.exportAssignmentIdentifier = id; + }; + + Emitter.prototype.getExportAssignmentIdentifier = function () { + return this.exportAssignmentIdentifier; + }; + + Emitter.prototype.setDocument = function (document) { + this.document = document; + }; + + Emitter.prototype.importStatementShouldBeEmitted = function (importDeclAST, unitPath) { + if (!importDeclAST.isDynamicImport) { + return true; + } + + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST, this.document.fileName); + var pullSymbol = importDecl.getSymbol(); + return pullSymbol.getIsUsedAsValue(); + }; + + Emitter.prototype.setSourceMappings = function (mapper) { + this.allSourceMappers.push(mapper); + this.sourceMapper = mapper; + }; + + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + + this.emitState.column += s.length; + }; + + Emitter.prototype.writeToOutputTrimmable = function (s) { + if (this.emitOptions.compilationSettings.minWhitespace) { + s = s.replace(/[\s]*/g, ''); + } + this.writeToOutput(s); + }; + + Emitter.prototype.writeLineToOutput = function (s) { + if (this.emitOptions.compilationSettings.minWhitespace) { + this.writeToOutput(s); + var c = s.charCodeAt(s.length - 1); + if (!((c === 32 /* space */) || (c === 59 /* semicolon */) || (c === 91 /* openBracket */))) { + this.writeToOutput(' '); + } + } else { + this.outfile.WriteLine(s); + this.emitState.column = 0; + this.emitState.line++; + } + }; + + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.recordSourceMappingStart(ast); + this.writeToOutput(this.captureThisStmtString); + this.recordSourceMappingEnd(ast); + this.writeLineToOutput(""); + }; + + Emitter.prototype.setInVarBlock = function (count) { + this.varListCountStack[this.varListCountStack.length - 1] = count; + }; + + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + + Emitter.prototype.getIndentString = function () { + if (this.emitOptions.compilationSettings.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + + Emitter.prototype.emitCommentInPlace = function (comment) { + var text = comment.getText(); + var hadNewLine = false; + + if (comment.isBlockComment) { + if (this.emitState.column === 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + + if (text.length > 1 || comment.endsLine) { + for (var i = 1; i < text.length; i++) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput(text[i]); + } + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } else { + this.recordSourceMappingEnd(comment); + } + } else { + if (this.emitState.column === 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } + + if (hadNewLine) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + }; + + Emitter.prototype.emitComments = function (ast, pre) { + var comments = pre ? ast.preComments : ast.postComments; + + if (this.emitOptions.compilationSettings.emitComments && comments && comments.length !== 0) { + for (var i = 0; i < comments.length; i++) { + this.emitCommentInPlace(comments[i]); + } + } + }; + + Emitter.prototype.emitObjectLiteral = function (objectLiteral) { + var useNewLines = !TypeScript.hasFlag(objectLiteral.getFlags(), 2 /* SingleLine */); + + this.writeToOutput("{"); + var list = objectLiteral.operand; + if (list.members.length > 0) { + if (useNewLines) { + this.writeLineToOutput(""); + } else { + this.writeToOutput(" "); + } + + this.indenter.increaseIndent(); + this.emitCommaSeparatedList(list, useNewLines); + this.indenter.decreaseIndent(); + if (useNewLines) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + } + this.writeToOutput("}"); + }; + + Emitter.prototype.emitArrayLiteral = function (arrayLiteral) { + var useNewLines = !TypeScript.hasFlag(arrayLiteral.getFlags(), 2 /* SingleLine */); + + this.writeToOutput("["); + var list = arrayLiteral.operand; + if (list.members.length > 0) { + if (useNewLines) { + this.writeLineToOutput(""); + } + + this.indenter.increaseIndent(); + this.emitCommaSeparatedList(list, useNewLines); + this.indenter.decreaseIndent(); + if (useNewLines) { + this.emitIndent(); + } + } + this.writeToOutput("]"); + }; + + Emitter.prototype.emitNew = function (target, args) { + this.writeToOutput("new "); + if (target.nodeType === 11 /* TypeRef */) { + var typeRef = target; + if (typeRef.arrayCount) { + this.writeToOutput("Array()"); + } else { + typeRef.term.emit(this); + this.writeToOutput("()"); + } + } else { + target.emit(this); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitCommaSeparatedList(args); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + + Emitter.prototype.getVarDeclFromIdentifier = function (boundDeclInfo) { + TypeScript.CompilerDiagnostics.assert(boundDeclInfo.boundDecl && boundDeclInfo.boundDecl.init && boundDeclInfo.boundDecl.init.nodeType === 20 /* Name */, "The init expression of bound declaration when emitting as constant has to be indentifier"); + + var init = boundDeclInfo.boundDecl.init; + var ident = init; + + this.setTypeCheckerUnit(this.document.fileName); + var pullSymbol = this.resolvingContext.resolvingTypeReference ? this.pullTypeChecker.resolver.resolveTypeNameExpression(ident, boundDeclInfo.pullDecl.getParentDecl(), this.resolvingContext).symbol : this.pullTypeChecker.resolver.resolveNameExpression(ident, boundDeclInfo.pullDecl.getParentDecl(), this.resolvingContext).symbol; + if (pullSymbol) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + var ast = this.semanticInfoChain.getASTForDecl(pullDecl); + if (ast && ast.nodeType === 17 /* VariableDeclarator */) { + return { boundDecl: ast, pullDecl: pullDecl }; + } + } + } + + return null; + }; + + Emitter.prototype.getConstantValue = function (boundDeclInfo) { + var init = boundDeclInfo.boundDecl.init; + if (init) { + if (init.nodeType === 7 /* NumericLiteral */) { + var numLit = init; + return numLit.value; + } else if (init.nodeType === 69 /* LeftShiftExpression */) { + var binop = init; + if (binop.operand1.nodeType === 7 /* NumericLiteral */ && binop.operand2.nodeType === 7 /* NumericLiteral */) { + return (binop.operand1).value << (binop.operand2).value; + } + } else if (init.nodeType === 20 /* Name */) { + var varDeclInfo = this.getVarDeclFromIdentifier(boundDeclInfo); + if (varDeclInfo) { + return this.getConstantValue(varDeclInfo); + } + } + } + + return null; + }; + + Emitter.prototype.getConstantDecl = function (dotExpr) { + this.setTypeCheckerUnit(this.document.fileName); + var pullSymbol = this.pullTypeChecker.resolver.resolveDottedNameExpression(dotExpr, this.getEnclosingDecl(), this.resolvingContext).symbol; + if (pullSymbol && pullSymbol.hasFlag(524288 /* Constant */)) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + var ast = this.semanticInfoChain.getASTForDecl(pullDecl); + if (ast && ast.nodeType === 17 /* VariableDeclarator */) { + return { boundDecl: ast, pullDecl: pullDecl }; + } + } + } + + return null; + }; + + Emitter.prototype.tryEmitConstant = function (dotExpr) { + if (!this.emitOptions.compilationSettings.propagateConstants) { + return false; + } + var propertyName = dotExpr.operand2; + var boundDeclInfo = this.getConstantDecl(dotExpr); + if (boundDeclInfo) { + var value = this.getConstantValue(boundDeclInfo); + if (value !== null) { + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.actualText; + comment += " */"; + this.writeToOutput(comment); + return true; + } + } + + return false; + }; + + Emitter.prototype.emitCall = function (callNode, target, args) { + if (!this.emitSuperCall(callNode)) { + if (target.nodeType === 12 /* FunctionDeclaration */) { + this.writeToOutput("("); + } + if (callNode.target.nodeType === 30 /* SuperExpression */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, false); + } + if (target.nodeType === 12 /* FunctionDeclaration */) { + this.writeToOutput(")"); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if (callNode.target.nodeType === 30 /* SuperExpression */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("this"); + if (args && args.members.length) { + this.writeToOutput(", "); + } + } + this.emitCommaSeparatedList(args); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + + Emitter.prototype.emitInnerFunction = function (funcDecl, printName, includePreComments) { + if (typeof includePreComments === "undefined") { includePreComments = true; } + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl, this.document.fileName); + this.pushDecl(pullDecl); + + var shouldParenthesize = false; + + if (includePreComments) { + this.emitComments(funcDecl, true); + } + + if (shouldParenthesize) { + this.writeToOutput("("); + } + this.recordSourceMappingStart(funcDecl); + var accessorSymbol = funcDecl.isAccessor() ? TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain, this.document.fileName) : null; + var container = accessorSymbol ? accessorSymbol.getContainer() : null; + var containerKind = container ? container.getKind() : 0 /* None */; + if (!(funcDecl.isAccessor() && containerKind !== 8 /* Class */ && containerKind !== 33554432 /* ConstructorType */)) { + this.writeToOutput("function "); + } + + if (funcDecl.isConstructor) { + this.writeToOutput(this.thisClassNode.name.actualText); + } + + if (printName) { + var id = funcDecl.getNameText(); + if (id && !funcDecl.isAccessor()) { + if (funcDecl.name) { + this.recordSourceMappingStart(funcDecl.name); + } + this.writeToOutput(id); + if (funcDecl.name) { + this.recordSourceMappingEnd(funcDecl.name); + } + } + } + + this.writeToOutput("("); + var argsLen = 0; + if (funcDecl.arguments) { + this.emitComments(funcDecl.arguments, true); + + var tempContainer = this.setContainer(6 /* Args */); + argsLen = funcDecl.arguments.members.length; + var printLen = argsLen; + if (funcDecl.variableArgList) { + printLen--; + } + for (var i = 0; i < printLen; i++) { + var arg = funcDecl.arguments.members[i]; + arg.emit(this); + + if (i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + + this.emitComments(funcDecl.arguments, false); + } + this.writeLineToOutput(") {"); + + if (funcDecl.isConstructor) { + this.recordSourceMappingNameStart("constructor"); + } else if (funcDecl.isGetAccessor()) { + this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); + } else if (funcDecl.isSetAccessor()) { + this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); + } else { + this.recordSourceMappingNameStart(funcDecl.getNameText()); + } + this.indenter.increaseIndent(); + + this.emitDefaultValueAssignments(funcDecl); + this.emitRestParameterInitializer(funcDecl); + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + if (funcDecl.isConstructor) { + this.emitConstructorStatements(funcDecl); + } else { + this.emitModuleElements(funcDecl.block.statements); + } + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(funcDecl.block.closeBraceSpan); + this.writeToOutput("}"); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl.block.closeBraceSpan); + this.recordSourceMappingEnd(funcDecl); + + if (shouldParenthesize) { + this.writeToOutput(")"); + } + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitDefaultValueAssignments = function (funcDecl) { + var n = funcDecl.arguments.members.length; + if (funcDecl.variableArgList) { + n--; + } + + for (var i = 0; i < n; i++) { + var arg = funcDecl.arguments.members[i]; + if (arg.init) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.emitJavascript(arg.init, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + } + }; + + Emitter.prototype.emitRestParameterInitializer = function (funcDecl) { + if (funcDecl.variableArgList) { + var n = funcDecl.arguments.members.length; + var lastArg = funcDecl.arguments.members[n - 1]; + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.recordSourceMappingStart(lastArg.id); + this.writeToOutput(lastArg.id.actualText); + this.recordSourceMappingEnd(lastArg.id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var _i = 0;"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput(" "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i < (arguments.length - " + (n - 1) + ")"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput("; "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i++"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + + this.recordSourceMappingStart(lastArg); + this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (n - 1) + "];"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + }; + + Emitter.prototype.getImportDecls = function (fileName) { + var semanticInfo = this.semanticInfoChain.getUnit(this.document.fileName); + var result = []; + + var queue = semanticInfo.getTopLevelDecls(); + + while (queue.length > 0) { + var decl = queue.shift(); + + if (decl.getKind() & 256 /* TypeAlias */) { + var importStatementAST = semanticInfo.getASTForDecl(decl); + if (importStatementAST.alias.nodeType === 20 /* Name */) { + var text = (importStatementAST.alias).actualText; + if (TypeScript.isQuoted(text)) { + var symbol = decl.getSymbol(); + var typeSymbol = symbol && symbol.getType(); + if (typeSymbol && typeSymbol !== this.semanticInfoChain.anyTypeSymbol && !typeSymbol.isError()) { + result.push(decl); + } + } + } + } + + queue = queue.concat(decl.getChildDecls()); + } + + return result; + }; + + Emitter.prototype.getModuleImportAndDependencyList = function (moduleDecl) { + var importList = ""; + var dependencyList = ""; + + var semanticInfo = this.semanticInfoChain.getUnit(this.document.fileName); + var importDecls = this.getImportDecls(this.document.fileName); + + if (importDecls.length) { + for (var i = 0; i < importDecls.length; i++) { + var importStatementDecl = importDecls[i]; + var importStatementSymbol = importStatementDecl.getSymbol(); + var importStatementAST = semanticInfo.getASTForDecl(importStatementDecl); + + if (importStatementSymbol.getIsUsedAsValue()) { + if (i <= importDecls.length - 1) { + dependencyList += ", "; + importList += ", "; + } + + importList += "__" + importStatementDecl.getName() + "__"; + dependencyList += importStatementAST.firstAliasedModToString(); + } + } + } + + for (var i = 0; i < moduleDecl.amdDependencies.length; i++) { + dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; + } + + return { + importList: importList, + dependencyList: dependencyList + }; + }; + + Emitter.prototype.shouldCaptureThis = function (ast) { + if (ast.nodeType === 2 /* Script */) { + var scriptDecl = this.semanticInfoChain.getUnit(this.document.fileName).getTopLevelDecls()[0]; + return (scriptDecl.getFlags() & 262144 /* MustCaptureThis */) === 262144 /* MustCaptureThis */; + } + + var decl = this.semanticInfoChain.getDeclForAST(ast, this.document.fileName); + if (decl) { + return (decl.getFlags() & 262144 /* MustCaptureThis */) === 262144 /* MustCaptureThis */; + } + + return false; + }; + + Emitter.prototype.emitModule = function (moduleDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl, this.document.fileName); + this.pushDecl(pullDecl); + + var modName = moduleDecl.name.actualText; + if (TypeScript.isTSFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 3)); + } + + var isDynamicMod = TypeScript.hasFlag(moduleDecl.getModuleFlags(), 512 /* IsDynamic */); + var prevOutFile = this.outfile; + var prevOutFileName = this.emittingFileName; + var prevAllSourceMappers = this.allSourceMappers; + var prevSourceMapper = this.sourceMapper; + var prevColumn = this.emitState.column; + var prevLine = this.emitState.line; + var temp = this.setContainer(1 /* Module */); + var svModuleName = this.moduleName; + var isExported = TypeScript.hasFlag(moduleDecl.getModuleFlags(), 1 /* Exported */); + var isWholeFile = TypeScript.hasFlag(moduleDecl.getModuleFlags(), 256 /* IsWholeFile */); + this.moduleName = moduleDecl.name.actualText; + + if (isDynamicMod) { + this.setExportAssignmentIdentifier(null); + this.setContainer(2 /* DynamicModule */); + + this.recordSourceMappingStart(moduleDecl); + if (this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + + var importAndDependencyList = this.getModuleImportAndDependencyList(moduleDecl); + importList += importAndDependencyList.importList; + dependencyList += importAndDependencyList.dependencyList + "]"; + + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } + } else { + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(") {"); + } + + if (!isWholeFile) { + this.recordSourceMappingNameStart(this.moduleName); + } + + if (!isDynamicMod || this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + this.indenter.increaseIndent(); + } + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + this.emitModuleElements(moduleDecl.members); + if (!isDynamicMod || this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + this.indenter.decreaseIndent(); + } + this.emitIndent(); + + if (isDynamicMod) { + var exportAssignmentIdentifier = this.getExportAssignmentIdentifier(); + var exportAssignmentValueSymbol = (pullDecl.getSymbol()).getExportAssignedValueSymbol(); + + if (this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.getKind() & TypeScript.PullElementKind.SomeTypeReference)) { + this.indenter.increaseIndent(); + this.emitIndent(); + this.writeLineToOutput("return " + exportAssignmentIdentifier + ";"); + this.indenter.decreaseIndent(); + } + this.writeToOutput("});"); + } else if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.getKind() & TypeScript.PullElementKind.SomeTypeReference)) { + this.emitIndent(); + this.writeLineToOutput("module.exports = " + exportAssignmentIdentifier + ";"); + } + + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl); + + if (this.outfile !== prevOutFile) { + this.emitSourceMapsAndClose(); + if (prevSourceMapper !== null) { + this.allSourceMappers = prevAllSourceMappers; + this.sourceMapper = prevSourceMapper; + this.emitState.column = prevColumn; + this.emitState.line = prevLine; + } + this.outfile = prevOutFile; + this.emittingFileName = prevOutFileName; + } + } else { + var parentIsDynamic = temp === 2 /* DynamicModule */; + this.recordSourceMappingStart(moduleDecl.endingToken); + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + if (!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitEnumElement = function (varDecl) { + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(this.moduleName); + this.writeToOutput('["'); + this.writeToOutput(varDecl.id.text); + this.writeToOutput('"] = '); + varDecl.init.emit(this); + this.writeToOutput('] = "'); + this.writeToOutput(varDecl.id.text); + this.writeToOutput('";'); + }; + + Emitter.prototype.emitIndex = function (operand1, operand2) { + operand1.emit(this); + this.writeToOutput("["); + operand2.emit(this); + this.writeToOutput("]"); + }; + + Emitter.prototype.emitFunction = function (funcDecl) { + if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 128 /* Signature */)) { + return; + } + var temp; + var tempFnc = this.thisFunctionDeclaration; + this.thisFunctionDeclaration = funcDecl; + + if (funcDecl.isConstructor) { + temp = this.setContainer(4 /* Constructor */); + } else { + temp = this.setContainer(5 /* Function */); + } + + var funcName = funcDecl.getNameText(); + + if (((temp !== 4 /* Constructor */) || ((funcDecl.getFunctionFlags() & 256 /* Method */) === 0 /* None */))) { + this.recordSourceMappingStart(funcDecl); + this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing())); + } + this.setContainer(temp); + this.thisFunctionDeclaration = tempFnc; + + if (!TypeScript.hasFlag(funcDecl.getFunctionFlags(), 128 /* Signature */)) { + if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 16 /* Static */)) { + if (this.thisClassNode) { + this.writeLineToOutput(""); + if (funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } else if ((this.emitState.container === 1 /* Module */ || this.emitState.container === 2 /* DynamicModule */) && TypeScript.hasFlag(funcDecl.getFunctionFlags(), 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = this.emitState.container === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + if (varDecl.init) { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, false); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + }; + + Emitter.prototype.varListCount = function () { + return this.varListCountStack[this.varListCountStack.length - 1]; + }; + + Emitter.prototype.emitVarDeclVar = function () { + if (this.varListCount() >= 0) { + this.writeToOutput("var "); + this.setInVarBlock(-this.varListCount()); + } + return true; + }; + + Emitter.prototype.onEmitVar = function () { + if (this.varListCount() > 0) { + this.setInVarBlock(this.varListCount() - 1); + } else if (this.varListCount() < 0) { + this.setInVarBlock(this.varListCount() + 1); + } + }; + + Emitter.prototype.emitVariableDeclaration = function (declaration) { + var varDecl = declaration.declarators.members[0]; + + var symbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(varDecl, this.document.fileName); + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.getKind() : 0 /* None */; + var inClass = parentKind === 8 /* Class */; + + this.emitComments(declaration, true); + this.recordSourceMappingStart(declaration); + this.setInVarBlock(declaration.declarators.members.length); + + var isAmbientWithoutInit = TypeScript.hasFlag(varDecl.getVarFlags(), 8 /* Ambient */) && varDecl.init === null; + if (!isAmbientWithoutInit) { + for (var i = 0, n = declaration.declarators.members.length; i < n; i++) { + var declarator = declaration.declarators.members[i]; + + if (i > 0) { + if (inClass) { + this.writeToOutputTrimmable(";"); + } else { + this.writeToOutputTrimmable(", "); + } + } + + declarator.emit(this); + } + } + + this.recordSourceMappingEnd(declaration); + this.emitComments(declaration, false); + }; + + Emitter.prototype.emitVariableDeclarator = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl, this.document.fileName); + this.pushDecl(pullDecl); + if ((varDecl.getVarFlags() & 8 /* Ambient */) === 8 /* Ambient */) { + this.emitAmbientVarDecl(varDecl); + this.onEmitVar(); + } else { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + + var symbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(varDecl, this.document.fileName); + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.getKind() : 0 /* None */; + var associatedParentSymbol = parentSymbol ? parentSymbol.getAssociatedContainerType() : null; + var associatedParentSymbolKind = associatedParentSymbol ? associatedParentSymbol.getKind() : 0 /* None */; + if (parentKind === 8 /* Class */) { + if (this.emitState.container !== 6 /* Args */) { + if (varDecl.isStatic()) { + this.writeToOutput(parentSymbol.getName() + "."); + } else { + this.writeToOutput("this."); + } + } + } else if (parentKind === 64 /* Enum */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 64 /* Enum */) { + if (!varDecl.isExported() && !varDecl.isProperty()) { + this.emitVarDeclVar(); + } else { + if (this.emitState.container === 2 /* DynamicModule */) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + this.emitVarDeclVar(); + } + + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + var hasInitializer = (varDecl.init !== null); + if (hasInitializer) { + this.writeToOutputTrimmable(" = "); + + this.varListCountStack.push(0); + varDecl.init.emit(this); + this.varListCountStack.pop(); + } + + if (parentKind === 8 /* Class */) { + if (this.emitState.container !== 6 /* Args */) { + this.writeToOutput(";"); + } + } + + this.onEmitVar(); + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + this.popDecl(pullDecl); + }; + + Emitter.prototype.symbolIsUsedInItsEnclosingContainer = function (symbol, dynamic) { + if (typeof dynamic === "undefined") { dynamic = false; } + var symDecls = symbol.getDeclarations(); + + if (symDecls.length) { + var enclosingDecl = this.getEnclosingDecl(); + if (enclosingDecl) { + var parentDecl = symDecls[0].getParentDecl(); + if (parentDecl) { + var symbolDeclarationEnclosingContainer = parentDecl; + var enclosingContainer = enclosingDecl; + + while (symbolDeclarationEnclosingContainer) { + if (symbolDeclarationEnclosingContainer.getKind() === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + symbolDeclarationEnclosingContainer = symbolDeclarationEnclosingContainer.getParentDecl(); + } + + if (symbolDeclarationEnclosingContainer) { + while (enclosingContainer) { + if (enclosingContainer.getKind() === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + + enclosingContainer = enclosingContainer.getParentDecl(); + } + } + + if (symbolDeclarationEnclosingContainer && enclosingContainer) { + var same = symbolDeclarationEnclosingContainer === enclosingContainer; + + if (!same && symbol.hasFlag(32768 /* InitializedModule */)) { + same = symbolDeclarationEnclosingContainer === enclosingContainer.getParentDecl(); + } + + return same; + } + } + } + } + + return false; + }; + + Emitter.prototype.emitName = function (name, addThis) { + this.emitComments(name, true); + this.recordSourceMappingStart(name); + if (!name.isMissing()) { + this.setTypeCheckerUnit(this.document.fileName); + var pullSymbolAndDiagnostics = this.resolvingContext.resolvingTypeReference ? this.pullTypeChecker.resolver.resolveTypeNameExpression(name, this.getEnclosingDecl(), this.resolvingContext) : this.pullTypeChecker.resolver.resolveNameExpression(name, this.getEnclosingDecl(), this.resolvingContext); + var pullSymbol = pullSymbolAndDiagnostics.symbol; + var pullSymbolAlias = pullSymbolAndDiagnostics.symbolAlias; + var pullSymbolKind = pullSymbol.getKind(); + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() == this.getEnclosingDecl()); + if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { + var pullSymbolContainer = pullSymbol.getContainer(); + + if (pullSymbolContainer) { + var pullSymbolContainerKind = pullSymbolContainer.getKind(); + + if (pullSymbolContainerKind === 8 /* Class */) { + if (pullSymbol.hasFlag(16 /* Static */)) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } else if (pullSymbolKind === 4096 /* Property */) { + this.emitThis(); + this.writeToOutput("."); + } + } else if (pullSymbolContainerKind === 4 /* Container */ || pullSymbolContainerKind === 64 /* Enum */ || pullSymbolContainer.hasFlag(32768 /* InitializedModule */ | 131072 /* InitializedEnum */)) { + if (pullSymbolKind === 4096 /* Property */ || pullSymbolKind === 67108864 /* EnumMember */) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } else if (pullSymbol.hasFlag(1 /* Exported */) && pullSymbolKind === 1024 /* Variable */ && !pullSymbol.hasFlag(32768 /* InitializedModule */ | 131072 /* InitializedEnum */)) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } else if (pullSymbol.hasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(pullSymbol)) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } + } else if (pullSymbolContainerKind === 32 /* DynamicModule */ || pullSymbolContainer.hasFlag(65536 /* InitializedDynamicModule */)) { + if (pullSymbolKind === 4096 /* Property */) { + this.writeToOutput("exports."); + } else if (pullSymbol.hasFlag(1 /* Exported */) && !isLocalAlias && !pullSymbol.hasFlag(TypeScript.PullElementFlags.ImplicitVariable) && pullSymbol.getKind() !== 32768 /* ConstructorMethod */ && pullSymbol.getKind() !== 8 /* Class */ && pullSymbol.getKind() !== 64 /* Enum */) { + this.writeToOutput("exports."); + } + } else if (pullSymbolKind === 4096 /* Property */) { + if (pullSymbolContainer.getKind() === 8 /* Class */) { + this.emitThis(); + this.writeToOutput("."); + } + } else { + var pullDecls = pullSymbol.getDeclarations(); + var emitContainerName = true; + for (var i = 0; i < pullDecls.length; i++) { + if (pullDecls[i].getScriptName() === this.document.fileName) { + emitContainerName = false; + } + } + if (emitContainerName) { + this.writeToOutput(pullSymbolContainer.getName() + "."); + } + } + } + } + + if (pullSymbol && pullSymbolKind === 32 /* DynamicModule */) { + if (this.emitOptions.compilationSettings.moduleGenTarget === 1 /* Asynchronous */) { + this.writeToOutput("__" + this.modAliasId + "__"); + } else { + var moduleDecl = this.semanticInfoChain.getASTForSymbol(pullSymbol, this.document.fileName); + var modPath = name.actualText; + var isAmbient = pullSymbol.hasFlag(8 /* Ambient */); + modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); + modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); + this.writeToOutput("require(" + modPath + ")"); + } + } else { + this.writeToOutput(name.actualText); + } + } + + this.recordSourceMappingEnd(name); + this.emitComments(name, false); + }; + + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if (this.sourceMapper) { + var finalName = name; + if (!name) { + finalName = ""; + } else if (this.sourceMapper.currentNameIndex.length > 0) { + finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]] + "." + name; + } + + this.sourceMapper.names.push(finalName); + this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); + } + }; + + Emitter.prototype.recordSourceMappingNameEnd = function () { + if (this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + + Emitter.prototype.recordSourceMappingStart = function (ast) { + if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + var lineCol = { line: -1, character: -1 }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + + var lineMap = this.document.lineMap; + lineMap.fillLineAndCharacterFromPosition(ast.minChar, lineCol); + sourceMapping.start.sourceColumn = lineCol.character; + sourceMapping.start.sourceLine = lineCol.line + 1; + lineMap.fillLineAndCharacterFromPosition(ast.limChar, lineCol); + sourceMapping.end.sourceColumn = lineCol.character; + sourceMapping.end.sourceLine = lineCol.line + 1; + if (this.sourceMapper.currentNameIndex.length > 0) { + sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + } + + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + siblings.push(sourceMapping); + this.sourceMapper.currentMappings.push(sourceMapping.childMappings); + } + }; + + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + this.sourceMapper.currentMappings.pop(); + + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + var sourceMapping = siblings[siblings.length - 1]; + + sourceMapping.end.emittedColumn = this.emitState.column; + sourceMapping.end.emittedLine = this.emitState.line; + } + }; + + Emitter.prototype.emitSourceMapsAndClose = function () { + if (this.sourceMapper !== null) { + TypeScript.SourceMapper.emitSourceMapping(this.allSourceMappers); + } + + try { + this.outfile.Close(); + } catch (e) { + Emitter.throwEmitterError(e); + } + }; + + Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { + var constructorDecl = this.thisClassNode.constructorDecl; + + if (constructorDecl && constructorDecl.arguments) { + for (var i = 0, n = constructorDecl.arguments.members.length; i < n; i++) { + var arg = constructorDecl.arguments.members[i]; + if ((arg.getVarFlags() & 256 /* Property */) !== 0 /* None */) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + + for (var i = 0, n = this.thisClassNode.members.members.length; i < n; i++) { + if (this.thisClassNode.members.members[i].nodeType === 17 /* VariableDeclarator */) { + var varDecl = this.thisClassNode.members.members[i]; + if (!TypeScript.hasFlag(varDecl.getVarFlags(), 16 /* Static */) && varDecl.init) { + this.emitIndent(); + this.emitVariableDeclarator(varDecl); + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.emitCommaSeparatedList = function (list, startLine) { + if (typeof startLine === "undefined") { startLine = false; } + if (list === null) { + return; + } else { + for (var i = 0, n = list.members.length; i < n; i++) { + var emitNode = list.members[i]; + this.emitJavascript(emitNode, startLine); + + if (i < (n - 1)) { + this.writeToOutput(startLine ? "," : ", "); + } + + if (startLine) { + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.emitModuleElements = function (list) { + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = 0, n = list.members.length; i < n; i++) { + var node = list.members[i]; + + if (node.shouldEmit()) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.isDirectivePrologueElement = function (node) { + if (node.nodeType === 88 /* ExpressionStatement */) { + var exprStatement = node; + return exprStatement.expression.nodeType === 5 /* StringLiteral */; + } + + return false; + }; + + Emitter.prototype.emitSpaceBetweenConstructs = function (node1, node2) { + if (node1 === null || node2 === null) { + return; + } + + if (node1.minChar === -1 || node1.limChar === -1 || node2.minChar === -1 || node2.limChar === -1) { + return; + } + + var lineMap = this.document.lineMap; + var node1EndLine = lineMap.getLineNumberFromPosition(node1.limChar); + var node2StartLine = lineMap.getLineNumberFromPosition(node2.minChar); + + if ((node2StartLine - node1EndLine) > 1) { + this.writeLineToOutput(""); + } + }; + + Emitter.prototype.emitScriptElements = function (script, requiresExtendsBlock) { + var list = script.moduleElements; + this.emitComments(list, true); + + for (var i = 0, n = list.members.length; i < n; i++) { + var node = list.members[i]; + + if (!this.isDirectivePrologueElement(node)) { + break; + } + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + } + + this.emitPrologue(script, requiresExtendsBlock); + var lastEmittedNode = null; + + for (; i < n; i++) { + var node = list.members[i]; + + if (node.shouldEmit()) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitConstructorStatements = function (funcDecl) { + var list = funcDecl.block.statements; + + if (list === null) { + return; + } + + this.emitComments(list, true); + + var emitPropertyAssignmentsAfterSuperCall = this.thisClassNode.extendsList && this.thisClassNode.extendsList.members.length > 0; + var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; + var lastEmittedNode = null; + + for (var i = 0, n = list.members.length; i < n; i++) { + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + var node = list.members[i]; + + if (node.shouldEmit()) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitJavascript = function (ast, startLine) { + if (ast === null) { + return; + } + + if (startLine && this.indenter.indentAmt > 0) { + this.emitIndent(); + } + + ast.emit(this); + }; + + Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { + if (!TypeScript.hasFlag(funcDecl.getFunctionFlags(), 32 /* GetAccessor */)) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain, this.document.fileName); + if (accessorSymbol.getGetter()) { + return; + } + } + + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); + this.indenter.increaseIndent(); + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain, this.document.fileName); + if (accessors.getter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.getter); + this.writeToOutput("get: "); + this.emitInnerFunction(accessors.getter, false); + this.writeLineToOutput(","); + } + + if (accessors.setter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.setter); + this.writeToOutput("set: "); + this.emitInnerFunction(accessors.setter, false); + this.writeLineToOutput(","); + } + + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + }; + + Emitter.prototype.emitPrototypeMember = function (funcDecl, className) { + if (funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, className, true); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.emitComments(funcDecl, true); + this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); + this.emitInnerFunction(funcDecl, false, false); + this.writeLineToOutput(";"); + } + }; + + Emitter.prototype.emitClass = function (classDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(classDecl, this.document.fileName); + this.pushDecl(pullDecl); + + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var className = classDecl.name.actualText; + this.emitComments(classDecl, true); + var temp = this.setContainer(3 /* Class */); + + this.recordSourceMappingStart(classDecl); + this.writeToOutput("var " + className); + + var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; + var baseNameDecl = null; + var baseName = null; + var varDecl = null; + + if (hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + + if (hasBaseClass) { + baseNameDecl = classDecl.extendsList.members[0]; + baseName = baseNameDecl.nodeType === 36 /* InvocationExpression */ ? (baseNameDecl).target : baseNameDecl; + this.emitIndent(); + this.writeLineToOutput("__extends(" + className + ", _super);"); + } + + this.emitIndent(); + + var constrDecl = classDecl.constructorDecl; + + if (constrDecl) { + constrDecl.emit(this); + this.writeLineToOutput(""); + } else { + this.recordSourceMappingStart(classDecl); + + this.indenter.increaseIndent(); + this.writeLineToOutput("function " + classDecl.name.actualText + "() {"); + this.recordSourceMappingNameStart("constructor"); + if (hasBaseClass) { + this.emitIndent(); + this.writeLineToOutput("_super.apply(this, arguments);"); + } + + this.emitParameterPropertyAndMemberVariableAssignments(); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + + this.emitClassMembers(classDecl); + + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeLineToOutput("return " + className + ";"); + this.recordSourceMappingEnd(classDecl.endingToken); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl.endingToken); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if (hasBaseClass) { + this.resolvingContext.resolvingTypeReference = true; + this.emitJavascript(baseName, false); + this.resolvingContext.resolvingTypeReference = false; + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + + if ((temp === 1 /* Module */ || temp === 2 /* DynamicModule */) && TypeScript.hasFlag(classDecl.getVarFlags(), 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(classDecl); + this.writeToOutput(modName + "." + className + " = " + className + ";"); + this.recordSourceMappingEnd(classDecl); + } + + this.recordSourceMappingEnd(classDecl); + this.emitComments(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClassMembers = function (classDecl) { + var lastEmittedMember = null; + + for (var i = 0, n = classDecl.members.members.length; i < n; i++) { + var memberDecl = classDecl.members.members[i]; + + if (memberDecl.nodeType === 12 /* FunctionDeclaration */) { + var fn = memberDecl; + + if (TypeScript.hasFlag(fn.getFunctionFlags(), 256 /* Method */) && !fn.isSignature()) { + this.emitSpaceBetweenConstructs(lastEmittedMember, fn); + + if (!TypeScript.hasFlag(fn.getFunctionFlags(), 16 /* Static */)) { + this.emitPrototypeMember(fn, classDecl.name.actualText); + } else { + if (fn.isAccessor()) { + this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(fn); + this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); + this.emitInnerFunction(fn, false); + this.writeLineToOutput(";"); + } + } + + lastEmittedMember = fn; + } + } + } + + for (var i = 0, n = classDecl.members.members.length; i < n; i++) { + var memberDecl = classDecl.members.members[i]; + + if (memberDecl.nodeType === 17 /* VariableDeclarator */) { + var varDecl = memberDecl; + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 16 /* Static */) && varDecl.init) { + this.emitSpaceBetweenConstructs(lastEmittedMember, varDecl); + + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); + varDecl.init.emit(this); + + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(varDecl); + + lastEmittedMember = varDecl; + } + } + } + }; + + Emitter.prototype.emitPrologue = function (script, requiresExtendsBlock) { + if (!this.extendsPrologueEmitted) { + if (requiresExtendsBlock) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + + if (!this.globalThisCapturePrologueEmitted) { + if (this.shouldCaptureThis(script)) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + + Emitter.prototype.emitSuperReference = function () { + this.writeToOutput("_super.prototype"); + }; + + Emitter.prototype.emitSuperCall = function (callEx) { + if (callEx.target.nodeType === 32 /* MemberAccessExpression */) { + var dotNode = callEx.target; + if (dotNode.operand1.nodeType === 30 /* SuperExpression */) { + dotNode.emit(this); + this.writeToOutput(".call("); + this.emitThis(); + if (callEx.arguments && callEx.arguments.members.length > 0) { + this.writeToOutput(", "); + this.emitCommaSeparatedList(callEx.arguments); + } + this.writeToOutput(")"); + return true; + } + } + return false; + }; + + Emitter.prototype.emitThis = function () { + if (this.thisFunctionDeclaration && !this.thisFunctionDeclaration.isMethod() && (!this.thisFunctionDeclaration.isConstructor)) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + + Emitter.prototype.emitBlockOrStatement = function (node) { + if (node.nodeType === 81 /* Block */) { + node.emit(this); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascript(node, true); + this.indenter.decreaseIndent(); + } + }; + + Emitter.throwEmitterError = function (e) { + var error = new Error(e.message); + error.isEmitterError = true; + throw error; + }; + + Emitter.handleEmitterError = function (fileName, e) { + if ((e).isEmitterError === true) { + return [new TypeScript.Diagnostic(fileName, 0, 0, 275 /* Emit_Error__0 */, [e.message])]; + } + + throw e; + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (typeof markerBaseLength === "undefined") { markerBaseLength = 0; } + var result = memberName.prefix; + + if (memberName.isString()) { + result += (memberName).text; + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + + result += memberName.suffix; + return result; + }; + + MemberName.create = function (arg1, arg2, arg3) { + if (typeof arg1 === "string") { + return new MemberNameString(arg1); + } else { + var result = new MemberNameArray(); + if (arg2) + result.prefix = arg2; + if (arg3) + result.suffix = arg3; + result.entries.push(arg1); + return result; + } + }; + return MemberName; + })(); + TypeScript.MemberName = MemberName; + + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.call(this); + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + + MemberNameArray.prototype.addAll = function (entries) { + for (var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripQuotes(str) { + return str.replace(/"/g, "").replace(/'/g, ""); + } + TypeScript.stripQuotes = stripQuotes; + + function isSingleQuoted(str) { + return str.indexOf("'") !== -1; + } + TypeScript.isSingleQuoted = isSingleQuoted; + + function isQuoted(str) { + return str.indexOf("\"") !== -1 || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + + function swapQuotes(str) { + if (str.indexOf("\"") !== -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } else { + str = str.replace("'", "\""); + str = str.replace("'", "\""); + } + + return str; + } + TypeScript.swapQuotes = swapQuotes; + + function switchToForwardSlashes(path) { + return path.replace(/\\/g, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + + function trimModName(modName) { + if (modName.length > 5 && modName.substring(modName.length - 5, modName.length) === ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if (modName.length > 3 && modName.substring(modName.length - 3, modName.length) === ".ts") { + return modName.substring(0, modName.length - 3); + } + + if (modName.length > 3 && modName.substring(modName.length - 3, modName.length) === ".js") { + return modName.substring(0, modName.length - 3); + } + + return modName; + } + TypeScript.trimModName = trimModName; + + function getDeclareFilePath(fname) { + return isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) === invariantExt; + } + + function isJSFile(fname) { + return isFileOfExtension(fname, ".js"); + } + TypeScript.isJSFile = isJSFile; + + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + + function getPrettyName(modPath, quote, treatAsFileName) { + if (typeof quote === "undefined") { quote = true; } + if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { + absoluteModPath = switchToForwardSlashes(absoluteModPath); + + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + + var joinStartIndex = 0; + for (; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if (fixedModComponents[joinStartIndex] !== modComponents[joinStartIndex]) { + break; + } + } + + if (joinStartIndex !== 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for (; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if (fixedModComponents[joinStartIndex] !== "") { + relativePath = relativePath + "../"; + } + } + + return relativePath + relativePathComponents.join("/"); + } + + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + + function quoteBaseName(modPath) { + var modName = trimModName(stripQuotes(modPath)); + var path = getRootFilePath(modName); + if (path === "") { + return modPath; + } else { + var components = modName.split(path); + var fileIndex = components.length > 1 ? 1 : 0; + return quoteStr(components[fileIndex]); + } + } + TypeScript.quoteBaseName = quoteBaseName; + + function changePathToDTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + + function isRelative(path) { + return path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.charAt(0) === "\\" || path.charAt(0) === "/" || (path.indexOf(":\\") !== -1) || (path.indexOf(":/") !== -1); + } + TypeScript.isRooted = isRooted; + + function getRootFilePath(outFname) { + if (outFname === "") { + return outFname; + } else { + var isPath = outFname.indexOf("/") !== -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + + function normalizePath(path) { + if (/^\\\\[^\\]/.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + + normalizedParts.push(part); + } + + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnit = (function () { + function SourceUnit(path, fileInformation) { + this.path = path; + this.fileInformation = fileInformation; + this.referencedFiles = null; + this.lineStarts = null; + } + SourceUnit.prototype.getText = function (start, end) { + return this.fileInformation.contents().substring(start, end); + }; + + SourceUnit.prototype.getLength = function () { + return this.fileInformation.contents().length; + }; + + SourceUnit.prototype.getLineStartPositions = function () { + if (this.lineStarts === null) { + this.lineStarts = TypeScript.LineMap.fromString(this.fileInformation.contents()).lineStarts(); + } + + return this.lineStarts; + }; + + SourceUnit.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return SourceUnit; + })(); + TypeScript.SourceUnit = SourceUnit; + + var CompilationEnvironment = (function () { + function CompilationEnvironment(compilationSettings, ioHost) { + this.compilationSettings = compilationSettings; + this.ioHost = ioHost; + this.code = []; + this.inputFileNameToOutputFileName = new TypeScript.StringHashTable(); + } + CompilationEnvironment.prototype.getSourceUnit = function (path) { + var normalizedPath = TypeScript.switchToForwardSlashes(path.toUpperCase()); + for (var i = 0, n = this.code.length; i < n; i++) { + var sourceUnit = this.code[i]; + var soruceUnitNormalizedPath = TypeScript.switchToForwardSlashes(sourceUnit.path.toUpperCase()); + if (normalizedPath === soruceUnitNormalizedPath) { + return sourceUnit; + } + } + + return null; + }; + return CompilationEnvironment; + })(); + TypeScript.CompilationEnvironment = CompilationEnvironment; + + var CodeResolver = (function () { + function CodeResolver(environment) { + this.environment = environment; + this.visited = {}; + } + CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { + var resolvedFile = { fileInformation: null, path: referencePath }; + + var ioHost = this.environment.ioHost; + + var isRelativePath = TypeScript.isRelative(referencePath); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); + var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); + + if (!TypeScript.isTSFile(normalizedPath)) { + normalizedPath += ".ts"; + } + + normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); + var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); + + if (!this.visited[absoluteModuleID]) { + if (isRelativePath || isRootedPath || !performSearch) { + try { + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + + try { + resolvedFile.fileInformation = ioHost.readFile(normalizedPath); + } catch (err1) { + if (TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.fileInformation = ioHost.readFile(normalizedPath); + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); + + resolvedFile.path = normalizedPath; + this.visited[absoluteModuleID] = true; + } catch (err4) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); + + return false; + } + } else { + try { + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + + if (!resolvedFile) { + if (TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + } + } catch (e) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + normalizedPath); + + return false; + } + + if (resolvedFile) { + resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); + TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); + resolvedFile.fileInformation = resolvedFile.fileInformation; + this.visited[absoluteModuleID] = true; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); + } + } + + if (resolvedFile && resolvedFile.fileInformation !== null) { + var rootDir = ioHost.dirName(resolvedFile.path); + var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.fileInformation); + var preProcessedFileInfo = TypeScript.preProcessFile(resolvedFile.path, sourceUnit, this.environment.compilationSettings); + var resolvedFilePath = ioHost.resolvePath(resolvedFile.path); + var resolutionResult; + + sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; + + for (var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { + var fileReference = preProcessedFileInfo.referencedFiles[i]; + + normalizedPath = TypeScript.isRooted(fileReference.path) ? fileReference.path : rootDir + "/" + fileReference.path; + normalizedPath = ioHost.resolvePath(normalizedPath); + + if (resolvedFilePath === normalizedPath) { + resolutionDispatcher.errorReporter.addDiagnostic(new TypeScript.Diagnostic(normalizedPath, fileReference.position, fileReference.length, 270 /* A_file_cannot_have_a_reference_itself */, null)); + continue; + } + + resolutionResult = this.resolveCode(fileReference.path, rootDir, false, resolutionDispatcher); + + if (!resolutionResult) { + resolutionDispatcher.errorReporter.addDiagnostic(new TypeScript.Diagnostic(resolvedFilePath, fileReference.position, fileReference.length, 271 /* Cannot_resolve_referenced_file___0_ */, [fileReference.path])); + } + } + + for (var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { + var fileImport = preProcessedFileInfo.importedFiles[i]; + + resolutionResult = this.resolveCode(fileImport.path, rootDir, true, resolutionDispatcher); + + if (!resolutionResult) { + resolutionDispatcher.errorReporter.addDiagnostic(new TypeScript.Diagnostic(resolvedFilePath, fileImport.position, fileImport.length, 272 /* Cannot_resolve_imported_file___0_ */, [fileImport.path])); + } + } + + resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); + } + } + return true; + }; + return CodeResolver; + })(); + TypeScript.CodeResolver = CodeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CompilationSettings = (function () { + function CompilationSettings() { + this.propagateConstants = false; + this.minWhitespace = false; + this.emitComments = false; + this.watch = false; + this.exec = false; + this.resolve = true; + this.disallowBool = false; + this.allowAutomaticSemicolonInsertion = true; + this.allowModuleKeywordInExternalModuleReference = true; + this.useDefaultLib = true; + this.codeGenTarget = 0 /* EcmaScript3 */; + this.moduleGenTarget = 0 /* Synchronous */; + this.outputOption = ""; + this.mapSourceFiles = false; + this.emitFullSourceMapPath = false; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + this.gatherDiagnostics = false; + this.updateTC = false; + this.implicitAny = false; + } + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + + function getFileReferenceFromReferencePath(comment) { + var referencesRegEx = /^(\/\/\/\s*/gim; + var match = referencesRegEx.exec(comment); + + if (match) { + var path = TypeScript.normalizePath(match[3]); + var adjustedPath = TypeScript.normalizePath(path); + + var isResident = match.length >= 7 && match[6] === "true"; + if (isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } else { + return null; + } + } + + function getImplicitImport(comment) { + var implicitImportRegEx = /^(\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(comment); + + if (match) { + return true; + } + + return false; + } + TypeScript.getImplicitImport = getImplicitImport; + + function getReferencedFiles(fileName, sourceText) { + var preProcessInfo = preProcessFile(fileName, sourceText, null, false); + return preProcessInfo.referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; + + var scannerWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + var scannerDiagnostics = []; + + function processImports(lineMap, scanner, token, importedFiles) { + var position = 0; + var lineChar = { line: -1, character: -1 }; + + while (token.tokenKind !== 10 /* EndOfFileToken */) { + if (token.tokenKind === 49 /* ImportKeyword */) { + var importStart = position + token.leadingTriviaWidth(); + token = scanner.scan(scannerDiagnostics, false); + + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 108 /* EqualsToken */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 66 /* ModuleKeyword */ || token.tokenKind === 67 /* RequireKeyword */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 73 /* OpenParenToken */) { + var afterOpenParenPosition = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + + lineMap.fillLineAndCharacterFromPosition(importStart, lineChar); + + if (token.tokenKind === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: afterOpenParenPosition + token.leadingTriviaWidth(), + length: token.width(), + path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + + position = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + } + } + + function processTripleSlashDirectives(lineMap, firstToken, settings, referencedFiles) { + var leadingTrivia = firstToken.leadingTrivia(); + + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(triviaText); + + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + + referencedFiles.push(referencedCode); + } + + if (settings) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + var isNoDefaultLibMatch = isNoDefaultLibRegex.exec(triviaText); + if (isNoDefaultLibMatch) { + noDefaultLib = (isNoDefaultLibMatch[3] === "true"); + } + } + } + + position += trivia.fullWidth(); + } + + return { noDefaultLib: noDefaultLib }; + } + + function preProcessFile(fileName, sourceText, settings, readImportFiles) { + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + settings = settings || new CompilationSettings(); + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = new TypeScript.Scanner(fileName, text, settings.codeGenTarget, scannerWindow); + + var firstToken = scanner.scan(scannerDiagnostics, false); + + var importedFiles = []; + if (readImportFiles) { + processImports(text.lineMap(), scanner, firstToken, importedFiles); + } + + var referencedFiles = []; + var properties = processTripleSlashDirectives(text.lineMap(), firstToken, settings, referencedFiles); + + scannerDiagnostics.length = 0; + return { settings: settings, referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib }; + } + TypeScript.preProcessFile = preProcessFile; + + function getParseOptions(settings) { + return new TypeScript.ParseOptions(settings.allowAutomaticSemicolonInsertion, settings.allowModuleKeywordInExternalModuleReference); + } + TypeScript.getParseOptions = getParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextWriter = (function () { + function TextWriter(ioHost, path, writeByteOrderMark) { + this.ioHost = ioHost; + this.path = path; + this.writeByteOrderMark = writeByteOrderMark; + this.contents = ""; + this.onNewLine = true; + } + TextWriter.prototype.Write = function (s) { + this.contents += s; + this.onNewLine = false; + }; + + TextWriter.prototype.WriteLine = function (s) { + this.contents += s; + this.contents += "\r\n"; + this.onNewLine = true; + }; + + TextWriter.prototype.Close = function () { + try { + this.ioHost.writeFile(this.path, this.contents, this.writeByteOrderMark); + } catch (e) { + TypeScript.Emitter.throwEmitterError(e); + } + }; + return TextWriter; + })(); + TypeScript.TextWriter = TextWriter; + + var DeclarationEmitter = (function () { + function DeclarationEmitter(emittingFileName, semanticInfoChain, emitOptions, writeByteOrderMark) { + this.emittingFileName = emittingFileName; + this.semanticInfoChain = semanticInfoChain; + this.emitOptions = emitOptions; + this.writeByteOrderMark = writeByteOrderMark; + this.fileName = null; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.declarationContainerStack = []; + this.isDottedModuleName = []; + this.ignoreCallbackAst = null; + this.singleDeclFile = null; + this.varListCount = 0; + this.declFile = new TextWriter(emitOptions.ioHost, emittingFileName, writeByteOrderMark); + } + DeclarationEmitter.prototype.widenType = function (type) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol) { + return this.semanticInfoChain.anyTypeSymbol; + } + + return type; + }; + + DeclarationEmitter.prototype.close = function () { + try { + this.declFile.Close(); + } catch (e) { + TypeScript.Emitter.throwEmitterError(e); + } + }; + + DeclarationEmitter.prototype.emitDeclarations = function (script) { + TypeScript.AstWalkerWithDetailCallback.walk(script, this); + }; + + DeclarationEmitter.prototype.getAstDeclarationContainer = function () { + return this.declarationContainerStack[this.declarationContainerStack.length - 1]; + }; + + DeclarationEmitter.prototype.emitDottedModuleName = function () { + return (this.isDottedModuleName.length === 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; + }; + + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + if (this.emitOptions.compilationSettings.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + + DeclarationEmitter.prototype.canEmitSignature = function (declFlags, declAST, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { + if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } + if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } + var container; + if (useDeclarationContainerTop) { + container = this.getAstDeclarationContainer(); + } else { + container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; + } + + if (container.nodeType === 15 /* ModuleDeclaration */ && !TypeScript.hasFlag(declFlags, 1 /* Exported */)) { + var declSymbol = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(declAST, this.fileName).symbol; + return declSymbol && declSymbol.isExternallyVisible(); + } + + if (!canEmitGlobalAmbientDecl && container.nodeType === 2 /* Script */ && TypeScript.hasFlag(declFlags, 8 /* Ambient */)) { + return false; + } + + return true; + }; + + DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { + if (this.ignoreCallbackAst) { + TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst !== astWithPrePostCallback, "Ignore Callback AST mismatch"); + this.ignoreCallbackAst = null; + return false; + } else if (preCallback && !this.canEmitSignature(declFlags, astWithPrePostCallback, true, preCallback)) { + this.ignoreCallbackAst = astWithPrePostCallback; + return false; + } + + return true; + }; + + DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { + var result = this.getIndentString(); + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + result += "private "; + } + result += "static "; + } else { + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + result += "private "; + } else if (TypeScript.hasFlag(declFlags, 4 /* Public */)) { + result += "public "; + } else { + var emitDeclare = !TypeScript.hasFlag(declFlags, 1 /* Exported */); + + var container = this.getAstDeclarationContainer(); + if (container.nodeType === 15 /* ModuleDeclaration */ && TypeScript.hasFlag((container).getModuleFlags(), 256 /* IsWholeFile */) && TypeScript.hasFlag(declFlags, 1 /* Exported */)) { + result += "export "; + emitDeclare = true; + } + + if (emitDeclare && typeString !== "interface") { + result += "declare "; + } + + result += typeString + " "; + } + } + + return result; + }; + + DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { + this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); + }; + + DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { + if (typeof declFlag === "undefined") { declFlag = 0 /* None */; } + return !TypeScript.hasFlag(declFlag, 2 /* Private */); + }; + + DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { + this.declarationContainerStack.push(ast); + }; + + DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { + TypeScript.CompilerDiagnostics.assert(ast !== this.getAstDeclarationContainer(), 'Declaration container mismatch'); + this.declarationContainerStack.pop(); + }; + + DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { + if (typeof emitIndent === "undefined") { emitIndent = false; } + if (memberName.prefix === "{ ") { + if (emitIndent) { + this.emitIndent(); + } + + this.declFile.WriteLine("{"); + this.indenter.increaseIndent(); + emitIndent = true; + } else if (memberName.prefix !== "") { + if (emitIndent) { + this.emitIndent(); + } + + this.declFile.Write(memberName.prefix); + emitIndent = false; + } + + if (memberName.isString()) { + if (emitIndent) { + this.emitIndent(); + } + + this.declFile.Write((memberName).text); + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + this.emitTypeNamesMember(ar.entries[index], emitIndent); + if (ar.delim === "; ") { + this.declFile.WriteLine(";"); + } + } + } + + if (memberName.suffix === "}") { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.Write(memberName.suffix); + } else { + this.declFile.Write(memberName.suffix); + } + }; + + DeclarationEmitter.prototype.emitTypeSignature = function (type) { + var declarationContainerAst = this.getAstDeclarationContainer(); + var declarationContainerDecl = this.semanticInfoChain.getDeclForAST(declarationContainerAst, this.fileName); + var declarationPullSymbol = declarationContainerDecl.getSymbol(); + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol); + this.emitTypeNamesMember(typeNameMembers); + }; + + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = comment.getText(); + if (this.declFile.onNewLine) { + this.emitIndent(); + } else if (!comment.isBlockComment) { + this.declFile.WriteLine(""); + this.emitIndent(); + } + + this.declFile.Write(text[0]); + + for (var i = 1; i < text.length; i++) { + this.declFile.WriteLine(""); + this.emitIndent(); + this.declFile.Write(text[i]); + } + + if (comment.endsLine || !comment.isBlockComment) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (!this.emitOptions.compilationSettings.emitComments) { + return; + } + + var declComments = astOrSymbol.getDocComments(); + this.writeDeclarationComments(declComments, endLine); + }; + + DeclarationEmitter.prototype.writeDeclarationComments = function (declComments, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (declComments.length > 0) { + for (var i = 0; i < declComments.length; i++) { + this.emitComment(declComments[i]); + } + + if (endLine) { + if (!this.declFile.onNewLine) { + this.declFile.WriteLine(""); + } + } else { + if (this.declFile.onNewLine) { + this.emitIndent(); + } + } + } + }; + + DeclarationEmitter.prototype.emitTypeOfBoundDecl = function (boundDecl) { + var decl = this.semanticInfoChain.getDeclForAST(boundDecl, this.fileName); + var pullSymbol = decl.getSymbol(); + var type = this.widenType(pullSymbol.getType()); + if (!type) { + return; + } + + if (boundDecl.typeExpr || (boundDecl.init && type !== this.semanticInfoChain.anyTypeSymbol)) { + this.declFile.Write(": "); + this.emitTypeSignature(type); + } + }; + + DeclarationEmitter.prototype.VariableDeclaratorCallback = function (pre, varDecl) { + if (pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.getVarFlags()), varDecl, false)) { + var interfaceMember = (this.getAstDeclarationContainer().nodeType === 14 /* InterfaceDeclaration */); + this.emitDeclarationComments(varDecl); + if (!interfaceMember) { + if (this.varListCount >= 0) { + this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.getVarFlags()), "var"); + this.varListCount = -this.varListCount; + } + + this.declFile.Write(varDecl.id.actualText); + } else { + this.emitIndent(); + this.declFile.Write(varDecl.id.actualText); + if (TypeScript.hasFlag(varDecl.id.getFlags(), 4 /* OptionalName */)) { + this.declFile.Write("?"); + } + } + + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.getVarFlags()))) { + this.emitTypeOfBoundDecl(varDecl); + } + + if (this.varListCount > 0) { + this.varListCount--; + } else if (this.varListCount < 0) { + this.varListCount++; + } + + if (this.varListCount < 0) { + this.declFile.Write(", "); + } else { + this.declFile.WriteLine(";"); + } + } + return false; + }; + + DeclarationEmitter.prototype.BlockCallback = function (pre, block) { + return false; + }; + + DeclarationEmitter.prototype.VariableStatementCallback = function (pre, variableDeclaration) { + return true; + }; + + DeclarationEmitter.prototype.VariableDeclarationCallback = function (pre, variableDeclaration) { + if (pre) { + this.varListCount = variableDeclaration.declarators.members.length; + } else { + this.varListCount = 0; + } + return true; + }; + + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { + this.indenter.increaseIndent(); + + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(argDecl.id.actualText); + if (argDecl.isOptionalArg()) { + this.declFile.Write("?"); + } + + this.indenter.decreaseIndent(); + + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()))) { + this.emitTypeOfBoundDecl(argDecl); + } + }; + + DeclarationEmitter.prototype.isOverloadedCallSignature = function (funcDecl) { + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDecl, this.fileName); + var funcSymbol = functionDecl.getSymbol(); + var funcTypeSymbol = funcSymbol.getType(); + var signatures = funcTypeSymbol.getCallSignatures(); + return signatures && signatures.length > 1; + }; + + DeclarationEmitter.prototype.FunctionDeclarationCallback = function (pre, funcDecl) { + if (!pre) { + return false; + } + + if (funcDecl.isAccessor()) { + return this.emitPropertyAccessorSignature(funcDecl); + } + + var isInterfaceMember = (this.getAstDeclarationContainer().nodeType === 14 /* InterfaceDeclaration */); + + var funcSymbol = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(funcDecl, this.fileName).symbol; + var funcTypeSymbol = funcSymbol.getType(); + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return false; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return false; + } + } else if (!isInterfaceMember && TypeScript.hasFlag(funcDecl.getFunctionFlags(), 2 /* Private */) && this.isOverloadedCallSignature(funcDecl)) { + var callSignatures = funcTypeSymbol.getCallSignatures(); + TypeScript.Debug.assert(callSignatures && callSignatures.length > 1); + var firstSignature = callSignatures[0].isDefinition() ? callSignatures[1] : callSignatures[0]; + var firstSignatureDecl = firstSignature.getDeclarations()[0]; + var firstFuncDecl = this.semanticInfoChain.getASTForDecl(firstSignatureDecl); + if (firstFuncDecl !== funcDecl) { + return false; + } + } + + if (!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()), funcDecl, false)) { + return false; + } + + var funcSignature = this.semanticInfoChain.getDeclForAST(funcDecl, this.fileName).getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + if (funcDecl.isConstructor) { + this.emitIndent(); + this.declFile.Write("constructor"); + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } else { + var id = funcDecl.getNameText(); + if (!isInterfaceMember) { + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()), "function"); + if (id !== "__missing" || !funcDecl.name || !funcDecl.name.isMissing()) { + this.declFile.Write(id); + } else if (funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } + + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } else { + this.emitIndent(); + if (funcDecl.isConstructMember()) { + this.declFile.Write("new"); + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } else if (!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { + this.declFile.Write(id); + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + if (TypeScript.hasFlag(funcDecl.name.getFlags(), 4 /* OptionalName */)) { + this.declFile.Write("? "); + } + } else { + this.emitTypeParameters(funcDecl.typeArguments, funcSignature); + } + } + } + + if (!funcDecl.isIndexerMember()) { + this.declFile.Write("("); + } else { + this.declFile.Write("["); + } + + if (funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if (funcDecl.variableArgList) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + this.emitArgDecl(argDecl, funcDecl); + if (i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + } + + if (funcDecl.variableArgList) { + var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; + if (funcDecl.arguments.members.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + + this.emitArgDecl(lastArg, funcDecl); + } + + if (!funcDecl.isIndexerMember()) { + this.declFile.Write(")"); + } else { + this.declFile.Write("]"); + } + + if (!funcDecl.isConstructor && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()))) { + var returnType = funcSignature.getReturnType(); + if (funcDecl.returnTypeAnnotation || (returnType && returnType !== this.semanticInfoChain.anyTypeSymbol)) { + this.declFile.Write(": "); + this.emitTypeSignature(returnType); + } + } + + this.declFile.WriteLine(";"); + + return false; + }; + + DeclarationEmitter.prototype.emitBaseExpression = function (bases, index) { + var baseTypeAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(bases.members[index], this.fileName); + var baseType = baseTypeAndDiagnostics && baseTypeAndDiagnostics.symbol; + this.emitTypeSignature(baseType); + }; + + DeclarationEmitter.prototype.emitBaseList = function (typeDecl, useExtendsList) { + var bases = useExtendsList ? typeDecl.extendsList : typeDecl.implementsList; + if (bases && (bases.members.length > 0)) { + var qual = useExtendsList ? "extends" : "implements"; + this.declFile.Write(" " + qual + " "); + var basesLen = bases.members.length; + for (var i = 0; i < basesLen; i++) { + if (i > 0) { + this.declFile.Write(", "); + } + this.emitBaseExpression(bases, i); + } + } + }; + + DeclarationEmitter.prototype.emitAccessorDeclarationComments = function (funcDecl) { + if (!this.emitOptions.compilationSettings.emitComments) { + return; + } + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain, this.fileName); + var comments = []; + if (accessors.getter) { + comments = comments.concat(accessors.getter.getDocComments()); + } + if (accessors.setter) { + comments = comments.concat(accessors.setter.getDocComments()); + } + this.writeDeclarationComments(comments); + }; + + DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain, this.fileName); + if (!TypeScript.hasFlag(funcDecl.getFunctionFlags(), 32 /* GetAccessor */) && accessorSymbol.getGetter()) { + return false; + } + + this.emitAccessorDeclarationComments(funcDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()), "var"); + this.declFile.Write(funcDecl.name.actualText); + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.getFunctionFlags()))) { + this.declFile.Write(" : "); + var type = accessorSymbol.getType(); + this.emitTypeSignature(type); + } + this.declFile.WriteLine(";"); + + return false; + }; + + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + if (funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if (funcDecl.variableArgList) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + if (TypeScript.hasFlag(argDecl.getVarFlags(), 256 /* Property */)) { + this.emitDeclarationComments(argDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.getVarFlags()), "var"); + this.declFile.Write(argDecl.id.actualText); + + if (this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.getVarFlags()))) { + this.emitTypeOfBoundDecl(argDecl); + } + this.declFile.WriteLine(";"); + } + } + } + }; + + DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { + if (!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.getVarFlags()), classDecl, pre)) { + return false; + } + + if (pre) { + var className = classDecl.name.actualText; + this.emitDeclarationComments(classDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.getVarFlags()), "class"); + this.declFile.Write(className); + this.pushDeclarationContainer(classDecl); + this.emitTypeParameters(classDecl.typeParameters); + this.emitBaseList(classDecl, true); + this.emitBaseList(classDecl, false); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + if (classDecl.constructorDecl) { + this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); + } + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(classDecl); + + this.emitIndent(); + this.declFile.WriteLine("}"); + } + + return true; + }; + + DeclarationEmitter.prototype.emitTypeParameters = function (typeParams, funcSignature) { + if (!typeParams || !typeParams.members.length) { + return; + } + + this.declFile.Write("<"); + var containerAst = this.getAstDeclarationContainer(); + var containerDecl = this.semanticInfoChain.getDeclForAST(containerAst, this.fileName); + var containerSymbol = containerDecl.getSymbol(); + var typars; + if (funcSignature) { + typars = funcSignature.getTypeParameters(); + } else { + typars = containerSymbol.getTypeArguments(); + if (!typars || !typars.length) { + typars = containerSymbol.getTypeParameters(); + } + } + + for (var i = 0; i < typars.length; i++) { + if (i) { + this.declFile.Write(", "); + } + + var memberName = typars[i].getScopedNameEx(containerSymbol, true); + this.emitTypeNamesMember(memberName); + } + + this.declFile.Write(">"); + }; + + DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { + if (!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.getVarFlags()), interfaceDecl, pre)) { + return false; + } + + if (pre) { + var interfaceName = interfaceDecl.name.actualText; + this.emitDeclarationComments(interfaceDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.getVarFlags()), "interface"); + this.declFile.Write(interfaceName); + this.pushDeclarationContainer(interfaceDecl); + this.emitTypeParameters(interfaceDecl.typeParameters); + this.emitBaseList(interfaceDecl, true); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(interfaceDecl); + + this.emitIndent(); + this.declFile.WriteLine("}"); + } + + return true; + }; + + DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDeclAST) { + if (pre) { + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST, this.fileName); + var importSymbol = importDecl.getSymbol(); + if (importSymbol.getTypeUsedExternally() || TypeScript.PullContainerTypeSymbol.usedAsSymbol(importSymbol.getContainer(), importSymbol)) { + this.emitDeclarationComments(importDeclAST); + this.emitIndent(); + this.declFile.Write("import "); + + this.declFile.Write(importDeclAST.id.actualText + " = "); + if (importDeclAST.isDynamicImport) { + this.declFile.WriteLine("require(" + importDeclAST.getAliasName() + ");"); + } else { + this.declFile.WriteLine(importDeclAST.getAliasName() + ";"); + } + } + } + + return false; + }; + + DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { + if (!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), moduleDecl)) { + return false; + } + + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), "enum"); + this.declFile.WriteLine(moduleDecl.name.actualText + " {"); + + this.indenter.increaseIndent(); + var membersLen = moduleDecl.members.members.length; + for (var j = 0; j < membersLen; j++) { + var memberDecl = moduleDecl.members.members[j]; + if (memberDecl.nodeType === 97 /* VariableStatement */ && !TypeScript.hasFlag(memberDecl.getFlags(), 32 /* EnumMapElement */)) { + var variableStatement = memberDecl; + this.emitDeclarationComments(memberDecl); + this.emitIndent(); + this.declFile.WriteLine((variableStatement.declaration.declarators.members[0]).id.actualText + ","); + } + } + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + + return false; + }; + + DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 256 /* IsWholeFile */)) { + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 512 /* IsDynamic */)) { + if (pre) { + if (!this.emitOptions.outputMany) { + this.singleDeclFile = this.declFile; + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt === 0, "Indent has to be 0 when outputing new file"); + + var declareFileName = this.emitOptions.mapOutputFileName(this.fileName, TypeScript.TypeScriptCompiler.mapToDTSFileName); + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.compilationSettings.emitComments && moduleDecl.containsUnicodeCharInComment); + + this.declFile = new TextWriter(this.emitOptions.ioHost, declareFileName, this.writeByteOrderMark); + } + this.pushDeclarationContainer(moduleDecl); + } else { + if (!this.emitOptions.outputMany) { + TypeScript.CompilerDiagnostics.assert(this.singleDeclFile !== this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt === 0, "Indent has to be 0 when outputing new file"); + + try { + this.declFile.Close(); + } catch (e) { + TypeScript.Emitter.throwEmitterError(e); + } + + this.declFile = this.singleDeclFile; + } + + this.popDeclarationContainer(moduleDecl); + } + } + + return true; + } + + if (moduleDecl.isEnum()) { + if (pre) { + this.emitEnumSignature(moduleDecl); + } + return false; + } + + if (!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), moduleDecl, pre)) { + return false; + } + + if (pre) { + if (this.emitDottedModuleName()) { + this.dottedModuleEmit += "."; + } else { + this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.getModuleFlags()), "module"); + } + + this.dottedModuleEmit += moduleDecl.name.actualText; + + var isCurrentModuleDotted = (moduleDecl.members.members.length === 1 && moduleDecl.members.members[0].nodeType === 15 /* ModuleDeclaration */ && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).getModuleFlags(), 1 /* Exported */)); + + var moduleDeclComments = moduleDecl.getDocComments(); + isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments === null || moduleDeclComments.length === 0); + + this.isDottedModuleName.push(isCurrentModuleDotted); + this.pushDeclarationContainer(moduleDecl); + + if (!isCurrentModuleDotted) { + this.emitDeclarationComments(moduleDecl); + this.declFile.Write(this.dottedModuleEmit); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + } + } else { + if (!this.emitDottedModuleName()) { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + + this.popDeclarationContainer(moduleDecl); + this.isDottedModuleName.pop(); + } + + return true; + }; + + DeclarationEmitter.prototype.ExportAssignmentCallback = function (pre, ast) { + if (pre) { + this.emitIndent(); + this.declFile.Write("export = "); + this.declFile.Write((ast).id.actualText); + this.declFile.WriteLine(";"); + } + + return false; + }; + + DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { + if (pre) { + if (this.emitOptions.outputMany) { + for (var i = 0; i < script.referencedFiles.length; i++) { + var referencePath = script.referencedFiles[i].path; + var declareFileName; + if (TypeScript.isRooted(referencePath)) { + declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } else { + declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); + } + this.declFile.WriteLine('/// '); + } + } + this.pushDeclarationContainer(script); + } else { + this.popDeclarationContainer(script); + } + return true; + }; + + DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { + return !ast.isStatement(); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + + var sizeInEvenBytes = (m + 7) & ~7; + + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + + BloomFilter.prototype.computeHash = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = this.getCharacter(key, index); + var c2 = this.getCharacter(key, index + 1); + + var k = Math.abs(c1 | (c2 << 16)); + + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft == 1) { + h ^= this.getCharacter(key, index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + + return Math.round(h); + }; + + BloomFilter.prototype.getCharacter = function (key, index) { + return key.charCodeAt(index); + }; + + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + this.add(name); + } + }; + + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + + return true; + }; + + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount == filter.hashFunctionCount; + }; + + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length != array2.length) { + return false; + } + + for (var i = 0; i < array1.length; i++) { + if (array1[i] != array2[i]) { + return false; + } + } + + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IdentifierWalker = (function (_super) { + __extends(IdentifierWalker, _super); + function IdentifierWalker(list) { + _super.call(this); + this.list = list; + } + IdentifierWalker.prototype.visitToken = function (token) { + this.list[token.text()] = true; + }; + return IdentifierWalker; + })(TypeScript.SyntaxWalker); + TypeScript.IdentifierWalker = IdentifierWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DataMap = (function () { + function DataMap() { + this.map = {}; + } + DataMap.prototype.link = function (id, data) { + this.map[id] = data; + }; + + DataMap.prototype.unlink = function (id) { + this.map[id] = undefined; + }; + + DataMap.prototype.read = function (id) { + return this.map[id]; + }; + + DataMap.prototype.flush = function () { + this.map = {}; + }; + + DataMap.prototype.unpatch = function () { + return null; + }; + return DataMap; + })(); + TypeScript.DataMap = DataMap; + + var PatchedDataMap = (function (_super) { + __extends(PatchedDataMap, _super); + function PatchedDataMap(parent) { + _super.call(this); + this.parent = parent; + this.diffs = {}; + } + PatchedDataMap.prototype.link = function (id, data) { + this.diffs[id] = data; + }; + + PatchedDataMap.prototype.unlink = function (id) { + this.diffs[id] = undefined; + }; + + PatchedDataMap.prototype.read = function (id) { + var data = this.diffs[id]; + + if (data) { + return data; + } + + return this.parent.read(id); + }; + + PatchedDataMap.prototype.flush = function () { + this.diffs = {}; + }; + + PatchedDataMap.prototype.unpatch = function () { + this.flush(); + return this.parent; + }; + return PatchedDataMap; + })(DataMap); + TypeScript.PatchedDataMap = PatchedDataMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullElementFlags) { + PullElementFlags[PullElementFlags["None"] = 0] = "None"; + PullElementFlags[PullElementFlags["Exported"] = 1] = "Exported"; + PullElementFlags[PullElementFlags["Private"] = 1 << 1] = "Private"; + PullElementFlags[PullElementFlags["Public"] = 1 << 2] = "Public"; + PullElementFlags[PullElementFlags["Ambient"] = 1 << 3] = "Ambient"; + PullElementFlags[PullElementFlags["Static"] = 1 << 4] = "Static"; + PullElementFlags[PullElementFlags["GetAccessor"] = 1 << 5] = "GetAccessor"; + PullElementFlags[PullElementFlags["SetAccessor"] = 1 << 6] = "SetAccessor"; + PullElementFlags[PullElementFlags["Optional"] = 1 << 7] = "Optional"; + PullElementFlags[PullElementFlags["Call"] = 1 << 8] = "Call"; + PullElementFlags[PullElementFlags["Constructor"] = 1 << 9] = "Constructor"; + PullElementFlags[PullElementFlags["Index"] = 1 << 10] = "Index"; + PullElementFlags[PullElementFlags["Signature"] = 1 << 11] = "Signature"; + PullElementFlags[PullElementFlags["Enum"] = 1 << 12] = "Enum"; + PullElementFlags[PullElementFlags["FatArrow"] = 1 << 13] = "FatArrow"; + + PullElementFlags[PullElementFlags["ClassConstructorVariable"] = 1 << 14] = "ClassConstructorVariable"; + PullElementFlags[PullElementFlags["InitializedModule"] = 1 << 15] = "InitializedModule"; + PullElementFlags[PullElementFlags["InitializedDynamicModule"] = 1 << 16] = "InitializedDynamicModule"; + PullElementFlags[PullElementFlags["InitializedEnum"] = 1 << 17] = "InitializedEnum"; + + PullElementFlags[PullElementFlags["MustCaptureThis"] = 1 << 18] = "MustCaptureThis"; + PullElementFlags[PullElementFlags["Constant"] = 1 << 19] = "Constant"; + + PullElementFlags[PullElementFlags["ExpressionElement"] = 1 << 20] = "ExpressionElement"; + + PullElementFlags[PullElementFlags["DeclaredInAWithBlock"] = 1 << 21] = "DeclaredInAWithBlock"; + + PullElementFlags[PullElementFlags["ImplicitVariable"] = PullElementFlags.ClassConstructorVariable | PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.InitializedEnum] = "ImplicitVariable"; + PullElementFlags[PullElementFlags["SomeInitializedModule"] = PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.InitializedEnum] = "SomeInitializedModule"; + })(TypeScript.PullElementFlags || (TypeScript.PullElementFlags = {})); + var PullElementFlags = TypeScript.PullElementFlags; + + (function (PullElementKind) { + PullElementKind[PullElementKind["None"] = 0] = "None"; + PullElementKind[PullElementKind["Global"] = 0] = "Global"; + + PullElementKind[PullElementKind["Script"] = 1] = "Script"; + PullElementKind[PullElementKind["Primitive"] = 1 << 1] = "Primitive"; + + PullElementKind[PullElementKind["Container"] = 1 << 2] = "Container"; + PullElementKind[PullElementKind["Class"] = 1 << 3] = "Class"; + PullElementKind[PullElementKind["Interface"] = 1 << 4] = "Interface"; + PullElementKind[PullElementKind["DynamicModule"] = 1 << 5] = "DynamicModule"; + PullElementKind[PullElementKind["Enum"] = 1 << 6] = "Enum"; + PullElementKind[PullElementKind["Array"] = 1 << 7] = "Array"; + PullElementKind[PullElementKind["TypeAlias"] = 1 << 8] = "TypeAlias"; + PullElementKind[PullElementKind["ObjectLiteral"] = 1 << 9] = "ObjectLiteral"; + + PullElementKind[PullElementKind["Variable"] = 1 << 10] = "Variable"; + PullElementKind[PullElementKind["Parameter"] = 1 << 11] = "Parameter"; + PullElementKind[PullElementKind["Property"] = 1 << 12] = "Property"; + PullElementKind[PullElementKind["TypeParameter"] = 1 << 13] = "TypeParameter"; + + PullElementKind[PullElementKind["Function"] = 1 << 14] = "Function"; + PullElementKind[PullElementKind["ConstructorMethod"] = 1 << 15] = "ConstructorMethod"; + PullElementKind[PullElementKind["Method"] = 1 << 16] = "Method"; + PullElementKind[PullElementKind["FunctionExpression"] = 1 << 17] = "FunctionExpression"; + + PullElementKind[PullElementKind["GetAccessor"] = 1 << 18] = "GetAccessor"; + PullElementKind[PullElementKind["SetAccessor"] = 1 << 19] = "SetAccessor"; + + PullElementKind[PullElementKind["CallSignature"] = 1 << 20] = "CallSignature"; + PullElementKind[PullElementKind["ConstructSignature"] = 1 << 21] = "ConstructSignature"; + PullElementKind[PullElementKind["IndexSignature"] = 1 << 22] = "IndexSignature"; + + PullElementKind[PullElementKind["ObjectType"] = 1 << 23] = "ObjectType"; + PullElementKind[PullElementKind["FunctionType"] = 1 << 24] = "FunctionType"; + PullElementKind[PullElementKind["ConstructorType"] = 1 << 25] = "ConstructorType"; + + PullElementKind[PullElementKind["EnumMember"] = 1 << 26] = "EnumMember"; + PullElementKind[PullElementKind["ErrorType"] = 1 << 27] = "ErrorType"; + + PullElementKind[PullElementKind["Expression"] = 1 << 28] = "Expression"; + + PullElementKind[PullElementKind["WithBlock"] = 1 << 29] = "WithBlock"; + PullElementKind[PullElementKind["CatchBlock"] = 1 << 30] = "CatchBlock"; + + PullElementKind[PullElementKind["All"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Container | PullElementKind.Class | PullElementKind.Interface | PullElementKind.DynamicModule | PullElementKind.Enum | PullElementKind.Array | PullElementKind.TypeAlias | PullElementKind.ObjectLiteral | PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.TypeParameter | PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.EnumMember | PullElementKind.ErrorType | PullElementKind.Expression | PullElementKind.WithBlock | PullElementKind.CatchBlock] = "All"; + + PullElementKind[PullElementKind["SomeFunction"] = PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeFunction"; + + PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; + + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Array | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter | PullElementKind.ErrorType] = "SomeType"; + + PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; + + PullElementKind[PullElementKind["SomeContainer"] = PullElementKind.Container | PullElementKind.DynamicModule | PullElementKind.TypeAlias] = "SomeContainer"; + + PullElementKind[PullElementKind["SomeBlock"] = PullElementKind.WithBlock | PullElementKind.CatchBlock] = "SomeBlock"; + + PullElementKind[PullElementKind["SomeSignature"] = PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeSignature"; + + PullElementKind[PullElementKind["SomeAccessor"] = PullElementKind.GetAccessor | PullElementKind.SetAccessor] = "SomeAccessor"; + + PullElementKind[PullElementKind["SomeTypeReference"] = PullElementKind.Interface | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "SomeTypeReference"; + + PullElementKind[PullElementKind["SomeLHS"] = PullElementKind.Variable | PullElementKind.Property | PullElementKind.Parameter | PullElementKind.SetAccessor | PullElementKind.Method] = "SomeLHS"; + + PullElementKind[PullElementKind["InterfaceTypeExtension"] = PullElementKind.Interface | PullElementKind.Class | PullElementKind.Enum] = "InterfaceTypeExtension"; + PullElementKind[PullElementKind["ClassTypeExtension"] = PullElementKind.Interface | PullElementKind.Class] = "ClassTypeExtension"; + PullElementKind[PullElementKind["EnumTypeExtension"] = PullElementKind.Interface | PullElementKind.Enum] = "EnumTypeExtension"; + })(TypeScript.PullElementKind || (TypeScript.PullElementKind = {})); + var PullElementKind = TypeScript.PullElementKind; + + (function (SymbolLinkKind) { + SymbolLinkKind[SymbolLinkKind["TypedAs"] = 0] = "TypedAs"; + SymbolLinkKind[SymbolLinkKind["ContextuallyTypedAs"] = 1] = "ContextuallyTypedAs"; + SymbolLinkKind[SymbolLinkKind["ProvidesInferredType"] = 2] = "ProvidesInferredType"; + SymbolLinkKind[SymbolLinkKind["ArrayType"] = 3] = "ArrayType"; + + SymbolLinkKind[SymbolLinkKind["ArrayOf"] = 4] = "ArrayOf"; + + SymbolLinkKind[SymbolLinkKind["PublicMember"] = 5] = "PublicMember"; + SymbolLinkKind[SymbolLinkKind["PrivateMember"] = 6] = "PrivateMember"; + + SymbolLinkKind[SymbolLinkKind["ConstructorMethod"] = 7] = "ConstructorMethod"; + + SymbolLinkKind[SymbolLinkKind["Aliases"] = 8] = "Aliases"; + SymbolLinkKind[SymbolLinkKind["ExportAliases"] = 9] = "ExportAliases"; + + SymbolLinkKind[SymbolLinkKind["ContainedBy"] = 10] = "ContainedBy"; + + SymbolLinkKind[SymbolLinkKind["Extends"] = 11] = "Extends"; + SymbolLinkKind[SymbolLinkKind["Implements"] = 12] = "Implements"; + + SymbolLinkKind[SymbolLinkKind["Parameter"] = 13] = "Parameter"; + SymbolLinkKind[SymbolLinkKind["ReturnType"] = 14] = "ReturnType"; + + SymbolLinkKind[SymbolLinkKind["CallSignature"] = 15] = "CallSignature"; + SymbolLinkKind[SymbolLinkKind["ConstructSignature"] = 16] = "ConstructSignature"; + SymbolLinkKind[SymbolLinkKind["IndexSignature"] = 17] = "IndexSignature"; + + SymbolLinkKind[SymbolLinkKind["TypeParameter"] = 18] = "TypeParameter"; + SymbolLinkKind[SymbolLinkKind["TypeArgument"] = 19] = "TypeArgument"; + SymbolLinkKind[SymbolLinkKind["TypeParameterSpecializedTo"] = 20] = "TypeParameterSpecializedTo"; + SymbolLinkKind[SymbolLinkKind["SpecializedTo"] = 21] = "SpecializedTo"; + + SymbolLinkKind[SymbolLinkKind["TypeConstraint"] = 22] = "TypeConstraint"; + + SymbolLinkKind[SymbolLinkKind["ContributesToExpression"] = 23] = "ContributesToExpression"; + + SymbolLinkKind[SymbolLinkKind["GetterFunction"] = 24] = "GetterFunction"; + SymbolLinkKind[SymbolLinkKind["SetterFunction"] = 25] = "SetterFunction"; + })(TypeScript.SymbolLinkKind || (TypeScript.SymbolLinkKind = {})); + var SymbolLinkKind = TypeScript.SymbolLinkKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullDeclID = 0; + TypeScript.lastBoundPullDeclId = 0; + + var PullDecl = (function () { + function PullDecl(declName, displayName, declType, declFlags, span, scriptName) { + this.symbol = null; + this.declGroups = new TypeScript.BlockIntrinsics(); + this.signatureSymbol = null; + this.specializingSignatureSymbol = null; + this.childDecls = []; + this.typeParameters = []; + this.childDeclTypeCache = new TypeScript.BlockIntrinsics(); + this.childDeclValueCache = new TypeScript.BlockIntrinsics(); + this.childDeclNamespaceCache = new TypeScript.BlockIntrinsics(); + this.childDeclTypeParameterCache = new TypeScript.BlockIntrinsics(); + this.declID = TypeScript.pullDeclID++; + this.declFlags = 0 /* None */; + this.diagnostics = null; + this.parentDecl = null; + this._parentPath = null; + this._isBound = false; + this.synthesizedValDecl = null; + this.declName = declName; + this.declType = declType; + this.declFlags = declFlags; + this.span = span; + this.scriptName = scriptName; + + if (displayName !== this.declName) { + this.declDisplayName = displayName; + } + } + PullDecl.prototype.getDeclID = function () { + return this.declID; + }; + + PullDecl.prototype.getName = function () { + return this.declName; + }; + PullDecl.prototype.getKind = function () { + return this.declType; + }; + + PullDecl.prototype.getDisplayName = function () { + return this.declDisplayName === undefined ? this.declName : this.declDisplayName; + }; + + PullDecl.prototype.setSymbol = function (symbol) { + this.symbol = symbol; + }; + + PullDecl.prototype.ensureSymbolIsBound = function (bindSignatureSymbol) { + if (typeof bindSignatureSymbol === "undefined") { bindSignatureSymbol = false; } + if (!((bindSignatureSymbol && this.signatureSymbol) || this.symbol) && !this._isBound && this.declType != 1 /* Script */) { + var prevUnit = TypeScript.globalBinder.semanticInfo; + TypeScript.globalBinder.setUnit(this.scriptName); + TypeScript.globalBinder.bindDeclToPullSymbol(this); + if (prevUnit) { + TypeScript.globalBinder.setUnit(prevUnit.getPath()); + } + } + }; + + PullDecl.prototype.getSymbol = function () { + if (this.declType == 1 /* Script */) { + return null; + } + + this.ensureSymbolIsBound(); + + return this.symbol; + }; + + PullDecl.prototype.hasSymbol = function () { + return this.symbol != null; + }; + + PullDecl.prototype.setSignatureSymbol = function (signature) { + this.signatureSymbol = signature; + }; + PullDecl.prototype.getSignatureSymbol = function () { + this.ensureSymbolIsBound(true); + + return this.signatureSymbol; + }; + + PullDecl.prototype.hasSignature = function () { + return this.signatureSymbol != null; + }; + + PullDecl.prototype.setSpecializingSignatureSymbol = function (signature) { + this.specializingSignatureSymbol = signature; + }; + PullDecl.prototype.getSpecializingSignatureSymbol = function () { + if (this.specializingSignatureSymbol) { + return this.specializingSignatureSymbol; + } + + return this.signatureSymbol; + }; + + PullDecl.prototype.getFlags = function () { + return this.declFlags; + }; + PullDecl.prototype.setFlags = function (flags) { + this.declFlags = flags; + }; + + PullDecl.prototype.getSpan = function () { + return this.span; + }; + PullDecl.prototype.setSpan = function (span) { + this.span = span; + }; + + PullDecl.prototype.getScriptName = function () { + return this.scriptName; + }; + + PullDecl.prototype.setValueDecl = function (valDecl) { + this.synthesizedValDecl = valDecl; + }; + PullDecl.prototype.getValueDecl = function () { + return this.synthesizedValDecl; + }; + + PullDecl.prototype.isEqual = function (other) { + return (this.declName === other.declName) && (this.declType === other.declType) && (this.declFlags === other.declFlags) && (this.scriptName === other.scriptName) && (this.span.start() === other.span.start()) && (this.span.end() === other.span.end()); + }; + + PullDecl.prototype.getParentDecl = function () { + return this.parentDecl; + }; + + PullDecl.prototype.setParentDecl = function (parentDecl) { + this.parentDecl = parentDecl; + }; + + PullDecl.prototype.addDiagnostic = function (diagnostic) { + if (diagnostic) { + if (!this.diagnostics) { + this.diagnostics = []; + } + + this.diagnostics[this.diagnostics.length] = diagnostic; + } + }; + + PullDecl.prototype.getDiagnostics = function () { + return this.diagnostics; + }; + + PullDecl.prototype.setErrors = function (diagnostics) { + if (diagnostics) { + this.diagnostics = []; + + for (var i = 0; i < diagnostics.length; i++) { + diagnostics[i].adjustOffset(this.span.start()); + this.diagnostics[this.diagnostics.length] = diagnostics[i]; + } + } + }; + + PullDecl.prototype.resetErrors = function () { + this.diagnostics = []; + }; + + PullDecl.prototype.getChildDeclCache = function (declKind) { + return declKind === 8192 /* TypeParameter */ ? this.childDeclTypeParameterCache : TypeScript.hasFlag(declKind, TypeScript.PullElementKind.SomeContainer) ? this.childDeclNamespaceCache : TypeScript.hasFlag(declKind, TypeScript.PullElementKind.SomeType) ? this.childDeclTypeCache : this.childDeclValueCache; + }; + + PullDecl.prototype.addChildDecl = function (childDecl) { + if (childDecl.getKind() === 8192 /* TypeParameter */) { + this.typeParameters[this.typeParameters.length] = childDecl; + } else { + this.childDecls[this.childDecls.length] = childDecl; + } + + var declName = childDecl.getName(); + var cache = this.getChildDeclCache(childDecl.getKind()); + var childrenOfName = cache[declName]; + if (!childrenOfName) { + childrenOfName = []; + } + + childrenOfName.push(childDecl); + cache[declName] = childrenOfName; + }; + + PullDecl.prototype.searchChildDecls = function (declName, searchKind) { + var cache = (searchKind & TypeScript.PullElementKind.SomeType) ? this.childDeclTypeCache : (searchKind & TypeScript.PullElementKind.SomeContainer) ? this.childDeclNamespaceCache : this.childDeclValueCache; + + var cacheVal = cache[declName]; + + if (cacheVal) { + return cacheVal; + } else { + if (searchKind & TypeScript.PullElementKind.SomeType) { + cacheVal = this.childDeclTypeParameterCache[declName]; + + if (cacheVal) { + return cacheVal; + } + } + + return []; + } + }; + + PullDecl.prototype.getChildDecls = function () { + return this.childDecls; + }; + PullDecl.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + + PullDecl.prototype.addVariableDeclToGroup = function (decl) { + var declGroup = this.declGroups[decl.getName()]; + if (declGroup) { + declGroup.addDecl(decl); + } else { + declGroup = new PullDeclGroup(decl.getName()); + declGroup.addDecl(decl); + this.declGroups[decl.getName()] = declGroup; + } + }; + + PullDecl.prototype.getVariableDeclGroups = function () { + var declGroups = []; + + for (var declName in this.declGroups) { + if (this.declGroups[declName]) { + declGroups[declGroups.length] = this.declGroups[declName].getDecls(); + } + } + + return declGroups; + }; + + PullDecl.prototype.getParentPath = function () { + return this._parentPath; + }; + + PullDecl.prototype.setParentPath = function (path) { + this._parentPath = path; + }; + + PullDecl.prototype.setIsBound = function (isBinding) { + this._isBound = isBinding; + }; + + PullDecl.prototype.isBound = function () { + return this._isBound; + }; + return PullDecl; + })(); + TypeScript.PullDecl = PullDecl; + + var PullFunctionExpressionDecl = (function (_super) { + __extends(PullFunctionExpressionDecl, _super); + function PullFunctionExpressionDecl(expressionName, declFlags, span, scriptName) { + _super.call(this, "", "", 131072 /* FunctionExpression */, declFlags, span, scriptName); + this.functionExpressionName = expressionName; + } + PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { + return this.functionExpressionName; + }; + return PullFunctionExpressionDecl; + })(PullDecl); + TypeScript.PullFunctionExpressionDecl = PullFunctionExpressionDecl; + + var PullDeclGroup = (function () { + function PullDeclGroup(name) { + this.name = name; + this._decls = []; + } + PullDeclGroup.prototype.addDecl = function (decl) { + if (decl.getName() === this.name) { + this._decls[this._decls.length] = decl; + } + }; + + PullDeclGroup.prototype.getDecls = function () { + return this._decls; + }; + return PullDeclGroup; + })(); + TypeScript.PullDeclGroup = PullDeclGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullSymbolID = 0; + TypeScript.lastBoundPullSymbolID = 0; + TypeScript.globalTyvarID = 0; + + var PullSymbol = (function () { + function PullSymbol(name, declKind) { + this.pullSymbolID = TypeScript.pullSymbolID++; + this.outgoingLinks = new TypeScript.LinkList(); + this.incomingLinks = new TypeScript.LinkList(); + this.declarations = new TypeScript.LinkList(); + this.cachedPathIDs = {}; + this.cachedContainerLink = null; + this.cachedTypeLink = null; + this.cachedDeclarations = null; + this.hasBeenResolved = false; + this.isOptional = false; + this.inResolution = false; + this.isSynthesized = false; + this.isBound = false; + this.rebindingID = 0; + this.isVarArg = false; + this.isSpecialized = false; + this.isBeingSpecialized = false; + this.rootSymbol = null; + this.typeChangeUpdateVersion = -1; + this.addUpdateVersion = -1; + this.removeUpdateVersion = -1; + this.docComments = null; + this.isPrinting = false; + this.name = name; + this.declKind = declKind; + } + PullSymbol.prototype.getSymbolID = function () { + return this.pullSymbolID; + }; + + PullSymbol.prototype.isType = function () { + return (this.declKind & TypeScript.PullElementKind.SomeType) != 0; + }; + + PullSymbol.prototype.isSignature = function () { + return (this.declKind & TypeScript.PullElementKind.SomeSignature) != 0; + }; + + PullSymbol.prototype.isArray = function () { + return (this.declKind & 128 /* Array */) != 0; + }; + + PullSymbol.prototype.isPrimitive = function () { + return this.declKind === 2 /* Primitive */; + }; + + PullSymbol.prototype.isAccessor = function () { + return false; + }; + + PullSymbol.prototype.isError = function () { + return false; + }; + + PullSymbol.prototype.isAlias = function () { + return false; + }; + PullSymbol.prototype.isContainer = function () { + return false; + }; + + PullSymbol.prototype.findAliasedType = function (decls) { + for (var i = 0; i < decls.length; i++) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; j++) { + if (childDecls[j].getKind() === 256 /* TypeAlias */) { + var symbol = childDecls[j].getSymbol(); + if (PullContainerTypeSymbol.usedAsSymbol(symbol, this)) { + return symbol; + } + } + } + } + + return null; + }; + + PullSymbol.prototype.getAliasedSymbol = function (scopeSymbol) { + if (!scopeSymbol) { + return null; + } + + var scopePath = scopeSymbol.pathToRoot(); + if (scopePath.length && scopePath[scopePath.length - 1].getKind() === 32 /* DynamicModule */) { + var decls = scopePath[scopePath.length - 1].getDeclarations(); + var symbol = this.findAliasedType(decls); + return symbol; + } + + return null; + }; + + PullSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var symbol = this.getAliasedSymbol(scopeSymbol); + if (symbol) { + return symbol.getName(); + } + + return this.name; + }; + + PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName) { + var symbol = this.getAliasedSymbol(scopeSymbol); + if (symbol) { + return symbol.getDisplayName(); + } + + return this.getDeclarations()[0].getDisplayName(); + }; + + PullSymbol.prototype.getKind = function () { + return this.declKind; + }; + PullSymbol.prototype.setKind = function (declType) { + this.declKind = declType; + }; + + PullSymbol.prototype.setIsOptional = function () { + this.isOptional = true; + }; + PullSymbol.prototype.getIsOptional = function () { + return this.isOptional; + }; + + PullSymbol.prototype.getIsVarArg = function () { + return this.isVarArg; + }; + PullSymbol.prototype.setIsVarArg = function () { + this.isVarArg = true; + }; + + PullSymbol.prototype.setIsSynthesized = function () { + this.isSynthesized = true; + }; + PullSymbol.prototype.getIsSynthesized = function () { + return this.isSynthesized; + }; + + PullSymbol.prototype.setIsSpecialized = function () { + this.isSpecialized = true; + this.isBeingSpecialized = false; + }; + PullSymbol.prototype.getIsSpecialized = function () { + return this.isSpecialized; + }; + PullSymbol.prototype.currentlyBeingSpecialized = function () { + return this.isBeingSpecialized; + }; + PullSymbol.prototype.setIsBeingSpecialized = function () { + this.isBeingSpecialized = true; + }; + PullSymbol.prototype.setValueIsBeingSpecialized = function (val) { + this.isBeingSpecialized = val; + }; + + PullSymbol.prototype.getRootSymbol = function () { + if (!this.rootSymbol) { + return this; + } + return this.rootSymbol; + }; + PullSymbol.prototype.setRootSymbol = function (symbol) { + this.rootSymbol = symbol; + }; + + PullSymbol.prototype.setIsBound = function (rebindingID) { + this.isBound = true; + this.rebindingID = rebindingID; + }; + + PullSymbol.prototype.getRebindingID = function () { + return this.rebindingID; + }; + + PullSymbol.prototype.getIsBound = function () { + return this.isBound; + }; + + PullSymbol.prototype.addCacheID = function (cacheID) { + if (!this.cachedPathIDs[cacheID]) { + this.cachedPathIDs[cacheID] = true; + } + }; + + PullSymbol.prototype.invalidateCachedIDs = function (cache) { + for (var id in this.cachedPathIDs) { + if (cache[id]) { + cache[id] = undefined; + } + } + }; + + PullSymbol.prototype.addDeclaration = function (decl) { + TypeScript.Debug.assert(!!decl); + + if (this.rootSymbol) { + return; + } + + this.declarations.addItem(decl); + + if (!this.cachedDeclarations) { + this.cachedDeclarations = [decl]; + } else { + this.cachedDeclarations[this.cachedDeclarations.length] = decl; + } + }; + + PullSymbol.prototype.getDeclarations = function () { + if (this.rootSymbol) { + return this.rootSymbol.getDeclarations(); + } + + if (!this.cachedDeclarations) { + this.cachedDeclarations = []; + } + + return this.cachedDeclarations; + }; + + PullSymbol.prototype.removeDeclaration = function (decl) { + if (this.rootSymbol) { + return; + } + + this.declarations.remove(function (d) { + return d === decl; + }); + this.cachedDeclarations = this.declarations.find(function (d) { + return d; + }); + }; + + PullSymbol.prototype.updateDeclarations = function (map, context) { + if (this.rootSymbol) { + return; + } + + this.declarations.update(map, context); + }; + + PullSymbol.prototype.addOutgoingLink = function (linkTo, kind) { + var link = new TypeScript.PullSymbolLink(this, linkTo, kind); + this.outgoingLinks.addItem(link); + linkTo.incomingLinks.addItem(link); + + return link; + }; + + PullSymbol.prototype.findOutgoingLinks = function (p) { + return this.outgoingLinks.find(p); + }; + + PullSymbol.prototype.findIncomingLinks = function (p) { + return this.incomingLinks.find(p); + }; + + PullSymbol.prototype.removeOutgoingLink = function (link) { + if (link) { + this.outgoingLinks.remove(function (p) { + return p === link; + }); + + if (link.end.incomingLinks) { + link.end.incomingLinks.remove(function (p) { + return p === link; + }); + } + } + }; + + PullSymbol.prototype.updateOutgoingLinks = function (map, context) { + if (this.outgoingLinks) { + this.outgoingLinks.update(map, context); + } + }; + + PullSymbol.prototype.updateIncomingLinks = function (map, context) { + if (this.incomingLinks) { + this.incomingLinks.update(map, context); + } + }; + + PullSymbol.prototype.removeAllLinks = function () { + var _this = this; + this.updateOutgoingLinks(function (item) { + return _this.removeOutgoingLink(item); + }, null); + this.updateIncomingLinks(function (item) { + return item.start.removeOutgoingLink(item); + }, null); + }; + + PullSymbol.prototype.setContainer = function (containerSymbol) { + var link = this.addOutgoingLink(containerSymbol, 10 /* ContainedBy */); + this.cachedContainerLink = link; + + containerSymbol.addContainedByLink(link); + }; + + PullSymbol.prototype.getContainer = function () { + if (this.cachedContainerLink) { + return this.cachedContainerLink.end; + } + + if (this.getIsSpecialized()) { + var specializations = this.findIncomingLinks(function (symbolLink) { + return symbolLink.kind == 21 /* SpecializedTo */; + }); + if (specializations.length == 1) { + return specializations[0].start.getContainer(); + } + } + + return null; + }; + + PullSymbol.prototype.unsetContainer = function () { + if (this.cachedContainerLink) { + this.removeOutgoingLink(this.cachedContainerLink); + } + + this.invalidate(); + }; + + PullSymbol.prototype.setType = function (typeRef) { + if (this.cachedTypeLink) { + this.unsetType(); + } + + this.cachedTypeLink = this.addOutgoingLink(typeRef, 0 /* TypedAs */); + }; + + PullSymbol.prototype.getType = function () { + if (this.cachedTypeLink) { + return this.cachedTypeLink.end; + } + + return null; + }; + + PullSymbol.prototype.unsetType = function () { + var foundType = false; + + if (this.cachedTypeLink) { + this.removeOutgoingLink(this.cachedTypeLink); + foundType = true; + } + + if (foundType) { + this.invalidate(); + } + }; + + PullSymbol.prototype.isTyped = function () { + return this.getType() != null; + }; + + PullSymbol.prototype.setResolved = function () { + this.hasBeenResolved = true; + this.inResolution = false; + }; + PullSymbol.prototype.isResolved = function () { + return this.hasBeenResolved; + }; + + PullSymbol.prototype.startResolving = function () { + this.inResolution = true; + }; + PullSymbol.prototype.isResolving = function () { + return this.inResolution; + }; + + PullSymbol.prototype.setUnresolved = function () { + this.hasBeenResolved = false; + this.isBound = false; + this.inResolution = false; + }; + + PullSymbol.prototype.invalidate = function () { + this.docComments = null; + + this.hasBeenResolved = false; + this.isBound = false; + + this.declarations.update(function (pullDecl) { + return pullDecl.resetErrors(); + }, null); + }; + + PullSymbol.prototype.hasFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if ((declarations[i].getFlags() & flag) !== 0 /* None */) { + return true; + } + } + return false; + }; + + PullSymbol.prototype.allDeclsHaveFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (!((declarations[i].getFlags() & flag) !== 0 /* None */)) { + return false; + } + } + return true; + }; + + PullSymbol.prototype.pathToRoot = function () { + var path = []; + var node = this; + while (node) { + if (node.isType()) { + var associatedContainerSymbol = (node).getAssociatedContainerType(); + if (associatedContainerSymbol) { + node = associatedContainerSymbol; + } + } + path[path.length] = node; + node = node.getContainer(); + } + return path; + }; + + PullSymbol.prototype.findCommonAncestorPath = function (b) { + var aPath = this.pathToRoot(); + if (aPath.length === 1) { + return aPath; + } + + var bPath; + if (b) { + bPath = b.pathToRoot(); + } else { + return aPath; + } + + var commonNodeIndex = -1; + for (var i = 0, aLen = aPath.length; i < aLen; i++) { + var aNode = aPath[i]; + for (var j = 0, bLen = bPath.length; j < bLen; j++) { + var bNode = bPath[j]; + if (aNode === bNode) { + var aDecl = null; + if (i > 0) { + var decls = aPath[i - 1].getDeclarations(); + if (decls.length) { + aDecl = decls[0].getParentDecl(); + } + } + var bDecl = null; + if (j > 0) { + var decls = bPath[j - 1].getDeclarations(); + if (decls.length) { + bDecl = decls[0].getParentDecl(); + } + } + if (!aDecl || !bDecl || aDecl == bDecl) { + commonNodeIndex = i; + break; + } + } + } + if (commonNodeIndex >= 0) { + break; + } + } + + if (commonNodeIndex >= 0) { + return aPath.slice(0, commonNodeIndex); + } else { + return aPath; + } + }; + + PullSymbol.prototype.toString = function (useConstraintInName) { + var str = this.getNameAndTypeName(); + return str; + }; + + PullSymbol.prototype.getNamePartForFullName = function () { + return this.getDisplayName(null, true); + }; + + PullSymbol.prototype.fullName = function (scopeSymbol) { + var path = this.pathToRoot(); + var fullName = ""; + var aliasedSymbol = this.getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + return aliasedSymbol.getDisplayName(); + } + + for (var i = 1; i < path.length; i++) { + aliasedSymbol = path[i].getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + fullName = aliasedSymbol.getDisplayName() + "." + fullName; + break; + } else { + var scopedName = path[i].getNamePartForFullName(); + if (path[i].getKind() == 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + break; + } + + if (scopedName === "") { + break; + } + + fullName = scopedName + "." + fullName; + } + } + + fullName = fullName + this.getNamePartForFullName(); + return fullName; + }; + + PullSymbol.prototype.getScopedName = function (scopeSymbol, useConstraintInName) { + var path = this.findCommonAncestorPath(scopeSymbol); + var fullName = ""; + var aliasedSymbol = this.getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + return aliasedSymbol.getDisplayName(); + } + + for (var i = 1; i < path.length; i++) { + var kind = path[i].getKind(); + if (kind === 4 /* Container */ || kind === 32 /* DynamicModule */) { + aliasedSymbol = path[i].getAliasedSymbol(scopeSymbol); + if (aliasedSymbol) { + fullName = aliasedSymbol.getDisplayName() + "." + fullName; + break; + } else if (kind === 4 /* Container */) { + fullName = path[i].getDisplayName() + "." + fullName; + } else { + var displayName = path[i].getDisplayName(); + if (TypeScript.isQuoted(displayName)) { + fullName = displayName + "." + fullName; + } + break; + } + } else { + break; + } + } + fullName = fullName + this.getDisplayName(scopeSymbol, useConstraintInName); + return fullName; + }; + + PullSymbol.prototype.getScopedNameEx = function (scopeSymbol, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo) { + var name = this.getScopedName(scopeSymbol, useConstraintInName); + return TypeScript.MemberName.create(name); + }; + + PullSymbol.prototype.getTypeName = function (scopeSymbol, getPrettyTypeName) { + var memberName = this.getTypeNameEx(scopeSymbol, getPrettyTypeName); + return memberName.toString(); + }; + + PullSymbol.prototype.getTypeNameEx = function (scopeSymbol, getPrettyTypeName) { + var type = this.getType(); + if (type) { + var memberName = getPrettyTypeName ? this.getTypeNameForFunctionSignature("", scopeSymbol, getPrettyTypeName) : null; + if (!memberName) { + memberName = type.getScopedNameEx(scopeSymbol, true, getPrettyTypeName); + } + + return memberName; + } + return TypeScript.MemberName.create(""); + }; + + PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { + var type = this.getType(); + if (type && !type.isNamedTypeSymbol() && this.declKind != 4096 /* Property */ && this.declKind != 1024 /* Variable */ && this.declKind != 2048 /* Parameter */) { + var signatures = type.getCallSignatures(); + var typeName = new TypeScript.MemberNameArray(); + var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); + typeName.addAll(signatureName); + return typeName; + } + + return null; + }; + + PullSymbol.prototype.getNameAndTypeName = function (scopeSymbol) { + var nameAndTypeName = this.getNameAndTypeNameEx(scopeSymbol); + return nameAndTypeName.toString(); + }; + + PullSymbol.prototype.getNameAndTypeNameEx = function (scopeSymbol) { + var type = this.getType(); + var nameEx = this.getScopedNameEx(scopeSymbol); + if (type) { + var nameStr = nameEx.toString() + (this.getIsOptional() ? "?" : ""); + var memberName = this.getTypeNameForFunctionSignature(nameStr, scopeSymbol); + if (!memberName) { + var typeNameEx = type.getScopedNameEx(scopeSymbol); + memberName = TypeScript.MemberName.create(typeNameEx, nameStr + ": ", ""); + } + return memberName; + } + return nameEx; + }; + + PullSymbol.getTypeParameterString = function (typars, scopeSymbol, useContraintInName) { + return PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, undefined, useContraintInName).toString(); + }; + + PullSymbol.getTypeParameterStringEx = function (typeParameters, scopeSymbol, getTypeParamMarkerInfo, useContraintInName) { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = ""; + + if (typeParameters && typeParameters.length) { + builder.add(TypeScript.MemberName.create("<")); + + for (var i = 0; i < typeParameters.length; i++) { + if (i) { + builder.add(TypeScript.MemberName.create(", ")); + } + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + + builder.add(typeParameters[i].getScopedNameEx(scopeSymbol, useContraintInName)); + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + } + + builder.add(TypeScript.MemberName.create(">")); + } + + return builder; + }; + + PullSymbol.getIsExternallyVisible = function (symbol, fromIsExternallyVisibleSymbol, inIsExternallyVisibleSymbols) { + if (inIsExternallyVisibleSymbols) { + for (var i = 0; i < inIsExternallyVisibleSymbols.length; i++) { + if (inIsExternallyVisibleSymbols[i] === symbol) { + return true; + } + } + } else { + inIsExternallyVisibleSymbols = []; + } + + if (fromIsExternallyVisibleSymbol === symbol) { + return true; + } + inIsExternallyVisibleSymbols = inIsExternallyVisibleSymbols.concat(fromIsExternallyVisibleSymbol); + + return symbol.isExternallyVisible(inIsExternallyVisibleSymbols); + }; + + PullSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var kind = this.getKind(); + if (kind === 2 /* Primitive */) { + return true; + } + + if (this.isType()) { + var associatedContainerSymbol = (this).getAssociatedContainerType(); + if (associatedContainerSymbol) { + return PullSymbol.getIsExternallyVisible(associatedContainerSymbol, this, inIsExternallyVisibleSymbols); + } + } + + if (this.hasFlag(2 /* Private */)) { + return false; + } + + var container = this.getContainer(); + if (container === null) { + return true; + } + + if (container.getKind() == 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().getKind() == 32 /* DynamicModule */)) { + var containerTypeSymbol = container.getKind() == 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (PullContainerTypeSymbol.usedAsSymbol(containerTypeSymbol, this)) { + return true; + } + } + + if (!this.hasFlag(1 /* Exported */) && kind != 4096 /* Property */ && kind != 65536 /* Method */) { + return false; + } + + return PullSymbol.getIsExternallyVisible(container, this, inIsExternallyVisibleSymbols); + }; + return PullSymbol; + })(); + TypeScript.PullSymbol = PullSymbol; + + var PullExpressionSymbol = (function (_super) { + __extends(PullExpressionSymbol, _super); + function PullExpressionSymbol() { + _super.call(this, "", 268435456 /* Expression */); + this.contributingSymbols = []; + } + PullExpressionSymbol.prototype.addContributingSymbol = function (symbol) { + var link = this.addOutgoingLink(symbol, 23 /* ContributesToExpression */); + + this.contributingSymbols[this.contributingSymbols.length] = symbol; + }; + + PullExpressionSymbol.prototype.getContributingSymbols = function () { + return this.contributingSymbols; + }; + return PullExpressionSymbol; + })(PullSymbol); + TypeScript.PullExpressionSymbol = PullExpressionSymbol; + + var PullSignatureSymbol = (function (_super) { + __extends(PullSignatureSymbol, _super); + function PullSignatureSymbol(kind) { + _super.call(this, "", kind); + this.parameterLinks = null; + this.typeParameterLinks = null; + this.returnTypeLink = null; + this.hasOptionalParam = false; + this.nonOptionalParamCount = 0; + this.hasVarArgs = false; + this.specializationCache = {}; + this.memberTypeParameterNameCache = null; + this.hasAGenericParameter = false; + this.stringConstantOverload = undefined; + } + PullSignatureSymbol.prototype.isDefinition = function () { + return false; + }; + + PullSignatureSymbol.prototype.hasVariableParamList = function () { + return this.hasVarArgs; + }; + PullSignatureSymbol.prototype.setHasVariableParamList = function () { + this.hasVarArgs = true; + }; + + PullSignatureSymbol.prototype.setHasGenericParameter = function () { + this.hasAGenericParameter = true; + }; + PullSignatureSymbol.prototype.hasGenericParameter = function () { + return this.hasAGenericParameter; + }; + + PullSignatureSymbol.prototype.isGeneric = function () { + return this.hasAGenericParameter || (this.typeParameterLinks && this.typeParameterLinks.length != 0); + }; + + PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { + if (typeof isOptional === "undefined") { isOptional = false; } + if (!this.parameterLinks) { + this.parameterLinks = []; + } + + var link = this.addOutgoingLink(parameter, 13 /* Parameter */); + this.parameterLinks[this.parameterLinks.length] = link; + this.hasOptionalParam = isOptional; + + if (!isOptional) { + this.nonOptionalParamCount++; + } + }; + + PullSignatureSymbol.prototype.addSpecialization = function (signature, typeArguments) { + if (typeArguments && typeArguments.length) { + this.specializationCache[getIDForTypeSubstitutions(typeArguments)] = signature; + } + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArguments) { + if (typeArguments) { + var sig = this.specializationCache[getIDForTypeSubstitutions(typeArguments)]; + + if (sig) { + return sig; + } + } + + return null; + }; + + PullSignatureSymbol.prototype.addTypeParameter = function (parameter) { + if (!this.typeParameterLinks) { + this.typeParameterLinks = []; + } + + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + } + + var link = this.addOutgoingLink(parameter, 18 /* TypeParameter */); + this.typeParameterLinks[this.typeParameterLinks.length] = link; + + this.memberTypeParameterNameCache[link.end.getName()] = link.end; + }; + + PullSignatureSymbol.prototype.getNonOptionalParameterCount = function () { + return this.nonOptionalParamCount; + }; + + PullSignatureSymbol.prototype.setReturnType = function (returnType) { + if (returnType) { + if (this.returnTypeLink) { + this.removeOutgoingLink(this.returnTypeLink); + } + this.returnTypeLink = this.addOutgoingLink(returnType, 14 /* ReturnType */); + } + }; + + PullSignatureSymbol.prototype.getParameters = function () { + var params = []; + + if (this.parameterLinks) { + for (var i = 0; i < this.parameterLinks.length; i++) { + params[params.length] = this.parameterLinks[i].end; + } + } + + return params; + }; + + PullSignatureSymbol.prototype.getTypeParameters = function () { + var params = []; + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + params[params.length] = this.typeParameterLinks[i].end; + } + } + + return params; + }; + + PullSignatureSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + this.memberTypeParameterNameCache[this.typeParameterLinks[i].end.getName()] = this.typeParameterLinks[i].end; + } + } + } + + memberSymbol = this.memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullSignatureSymbol.prototype.removeParameter = function (parameterSymbol) { + var paramLink; + + if (this.parameterLinks) { + for (var i = 0; i < this.parameterLinks.length; i++) { + if (parameterSymbol === this.parameterLinks[i].end) { + paramLink = this.parameterLinks[i]; + this.removeOutgoingLink(paramLink); + break; + } + } + } + + this.invalidate(); + }; + + PullSignatureSymbol.prototype.mimicSignature = function (signature, resolver) { + var typeParameters = signature.getTypeParameters(); + var typeParameter; + + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + } + + var parameters = signature.getParameters(); + var parameter; + + if (parameters) { + for (var j = 0; j < parameters.length; j++) { + parameter = new PullSymbol(parameters[j].getName(), 2048 /* Parameter */); + parameter.setRootSymbol(parameters[j]); + + if (parameters[j].getIsOptional()) { + parameter.setIsOptional(); + } + if (parameters[j].getIsVarArg()) { + parameter.setIsVarArg(); + this.setHasVariableParamList(); + } + this.addParameter(parameter); + } + } + + var returnType = signature.getReturnType(); + + if (!resolver.isTypeArgumentOrWrapper(returnType)) { + this.setReturnType(returnType); + } + }; + + PullSignatureSymbol.prototype.getReturnType = function () { + if (this.returnTypeLink) { + return this.returnTypeLink.end; + } else { + var rtl = this.findOutgoingLinks(function (p) { + return p.kind === 14 /* ReturnType */; + }); + + if (rtl.length) { + this.returnTypeLink = rtl[0]; + return this.returnTypeLink.end; + } + + return null; + } + }; + + PullSignatureSymbol.prototype.parametersAreFixed = function () { + if (!this.isGeneric()) { + return true; + } + + if (this.parameterLinks) { + var paramType; + for (var i = 0; i < this.parameterLinks.length; i++) { + paramType = this.parameterLinks[i].end.getType(); + + if (paramType && !paramType.isFixed()) { + return false; + } + } + } + + return true; + }; + + PullSignatureSymbol.prototype.isFixed = function () { + if (!this.isGeneric()) { + return true; + } + + if (this.parameterLinks) { + var parameterType = null; + + for (var i = 0; i < this.parameterLinks.length; i++) { + parameterType = this.parameterLinks[i].end.getType(); + + if (parameterType && !parameterType.isFixed()) { + return false; + } + } + } + + if (this.returnTypeLink) { + var returnType = this.returnTypeLink.end; + + return returnType.isFixed(); + } + + return true; + }; + + PullSignatureSymbol.prototype.invalidate = function () { + this.parameterLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 13 /* Parameter */; + }); + this.nonOptionalParamCount = 0; + this.hasOptionalParam = false; + this.hasAGenericParameter = false; + this.stringConstantOverload = undefined; + + if (this.parameterLinks) { + for (var i = 0; i < this.parameterLinks.length; i++) { + this.parameterLinks[i].end.invalidate(); + + if (!this.parameterLinks[i].end.getIsOptional()) { + this.nonOptionalParamCount++; + } else { + this.hasOptionalParam; + break; + } + } + } + + _super.prototype.invalidate.call(this); + }; + + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { + if (this.stringConstantOverload === undefined) { + var params = this.getParameters(); + this.stringConstantOverload = false; + for (var i = 0; i < params.length; i++) { + var paramType = params[i].getType(); + if (paramType && paramType.isPrimitive() && (paramType).isStringConstant()) { + this.stringConstantOverload = true; + } + } + } + + return this.stringConstantOverload; + }; + + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { + var allMemberNames = new TypeScript.MemberNameArray(); + var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); + allMemberNames.addAll(signatureMemberName); + return allMemberNames; + }; + + PullSignatureSymbol.getSignaturesTypeNameEx = function (signatures, prefix, shortform, brackets, scopeSymbol, getPrettyTypeName, candidateSignature) { + var result = []; + var len = signatures.length; + if (!getPrettyTypeName && len > 1) { + shortform = false; + } + + var foundDefinition = false; + if (candidateSignature && candidateSignature.isDefinition() && len > 1) { + candidateSignature = null; + } + + for (var i = 0; i < len; i++) { + if (len > 1 && signatures[i].isDefinition()) { + foundDefinition = true; + continue; + } + + var signature = signatures[i]; + if (getPrettyTypeName && candidateSignature) { + signature = candidateSignature; + } + + result.push(signature.getSignatureTypeNameEx(prefix, shortform, brackets, scopeSymbol)); + if (getPrettyTypeName) { + break; + } + } + + if (getPrettyTypeName && result.length && len > 1) { + var lastMemberName = result[result.length - 1]; + for (var i = i + 1; i < len; i++) { + if (signatures[i].isDefinition()) { + foundDefinition = true; + break; + } + } + var overloadString = " (+ " + (foundDefinition ? len - 2 : len - 1) + " overload(s))"; + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + + return result; + }; + + PullSignatureSymbol.prototype.toString = function (useConstraintInName) { + var s = this.getSignatureTypeNameEx(this.getScopedNameEx().toString(), false, false, undefined, undefined, useConstraintInName).toString(); + return s; + }; + + PullSignatureSymbol.prototype.getSignatureTypeNameEx = function (prefix, shortform, brackets, scopeSymbol, getParamMarkerInfo, getTypeParamMarkerInfo) { + var typeParamterBuilder = new TypeScript.MemberNameArray(); + + typeParamterBuilder.add(PullSymbol.getTypeParameterStringEx(this.getTypeParameters(), scopeSymbol, getTypeParamMarkerInfo, true)); + + if (brackets) { + typeParamterBuilder.add(TypeScript.MemberName.create("[")); + } else { + typeParamterBuilder.add(TypeScript.MemberName.create("(")); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = prefix; + + if (getTypeParamMarkerInfo) { + builder.prefix = prefix; + builder.addAll(typeParamterBuilder.entries); + } else { + builder.prefix = prefix + typeParamterBuilder.toString(); + } + + var params = this.getParameters(); + var paramLen = params.length; + for (var i = 0; i < paramLen; i++) { + var paramType = params[i].getType(); + var typeString = paramType ? ": " : ""; + var paramIsVarArg = params[i].getIsVarArg(); + var varArgPrefix = paramIsVarArg ? "..." : ""; + var optionalString = (!paramIsVarArg && params[i].getIsOptional()) ? "?" : ""; + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + builder.add(TypeScript.MemberName.create(varArgPrefix + params[i].getScopedNameEx(scopeSymbol).toString() + optionalString + typeString)); + if (paramType) { + builder.add(paramType.getScopedNameEx(scopeSymbol)); + } + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + if (i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + + if (shortform) { + if (brackets) { + builder.add(TypeScript.MemberName.create("] => ")); + } else { + builder.add(TypeScript.MemberName.create(") => ")); + } + } else { + if (brackets) { + builder.add(TypeScript.MemberName.create("]: ")); + } else { + builder.add(TypeScript.MemberName.create("): ")); + } + } + + var returnType = this.getReturnType(); + + if (returnType) { + builder.add(returnType.getScopedNameEx(scopeSymbol)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + + return builder; + }; + return PullSignatureSymbol; + })(PullSymbol); + TypeScript.PullSignatureSymbol = PullSignatureSymbol; + + var PullTypeSymbol = (function (_super) { + __extends(PullTypeSymbol, _super); + function PullTypeSymbol() { + _super.apply(this, arguments); + this.memberLinks = null; + this.typeParameterLinks = null; + this.specializationLinks = null; + this.containedByLinks = null; + this.memberNameCache = null; + this.memberTypeNameCache = null; + this.memberTypeParameterNameCache = null; + this.containedMemberCache = null; + this.typeArguments = null; + this.specializedTypeCache = null; + this.memberCache = null; + this.implementedTypeLinks = null; + this.extendedTypeLinks = null; + this.callSignatureLinks = null; + this.constructSignatureLinks = null; + this.indexSignatureLinks = null; + this.arrayType = null; + this.hasGenericSignature = false; + this.hasGenericMember = false; + this.knownBaseTypeCount = 0; + this._hasBaseTypeConflict = false; + this.invalidatedSpecializations = false; + this.associatedContainerTypeSymbol = null; + this.constructorMethod = null; + this.hasDefaultConstructor = false; + } + PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { + return this.knownBaseTypeCount; + }; + PullTypeSymbol.prototype.resetKnownBaseTypeCount = function () { + this.knownBaseTypeCount = 0; + }; + PullTypeSymbol.prototype.incrementKnownBaseCount = function () { + this.knownBaseTypeCount++; + }; + PullTypeSymbol.prototype.setHasBaseTypeConflict = function () { + this._hasBaseTypeConflict = true; + }; + PullTypeSymbol.prototype.hasBaseTypeConflict = function () { + return this._hasBaseTypeConflict; + }; + + PullTypeSymbol.prototype.setUnresolved = function () { + _super.prototype.setUnresolved.call(this); + + var specializations = this.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].setUnresolved(); + } + }; + + PullTypeSymbol.prototype.isType = function () { + return true; + }; + PullTypeSymbol.prototype.isClass = function () { + return this.getKind() == 8 /* Class */ || (this.constructorMethod != null); + }; + + PullTypeSymbol.prototype.hasMembers = function () { + var thisHasMembers = this.memberLinks && this.memberLinks.length != 0; + + if (thisHasMembers) { + return true; + } + + var parents = this.getExtendedTypes(); + + for (var i = 0; i < parents.length; i++) { + if (parents[i].hasMembers()) { + return true; + } + } + + return false; + }; + PullTypeSymbol.prototype.isFunction = function () { + return false; + }; + PullTypeSymbol.prototype.isConstructor = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeParameter = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeVariable = function () { + return false; + }; + PullTypeSymbol.prototype.isError = function () { + return false; + }; + + PullTypeSymbol.prototype.setHasGenericSignature = function () { + this.hasGenericSignature = true; + }; + PullTypeSymbol.prototype.getHasGenericSignature = function () { + return this.hasGenericSignature; + }; + + PullTypeSymbol.prototype.setHasGenericMember = function () { + this.hasGenericMember = true; + }; + PullTypeSymbol.prototype.getHasGenericMember = function () { + return this.hasGenericMember; + }; + + PullTypeSymbol.prototype.setAssociatedContainerType = function (type) { + this.associatedContainerTypeSymbol = type; + }; + + PullTypeSymbol.prototype.getAssociatedContainerType = function () { + return this.associatedContainerTypeSymbol; + }; + + PullTypeSymbol.prototype.getType = function () { + return this; + }; + + PullTypeSymbol.prototype.getArrayType = function () { + return this.arrayType; + }; + + PullTypeSymbol.prototype.getElementType = function () { + var arrayOfLinks = this.findOutgoingLinks(function (link) { + return link.kind === 4 /* ArrayOf */; + }); + + if (arrayOfLinks.length) { + return arrayOfLinks[0].end; + } + + return null; + }; + PullTypeSymbol.prototype.setArrayType = function (arrayType) { + this.arrayType = arrayType; + + arrayType.addOutgoingLink(this, 4 /* ArrayOf */); + }; + + PullTypeSymbol.prototype.addContainedByLink = function (containedByLink) { + if (!this.containedByLinks) { + this.containedByLinks = []; + } + + if (!this.containedMemberCache) { + this.containedMemberCache = new TypeScript.BlockIntrinsics(); + } + + this.containedByLinks[this.containedByLinks.length] = containedByLink; + this.containedMemberCache[containedByLink.start.getName()] = containedByLink.start; + }; + + PullTypeSymbol.prototype.findContainedMember = function (name) { + if (!this.containedByLinks) { + this.containedByLinks = this.findIncomingLinks(function (psl) { + return psl.kind === 10 /* ContainedBy */; + }); + this.containedMemberCache = new TypeScript.BlockIntrinsics(); + + for (var i = 0; i < this.containedByLinks.length; i++) { + this.containedMemberCache[this.containedByLinks[i].start.getName()] = this.containedByLinks[i].start; + } + } + + return this.containedMemberCache[name]; + }; + + PullTypeSymbol.prototype.addMember = function (memberSymbol, linkKind, doNotChangeContainer) { + var link = this.addOutgoingLink(memberSymbol, linkKind); + + if (!doNotChangeContainer) { + memberSymbol.setContainer(this); + } + + if (!this.memberLinks) { + this.memberLinks = []; + } + + if (!this.memberCache || !this.memberNameCache) { + this.populateMemberCache(); + } + + if (!memberSymbol.isType()) { + this.memberLinks[this.memberLinks.length] = link; + + this.memberCache[this.memberCache.length] = memberSymbol; + + if (!this.memberNameCache) { + this.populateMemberCache(); + } + this.memberNameCache[memberSymbol.getName()] = memberSymbol; + } else { + if ((memberSymbol).isTypeParameter()) { + if (!this.typeParameterLinks) { + this.typeParameterLinks = []; + } + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + } + this.typeParameterLinks[this.typeParameterLinks.length] = link; + this.memberTypeParameterNameCache[memberSymbol.getName()] = memberSymbol; + } else { + if (!this.memberTypeNameCache) { + this.memberTypeNameCache = new TypeScript.BlockIntrinsics(); + } + this.memberLinks[this.memberLinks.length] = link; + this.memberTypeNameCache[memberSymbol.getName()] = memberSymbol; + this.memberCache[this.memberCache.length] = memberSymbol; + } + } + }; + + PullTypeSymbol.prototype.removeMember = function (memberSymbol) { + var memberLink; + var child; + + var links = (memberSymbol.isType() && (memberSymbol).isTypeParameter()) ? this.typeParameterLinks : this.memberLinks; + + if (links) { + for (var i = 0; i < links.length; i++) { + if (memberSymbol === links[i].end) { + memberLink = links[i]; + child = memberLink.end; + child.unsetContainer(); + this.removeOutgoingLink(memberLink); + break; + } + } + } + + this.invalidate(); + }; + + PullTypeSymbol.prototype.getMembers = function () { + if (this.memberCache) { + return this.memberCache; + } else { + var members = []; + + if (this.memberLinks) { + for (var i = 0; i < this.memberLinks.length; i++) { + members[members.length] = this.memberLinks[i].end; + } + } + + if (members.length) { + this.memberCache = members; + } + + return members; + } + }; + + PullTypeSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + this.hasDefaultConstructor = hasOne; + }; + + PullTypeSymbol.prototype.getHasDefaultConstructor = function () { + return this.hasDefaultConstructor; + }; + + PullTypeSymbol.prototype.getConstructorMethod = function () { + return this.constructorMethod; + }; + + PullTypeSymbol.prototype.setConstructorMethod = function (constructorMethod) { + this.constructorMethod = constructorMethod; + }; + + PullTypeSymbol.prototype.getTypeParameters = function () { + var members = []; + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + members[members.length] = this.typeParameterLinks[i].end; + } + } + + return members; + }; + + PullTypeSymbol.prototype.isGeneric = function () { + return (this.typeParameterLinks && this.typeParameterLinks.length != 0) || this.hasGenericSignature || this.hasGenericMember || (this.typeArguments && this.typeArguments.length); + }; + + PullTypeSymbol.prototype.isFixed = function () { + if (!this.isGeneric()) { + return true; + } + + if (this.typeParameterLinks && this.typeArguments) { + if (!this.typeArguments.length || this.typeArguments.length < this.typeParameterLinks.length) { + return false; + } + + for (var i = 0; i < this.typeArguments.length; i++) { + if (!this.typeArguments[i].isFixed()) { + return false; + } + } + + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { + if (!substitutingTypes || !substitutingTypes.length) { + return; + } + + if (!this.specializedTypeCache) { + this.specializedTypeCache = new TypeScript.BlockIntrinsics(); + } + + if (!this.specializationLinks) { + this.specializationLinks = []; + } + + this.specializationLinks[this.specializationLinks.length] = this.addOutgoingLink(specializedVersionOfThisType, 21 /* SpecializedTo */); + + this.specializedTypeCache[getIDForTypeSubstitutions(substitutingTypes)] = specializedVersionOfThisType; + }; + + PullTypeSymbol.prototype.getSpecialization = function (substitutingTypes) { + if (!substitutingTypes || !substitutingTypes.length) { + return null; + } + + if (!this.specializedTypeCache) { + this.specializedTypeCache = new TypeScript.BlockIntrinsics(); + + return null; + } + + var specialization = this.specializedTypeCache[getIDForTypeSubstitutions(substitutingTypes)]; + + if (!specialization) { + return null; + } + + return specialization; + }; + + PullTypeSymbol.prototype.getKnownSpecializations = function () { + var specializations = []; + + if (this.specializedTypeCache) { + for (var specializationID in this.specializedTypeCache) { + if (this.specializedTypeCache[specializationID]) { + specializations[specializations.length] = this.specializedTypeCache[specializationID]; + } + } + } + + return specializations; + }; + + PullTypeSymbol.prototype.invalidateSpecializations = function () { + if (this.invalidatedSpecializations) { + return; + } + + var specializations = this.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + + if (this.specializationLinks && this.specializationLinks.length) { + for (var i = 0; i < this.specializationLinks.length; i++) { + this.removeOutgoingLink(this.specializationLinks[i]); + } + } + + this.specializationLinks = null; + + this.specializedTypeCache = null; + + this.invalidatedSpecializations = true; + }; + + PullTypeSymbol.prototype.removeSpecialization = function (specializationType) { + if (this.specializationLinks && this.specializationLinks.length) { + for (var i = 0; i < this.specializationLinks.length; i++) { + if (this.specializationLinks[i].end === specializationType) { + this.removeOutgoingLink(this.specializationLinks[i]); + break; + } + } + } + + if (this.specializedTypeCache) { + for (var specializationID in this.specializedTypeCache) { + if (this.specializedTypeCache[specializationID] === specializationType) { + this.specializedTypeCache[specializationID] = undefined; + } + } + } + }; + + PullTypeSymbol.prototype.getTypeArguments = function () { + return this.typeArguments; + }; + PullTypeSymbol.prototype.setTypeArguments = function (typeArgs) { + this.typeArguments = typeArgs; + }; + + PullTypeSymbol.prototype.addCallSignature = function (callSignature) { + if (!this.callSignatureLinks) { + this.callSignatureLinks = []; + } + + var link = this.addOutgoingLink(callSignature, 15 /* CallSignature */); + this.callSignatureLinks[this.callSignatureLinks.length] = link; + + if (callSignature.isGeneric()) { + this.hasGenericSignature = true; + } + }; + + PullTypeSymbol.prototype.addCallSignatures = function (callSignatures) { + if (!this.callSignatureLinks) { + this.callSignatureLinks = []; + } + + for (var i = 0; i < callSignatures.length; i++) { + this.addCallSignature(callSignatures[i]); + } + }; + + PullTypeSymbol.prototype.addConstructSignature = function (constructSignature) { + if (!this.constructSignatureLinks) { + this.constructSignatureLinks = []; + } + + var link = this.addOutgoingLink(constructSignature, 16 /* ConstructSignature */); + this.constructSignatureLinks[this.constructSignatureLinks.length] = link; + + if (constructSignature.isGeneric()) { + this.hasGenericSignature = true; + } + }; + + PullTypeSymbol.prototype.addConstructSignatures = function (constructSignatures) { + if (!this.constructSignatureLinks) { + this.constructSignatureLinks = []; + } + + for (var i = 0; i < constructSignatures.length; i++) { + this.addConstructSignature(constructSignatures[i]); + } + }; + + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { + if (!this.indexSignatureLinks) { + this.indexSignatureLinks = []; + } + + var link = this.addOutgoingLink(indexSignature, 17 /* IndexSignature */); + this.indexSignatureLinks[this.indexSignatureLinks.length] = link; + + if (indexSignature.isGeneric()) { + this.hasGenericSignature = true; + } + }; + + PullTypeSymbol.prototype.addIndexSignatures = function (indexSignatures) { + if (!this.indexSignatureLinks) { + this.indexSignatureLinks = []; + } + + for (var i = 0; i < indexSignatures.length; i++) { + this.addIndexSignature(indexSignatures[i]); + } + }; + + PullTypeSymbol.prototype.hasOwnCallSignatures = function () { + return !!this.callSignatureLinks; + }; + + PullTypeSymbol.prototype.getCallSignatures = function (collectBaseSignatures) { + if (typeof collectBaseSignatures === "undefined") { collectBaseSignatures = true; } + var members = []; + + if (this.callSignatureLinks) { + for (var i = 0; i < this.callSignatureLinks.length; i++) { + members[members.length] = this.callSignatureLinks[i].end; + } + } + + if (collectBaseSignatures) { + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(this)) { + continue; + } + members = members.concat(extendedTypes[i].getCallSignatures()); + } + } + + return members; + }; + + PullTypeSymbol.prototype.hasOwnConstructSignatures = function () { + return !!this.constructSignatureLinks; + }; + + PullTypeSymbol.prototype.getConstructSignatures = function (collectBaseSignatures) { + if (typeof collectBaseSignatures === "undefined") { collectBaseSignatures = true; } + var members = []; + + if (this.constructSignatureLinks) { + for (var i = 0; i < this.constructSignatureLinks.length; i++) { + members[members.length] = this.constructSignatureLinks[i].end; + } + } + + if (collectBaseSignatures) { + if (!(this.getKind() == 33554432 /* ConstructorType */)) { + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(this)) { + continue; + } + members = members.concat(extendedTypes[i].getConstructSignatures()); + } + } + } + + return members; + }; + + PullTypeSymbol.prototype.hasOwnIndexSignatures = function () { + return !!this.indexSignatureLinks; + }; + + PullTypeSymbol.prototype.getIndexSignatures = function (collectBaseSignatures) { + if (typeof collectBaseSignatures === "undefined") { collectBaseSignatures = true; } + var members = []; + + if (this.indexSignatureLinks) { + for (var i = 0; i < this.indexSignatureLinks.length; i++) { + members[members.length] = this.indexSignatureLinks[i].end; + } + } + + if (collectBaseSignatures) { + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(this)) { + continue; + } + members = members.concat(extendedTypes[i].getIndexSignatures()); + } + } + + return members; + }; + + PullTypeSymbol.prototype.removeCallSignature = function (signature, invalidate) { + if (typeof invalidate === "undefined") { invalidate = true; } + var signatureLink; + + if (this.callSignatureLinks) { + for (var i = 0; i < this.callSignatureLinks.length; i++) { + if (signature === this.callSignatureLinks[i].end) { + signatureLink = this.callSignatureLinks[i]; + this.removeOutgoingLink(signatureLink); + break; + } + } + } + + if (invalidate) { + this.invalidate(); + } + }; + + PullTypeSymbol.prototype.recomputeCallSignatures = function () { + this.callSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 15 /* CallSignature */; + }); + }; + + PullTypeSymbol.prototype.removeConstructSignature = function (signature, invalidate) { + if (typeof invalidate === "undefined") { invalidate = true; } + var signatureLink; + + if (this.constructSignatureLinks) { + for (var i = 0; i < this.constructSignatureLinks.length; i++) { + if (signature === this.constructSignatureLinks[i].end) { + signatureLink = this.constructSignatureLinks[i]; + this.removeOutgoingLink(signatureLink); + break; + } + } + } + + if (invalidate) { + this.invalidate(); + } + }; + + PullTypeSymbol.prototype.recomputeConstructSignatures = function () { + this.constructSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 16 /* ConstructSignature */; + }); + }; + + PullTypeSymbol.prototype.removeIndexSignature = function (signature, invalidate) { + if (typeof invalidate === "undefined") { invalidate = true; } + var signatureLink; + + if (this.indexSignatureLinks) { + for (var i = 0; i < this.indexSignatureLinks.length; i++) { + if (signature === this.indexSignatureLinks[i].end) { + signatureLink = this.indexSignatureLinks[i]; + this.removeOutgoingLink(signatureLink); + break; + } + } + } + + if (invalidate) { + this.invalidate(); + } + }; + + PullTypeSymbol.prototype.recomputeIndexSignatures = function () { + this.indexSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 17 /* IndexSignature */; + }); + }; + + PullTypeSymbol.prototype.addImplementedType = function (interfaceType) { + if (!this.implementedTypeLinks) { + this.implementedTypeLinks = []; + } + + var link = this.addOutgoingLink(interfaceType, 12 /* Implements */); + this.implementedTypeLinks[this.implementedTypeLinks.length] = link; + }; + + PullTypeSymbol.prototype.getImplementedTypes = function () { + var members = []; + + if (this.implementedTypeLinks) { + for (var i = 0; i < this.implementedTypeLinks.length; i++) { + members[members.length] = this.implementedTypeLinks[i].end; + } + } + + return members; + }; + + PullTypeSymbol.prototype.removeImplementedType = function (implementedType) { + var typeLink; + + if (this.implementedTypeLinks) { + for (var i = 0; i < this.implementedTypeLinks.length; i++) { + if (implementedType === this.implementedTypeLinks[i].end) { + typeLink = this.implementedTypeLinks[i]; + this.removeOutgoingLink(typeLink); + break; + } + } + } + + this.invalidate(); + }; + + PullTypeSymbol.prototype.addExtendedType = function (extendedType) { + if (!this.extendedTypeLinks) { + this.extendedTypeLinks = []; + } + + var link = this.addOutgoingLink(extendedType, 11 /* Extends */); + this.extendedTypeLinks[this.extendedTypeLinks.length] = link; + }; + + PullTypeSymbol.prototype.getExtendedTypes = function () { + var members = []; + + if (this.extendedTypeLinks) { + for (var i = 0; i < this.extendedTypeLinks.length; i++) { + members[members.length] = this.extendedTypeLinks[i].end; + } + } + + return members; + }; + + PullTypeSymbol.prototype.hasBase = function (potentialBase, origin) { + if (typeof origin === "undefined") { origin = null; } + if (this === potentialBase) { + return true; + } + + if (origin && (this === origin || this.getRootSymbol() === origin)) { + return true; + } + + if (!origin) { + origin = this; + } + + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(potentialBase, origin)) { + return true; + } + } + + var implementedTypes = this.getImplementedTypes(); + + for (var i = 0; i < implementedTypes.length; i++) { + if (implementedTypes[i].hasBase(potentialBase, origin)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + if (baseType.isError()) { + return false; + } + + var thisIsClass = this.isClass(); + if (isExtendedType) { + if (thisIsClass) { + return baseType.getKind() === 8 /* Class */; + } + } else { + if (!thisIsClass) { + return false; + } + } + + return !!(baseType.getKind() & (16 /* Interface */ | 8 /* Class */ | 128 /* Array */)); + }; + + PullTypeSymbol.prototype.removeExtendedType = function (extendedType) { + var typeLink; + + if (this.extendedTypeLinks) { + for (var i = 0; i < this.extendedTypeLinks.length; i++) { + if (extendedType === this.extendedTypeLinks[i].end) { + typeLink = this.extendedTypeLinks[i]; + this.removeOutgoingLink(typeLink); + break; + } + } + } + + this.invalidate(); + }; + + PullTypeSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + var memberSymbol; + + if (!this.memberNameCache) { + this.populateMemberCache(); + } + + memberSymbol = this.memberNameCache[name]; + + if (!lookInParent) { + return memberSymbol; + } else if (memberSymbol) { + return memberSymbol; + } + + if (!memberSymbol && this.extendedTypeLinks) { + for (var i = 0; i < this.extendedTypeLinks.length; i++) { + memberSymbol = (this.extendedTypeLinks[i].end).findMember(name); + + if (memberSymbol) { + return memberSymbol; + } + } + } + + return this.findNestedType(name); + }; + + PullTypeSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this.memberTypeNameCache) { + this.populateMemberTypeCache(); + } + + memberSymbol = this.memberTypeNameCache[name]; + + if (memberSymbol && kind != 0 /* None */) { + memberSymbol = ((memberSymbol.getKind() & kind) != 0) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.populateMemberCache = function () { + if (!this.memberNameCache || !this.memberCache) { + this.memberNameCache = new TypeScript.BlockIntrinsics(); + this.memberCache = []; + + if (this.memberLinks) { + for (var i = 0; i < this.memberLinks.length; i++) { + this.memberNameCache[this.memberLinks[i].end.getName()] = this.memberLinks[i].end; + this.memberCache[this.memberCache.length] = this.memberLinks[i].end; + } + } + } + }; + + PullTypeSymbol.prototype.populateMemberTypeCache = function () { + if (!this.memberTypeNameCache) { + this.memberTypeNameCache = new TypeScript.BlockIntrinsics(); + + var setAll = false; + + if (!this.memberCache) { + this.memberCache = []; + this.memberNameCache = new TypeScript.BlockIntrinsics(); + setAll = true; + } + + if (this.memberLinks) { + for (var i = 0; i < this.memberLinks.length; i++) { + if (this.memberLinks[i].end.isType()) { + this.memberTypeNameCache[this.memberLinks[i].end.getName()] = this.memberLinks[i].end; + this.memberCache[this.memberCache.length] = this.memberLinks[i].end; + } else if (setAll) { + this.memberNameCache[this.memberLinks[i].end.getName()] = this.memberLinks[i].end; + this.memberCache[this.memberCache.length] = this.memberLinks[i].end; + } + } + } + } + }; + + PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, includePrivate) { + var allMembers = []; + var i = 0; + var j = 0; + var m = 0; + var n = 0; + + if (!this.memberCache) { + this.populateMemberCache(); + } + + if (!this.memberTypeNameCache) { + this.populateMemberTypeCache(); + } + + if (!this.memberNameCache) { + this.populateMemberCache(); + } + + for (var i = 0, n = this.memberCache.length; i < n; i++) { + var member = this.memberCache[i]; + if ((member.getKind() & searchDeclKind) && (includePrivate || !member.hasFlag(2 /* Private */))) { + allMembers[allMembers.length] = member; + } + } + + if (this.extendedTypeLinks) { + for (var i = 0, n = this.extendedTypeLinks.length; i < n; i++) { + var extendedMembers = (this.extendedTypeLinks[i].end).getAllMembers(searchDeclKind, includePrivate); + + for (var j = 0, m = extendedMembers.length; j < m; j++) { + var extendedMember = extendedMembers[j]; + if (!this.memberNameCache[extendedMember.getName()]) { + allMembers[allMembers.length] = extendedMember; + } + } + } + } + + return allMembers; + }; + + PullTypeSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this.memberTypeParameterNameCache) { + this.memberTypeParameterNameCache = new TypeScript.BlockIntrinsics(); + + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + this.memberTypeParameterNameCache[this.typeParameterLinks[i].end.getName()] = this.typeParameterLinks[i].end; + } + } + } + + memberSymbol = this.memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullTypeSymbol.prototype.cleanTypeParameters = function () { + if (this.typeParameterLinks) { + for (var i = 0; i < this.typeParameterLinks.length; i++) { + this.removeOutgoingLink(this.typeParameterLinks[i]); + } + } + + this.typeParameterLinks = null; + this.memberTypeParameterNameCache = null; + }; + + PullTypeSymbol.prototype.setResolved = function () { + this.invalidatedSpecializations = true; + _super.prototype.setResolved.call(this); + }; + + PullTypeSymbol.prototype.invalidate = function () { + if (this.constructorMethod) { + this.constructorMethod.invalidate(); + } + + this.memberNameCache = null; + this.memberCache = null; + this.memberTypeNameCache = null; + this.containedMemberCache = null; + + this.invalidatedSpecializations = false; + + this.containedByLinks = null; + + this.memberLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 6 /* PrivateMember */ || psl.kind === 5 /* PublicMember */; + }); + + this.typeParameterLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 18 /* TypeParameter */; + }); + + this.callSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 15 /* CallSignature */; + }); + + this.constructSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 16 /* ConstructSignature */; + }); + + this.indexSignatureLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 17 /* IndexSignature */; + }); + + this.implementedTypeLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 12 /* Implements */; + }); + + this.extendedTypeLinks = this.findOutgoingLinks(function (psl) { + return psl.kind === 11 /* Extends */; + }); + + this.knownBaseTypeCount = 0; + + _super.prototype.invalidate.call(this); + }; + + PullTypeSymbol.prototype.getNamePartForFullName = function () { + var name = _super.prototype.getNamePartForFullName.call(this); + + var typars = this.getTypeArguments(); + if (!typars || !typars.length) { + typars = this.getTypeParameters(); + } + + var typarString = PullSymbol.getTypeParameterString(typars, this, true); + return name + typarString; + }; + + PullTypeSymbol.prototype.getScopedName = function (scopeSymbol, useConstraintInName) { + return this.getScopedNameEx(scopeSymbol, useConstraintInName).toString(); + }; + + PullTypeSymbol.prototype.isNamedTypeSymbol = function () { + var kind = this.getKind(); + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 256 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.getName() != "")) { + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.toString = function (useConstraintInName) { + var s = this.getScopedNameEx(null, useConstraintInName).toString(); + return s; + }; + + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo) { + if (!this.isNamedTypeSymbol()) { + return this.getMemberTypeNameEx(true, scopeSymbol, getPrettyTypeName); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = _super.prototype.getScopedName.call(this, scopeSymbol, useConstraintInName); + + var typars = this.getTypeArguments(); + if (!typars || !typars.length) { + typars = this.getTypeParameters(); + } + + builder.add(PullSymbol.getTypeParameterStringEx(typars, this, getTypeParamMarkerInfo, useConstraintInName)); + + return builder; + }; + + PullTypeSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + return members.length === 0 && constructSignatures.length === 0 && callSignatures.length > 1; + }; + + PullTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + var indexSignatures = this.getIndexSignatures(); + + if (members.length > 0 || callSignatures.length > 0 || constructSignatures.length > 0 || indexSignatures.length > 0) { + var allMemberNames = new TypeScript.MemberNameArray(); + var curlies = !topLevel || indexSignatures.length != 0; + var delim = "; "; + for (var i = 0; i < members.length; i++) { + var memberTypeName = members[i].getNameAndTypeNameEx(scopeSymbol); + + if (memberTypeName.isArray() && (memberTypeName).delim === delim) { + allMemberNames.addAll((memberTypeName).entries); + } else { + allMemberNames.add(memberTypeName); + } + curlies = true; + } + + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.hasOnlyOverloadCallSignatures(); + + var signatureCount = callSignatures.length + constructSignatures.length + indexSignatures.length; + if (signatureCount != 0 || members.length != 0) { + var useShortFormSignature = !curlies && (signatureCount === 1); + var signatureMemberName; + + if (callSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(callSignatures, "", useShortFormSignature, false, scopeSymbol, getPrettyFunctionOverload); + allMemberNames.addAll(signatureMemberName); + } + + if (constructSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(constructSignatures, "new", useShortFormSignature, false, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if (indexSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(indexSignatures, "", useShortFormSignature, true, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if ((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if (allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + + return allMemberNames; + } + } + + return TypeScript.MemberName.create("{}"); + }; + + PullTypeSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var isVisible = _super.prototype.isExternallyVisible.call(this, inIsExternallyVisibleSymbols); + if (isVisible) { + var typars = this.getTypeArguments(); + if (!typars || !typars.length) { + typars = this.getTypeParameters(); + } + + if (typars) { + for (var i = 0; i < typars.length; i++) { + isVisible = PullSymbol.getIsExternallyVisible(typars[i], this, inIsExternallyVisibleSymbols); + if (!isVisible) { + break; + } + } + } + } + + return isVisible; + }; + + PullTypeSymbol.prototype.setType = function (type) { + TypeScript.Debug.assert(false, "tried to set type of type"); + }; + return PullTypeSymbol; + })(PullSymbol); + TypeScript.PullTypeSymbol = PullTypeSymbol; + + var PullPrimitiveTypeSymbol = (function (_super) { + __extends(PullPrimitiveTypeSymbol, _super); + function PullPrimitiveTypeSymbol(name) { + _super.call(this, name, 2 /* Primitive */); + } + PullPrimitiveTypeSymbol.prototype.isResolved = function () { + return true; + }; + + PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { + return false; + }; + + PullPrimitiveTypeSymbol.prototype.isFixed = function () { + return true; + }; + + PullPrimitiveTypeSymbol.prototype.invalidate = function () { + }; + return PullPrimitiveTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; + + var PullStringConstantTypeSymbol = (function (_super) { + __extends(PullStringConstantTypeSymbol, _super); + function PullStringConstantTypeSymbol(name) { + _super.call(this, name); + } + PullStringConstantTypeSymbol.prototype.isStringConstant = function () { + return true; + }; + return PullStringConstantTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullStringConstantTypeSymbol = PullStringConstantTypeSymbol; + + var PullErrorTypeSymbol = (function (_super) { + __extends(PullErrorTypeSymbol, _super); + function PullErrorTypeSymbol(diagnostic, delegateType, _data) { + if (typeof _data === "undefined") { _data = null; } + _super.call(this, "error"); + this.diagnostic = diagnostic; + this.delegateType = delegateType; + this._data = _data; + } + PullErrorTypeSymbol.prototype.isError = function () { + return true; + }; + + PullErrorTypeSymbol.prototype.getDiagnostic = function () { + return this.diagnostic; + }; + + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + return this.delegateType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName) { + return this.delegateType.getDisplayName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.toString = function () { + return this.delegateType.toString(); + }; + + PullErrorTypeSymbol.prototype.isResolved = function () { + return false; + }; + + PullErrorTypeSymbol.prototype.setData = function (data) { + this._data = data; + }; + + PullErrorTypeSymbol.prototype.getData = function () { + return this._data; + }; + return PullErrorTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullErrorTypeSymbol = PullErrorTypeSymbol; + + var PullClassTypeSymbol = (function (_super) { + __extends(PullClassTypeSymbol, _super); + function PullClassTypeSymbol(name) { + _super.call(this, name, 8 /* Class */); + } + return PullClassTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullClassTypeSymbol = PullClassTypeSymbol; + + var PullContainerTypeSymbol = (function (_super) { + __extends(PullContainerTypeSymbol, _super); + function PullContainerTypeSymbol(name, kind) { + if (typeof kind === "undefined") { kind = 4 /* Container */; } + _super.call(this, name, kind); + this.instanceSymbol = null; + this._exportAssignedValueSymbol = null; + this._exportAssignedTypeSymbol = null; + this._exportAssignedContainerSymbol = null; + } + PullContainerTypeSymbol.prototype.isContainer = function () { + return true; + }; + + PullContainerTypeSymbol.prototype.setInstanceSymbol = function (symbol) { + this.instanceSymbol = symbol; + }; + + PullContainerTypeSymbol.prototype.getInstanceSymbol = function () { + return this.instanceSymbol; + }; + + PullContainerTypeSymbol.prototype.invalidate = function () { + if (this.instanceSymbol) { + this.instanceSymbol.invalidate(); + } + + _super.prototype.invalidate.call(this); + }; + + PullContainerTypeSymbol.prototype.setExportAssignedValueSymbol = function (symbol) { + this._exportAssignedValueSymbol = symbol; + }; + PullContainerTypeSymbol.prototype.getExportAssignedValueSymbol = function () { + return this._exportAssignedValueSymbol; + }; + + PullContainerTypeSymbol.prototype.setExportAssignedTypeSymbol = function (type) { + this._exportAssignedTypeSymbol = type; + }; + PullContainerTypeSymbol.prototype.getExportAssignedTypeSymbol = function () { + return this._exportAssignedTypeSymbol; + }; + + PullContainerTypeSymbol.prototype.setExportAssignedContainerSymbol = function (container) { + this._exportAssignedContainerSymbol = container; + }; + PullContainerTypeSymbol.prototype.getExportAssignedContainerSymbol = function () { + return this._exportAssignedContainerSymbol; + }; + + PullContainerTypeSymbol.prototype.resetExportAssignedSymbols = function () { + this._exportAssignedContainerSymbol = null; + this._exportAssignedTypeSymbol = null; + this._exportAssignedValueSymbol = null; + }; + + PullContainerTypeSymbol.usedAsSymbol = function (containerSymbol, symbol) { + if (!containerSymbol || !containerSymbol.isContainer()) { + return false; + } + + if (containerSymbol.getType() == symbol) { + return true; + } + + var containerTypeSymbol = containerSymbol; + var valueExportSymbol = containerTypeSymbol.getExportAssignedValueSymbol(); + var typeExportSymbol = containerTypeSymbol.getExportAssignedTypeSymbol(); + var containerExportSymbol = containerTypeSymbol.getExportAssignedContainerSymbol(); + if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { + return valueExportSymbol == symbol || typeExportSymbol == symbol || containerExportSymbol == symbol || PullContainerTypeSymbol.usedAsSymbol(containerExportSymbol, symbol); + } + + return false; + }; + return PullContainerTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullContainerTypeSymbol = PullContainerTypeSymbol; + + var PullTypeAliasSymbol = (function (_super) { + __extends(PullTypeAliasSymbol, _super); + function PullTypeAliasSymbol(name) { + _super.call(this, name, 256 /* TypeAlias */); + this.typeAliasLink = null; + this.isUsedAsValue = false; + this.typeUsedExternally = false; + this.retrievingExportAssignment = false; + } + PullTypeAliasSymbol.prototype.isAlias = function () { + return true; + }; + PullTypeAliasSymbol.prototype.isContainer = function () { + return true; + }; + + PullTypeAliasSymbol.prototype.setAliasedType = function (type) { + TypeScript.Debug.assert(!type.isError(), "Attempted to alias an error"); + if (this.typeAliasLink) { + this.removeOutgoingLink(this.typeAliasLink); + } + + this.typeAliasLink = this.addOutgoingLink(type, 8 /* Aliases */); + }; + + PullTypeAliasSymbol.prototype.getExportAssignedValueSymbol = function () { + if (!this.typeAliasLink) { + return null; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this.typeAliasLink.end.isContainer()) { + this.retrievingExportAssignment = true; + var sym = (this.typeAliasLink.end).getExportAssignedValueSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedTypeSymbol = function () { + if (!this.typeAliasLink) { + return null; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this.typeAliasLink.end.isContainer()) { + this.retrievingExportAssignment = true; + var sym = (this.typeAliasLink.end).getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedContainerSymbol = function () { + if (!this.typeAliasLink) { + return null; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this.typeAliasLink.end.isContainer()) { + this.retrievingExportAssignment = true; + var sym = (this.typeAliasLink.end).getExportAssignedContainerSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getType = function () { + if (this.typeAliasLink) { + return this.typeAliasLink.end; + } + + return null; + }; + + PullTypeAliasSymbol.prototype.setType = function (type) { + this.setAliasedType(type); + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this.isUsedAsValue = true; + }; + + PullTypeAliasSymbol.prototype.getIsUsedAsValue = function () { + return this.isUsedAsValue; + }; + + PullTypeAliasSymbol.prototype.setIsTypeUsedExternally = function () { + this.typeUsedExternally = true; + }; + + PullTypeAliasSymbol.prototype.getTypeUsedExternally = function () { + return this.typeUsedExternally; + }; + + PullTypeAliasSymbol.prototype.getMembers = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getMembers(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.getCallSignatures = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getCallSignatures(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.getConstructSignatures = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getConstructSignatures(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.getIndexSignatures = function () { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getIndexSignatures(); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.findMember = function (name) { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).findMember(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedType = function (name) { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).findNestedType(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getAllMembers = function (searchDeclKind, includePrivate) { + if (this.typeAliasLink) { + return (this.typeAliasLink.end).getAllMembers(searchDeclKind, includePrivate); + } + + return []; + }; + + PullTypeAliasSymbol.prototype.invalidate = function () { + this.isUsedAsValue = false; + + _super.prototype.invalidate.call(this); + }; + return PullTypeAliasSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; + + var PullDefinitionSignatureSymbol = (function (_super) { + __extends(PullDefinitionSignatureSymbol, _super); + function PullDefinitionSignatureSymbol() { + _super.apply(this, arguments); + } + PullDefinitionSignatureSymbol.prototype.isDefinition = function () { + return true; + }; + return PullDefinitionSignatureSymbol; + })(PullSignatureSymbol); + TypeScript.PullDefinitionSignatureSymbol = PullDefinitionSignatureSymbol; + + var PullFunctionTypeSymbol = (function (_super) { + __extends(PullFunctionTypeSymbol, _super); + function PullFunctionTypeSymbol() { + _super.call(this, "", 16777216 /* FunctionType */); + this.definitionSignature = null; + } + PullFunctionTypeSymbol.prototype.isFunction = function () { + return true; + }; + + PullFunctionTypeSymbol.prototype.invalidate = function () { + var callSignatures = this.getCallSignatures(); + + if (callSignatures.length) { + for (var i = 0; i < callSignatures.length; i++) { + callSignatures[i].invalidate(); + } + } + + this.definitionSignature = null; + + _super.prototype.invalidate.call(this); + }; + + PullFunctionTypeSymbol.prototype.addSignature = function (signature) { + this.addCallSignature(signature); + + if (signature.isDefinition()) { + this.definitionSignature = signature; + } + }; + + PullFunctionTypeSymbol.prototype.getDefinitionSignature = function () { + return this.definitionSignature; + }; + return PullFunctionTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullFunctionTypeSymbol = PullFunctionTypeSymbol; + + var PullConstructorTypeSymbol = (function (_super) { + __extends(PullConstructorTypeSymbol, _super); + function PullConstructorTypeSymbol() { + _super.call(this, "", 33554432 /* ConstructorType */); + this.definitionSignature = null; + } + PullConstructorTypeSymbol.prototype.isFunction = function () { + return true; + }; + PullConstructorTypeSymbol.prototype.isConstructor = function () { + return true; + }; + + PullConstructorTypeSymbol.prototype.invalidate = function () { + this.definitionSignature = null; + + _super.prototype.invalidate.call(this); + }; + + PullConstructorTypeSymbol.prototype.addSignature = function (signature) { + this.addConstructSignature(signature); + + if (signature.isDefinition()) { + this.definitionSignature = signature; + } + }; + + PullConstructorTypeSymbol.prototype.addTypeParameter = function (typeParameter, doNotChangeContainer) { + this.addMember(typeParameter, 18 /* TypeParameter */, doNotChangeContainer); + + var constructSignatures = this.getConstructSignatures(); + + for (var i = 0; i < constructSignatures.length; i++) { + constructSignatures[i].addTypeParameter(typeParameter); + } + }; + + PullConstructorTypeSymbol.prototype.getDefinitionSignature = function () { + return this.definitionSignature; + }; + return PullConstructorTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullConstructorTypeSymbol = PullConstructorTypeSymbol; + + var PullTypeParameterSymbol = (function (_super) { + __extends(PullTypeParameterSymbol, _super); + function PullTypeParameterSymbol(name, _isFunctionTypeParameter) { + _super.call(this, name, 8192 /* TypeParameter */); + this._isFunctionTypeParameter = _isFunctionTypeParameter; + this.constraintLink = null; + } + PullTypeParameterSymbol.prototype.isTypeParameter = function () { + return true; + }; + PullTypeParameterSymbol.prototype.isFunctionTypeParameter = function () { + return this._isFunctionTypeParameter; + }; + + PullTypeParameterSymbol.prototype.isFixed = function () { + return false; + }; + + PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { + if (this.constraintLink) { + this.removeOutgoingLink(this.constraintLink); + } + + this.constraintLink = this.addOutgoingLink(constraintType, 22 /* TypeConstraint */); + }; + + PullTypeParameterSymbol.prototype.getConstraint = function () { + if (this.constraintLink) { + return this.constraintLink.end; + } + + return null; + }; + + PullTypeParameterSymbol.prototype.isGeneric = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.fullName = function (scopeSymbol) { + var name = this.getDisplayName(scopeSymbol); + var container = this.getContainer(); + if (container) { + var containerName = container.fullName(scopeSymbol); + name = name + " in " + containerName; + } + + return name; + }; + + PullTypeParameterSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getName.call(this, scopeSymbol); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this.constraintLink) { + name += " extends " + this.constraintLink.end.toString(); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getDisplayName.call(this, scopeSymbol, useConstraintInName); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this.constraintLink) { + name += " extends " + this.constraintLink.end.toString(); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var constraint = this.getConstraint(); + if (constraint) { + return PullSymbol.getIsExternallyVisible(constraint, this, inIsExternallyVisibleSymbols); + } + + return true; + }; + return PullTypeParameterSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeParameterSymbol = PullTypeParameterSymbol; + + var PullTypeVariableSymbol = (function (_super) { + __extends(PullTypeVariableSymbol, _super); + function PullTypeVariableSymbol(name, isFunctionTypeParameter) { + _super.call(this, name, isFunctionTypeParameter); + this.tyvarID = TypeScript.globalTyvarID++; + } + PullTypeVariableSymbol.prototype.isTypeParameter = function () { + return true; + }; + PullTypeVariableSymbol.prototype.isTypeVariable = function () { + return true; + }; + return PullTypeVariableSymbol; + })(PullTypeParameterSymbol); + TypeScript.PullTypeVariableSymbol = PullTypeVariableSymbol; + + var PullAccessorSymbol = (function (_super) { + __extends(PullAccessorSymbol, _super); + function PullAccessorSymbol(name) { + _super.call(this, name, 4096 /* Property */); + this.getterSymbolLink = null; + this.setterSymbolLink = null; + } + PullAccessorSymbol.prototype.isAccessor = function () { + return true; + }; + + PullAccessorSymbol.prototype.setSetter = function (setter) { + this.setterSymbolLink = this.addOutgoingLink(setter, 25 /* SetterFunction */); + }; + + PullAccessorSymbol.prototype.getSetter = function () { + var setter = null; + + if (this.setterSymbolLink) { + setter = this.setterSymbolLink.end; + } + + return setter; + }; + + PullAccessorSymbol.prototype.removeSetter = function () { + if (this.setterSymbolLink) { + this.removeOutgoingLink(this.setterSymbolLink); + } + }; + + PullAccessorSymbol.prototype.setGetter = function (getter) { + this.getterSymbolLink = this.addOutgoingLink(getter, 24 /* GetterFunction */); + }; + + PullAccessorSymbol.prototype.getGetter = function () { + var getter = null; + + if (this.getterSymbolLink) { + getter = this.getterSymbolLink.end; + } + + return getter; + }; + + PullAccessorSymbol.prototype.removeGetter = function () { + if (this.getterSymbolLink) { + this.removeOutgoingLink(this.getterSymbolLink); + } + }; + + PullAccessorSymbol.prototype.invalidate = function () { + if (this.getterSymbolLink) { + this.getterSymbolLink.end.invalidate(); + } + + if (this.setterSymbolLink) { + this.setterSymbolLink.end.invalidate(); + } + + _super.prototype.invalidate.call(this); + }; + return PullAccessorSymbol; + })(PullSymbol); + TypeScript.PullAccessorSymbol = PullAccessorSymbol; + + var PullArrayTypeSymbol = (function (_super) { + __extends(PullArrayTypeSymbol, _super); + function PullArrayTypeSymbol() { + _super.call(this, "Array", 128 /* Array */); + this.elementType = null; + } + PullArrayTypeSymbol.prototype.isArray = function () { + return true; + }; + PullArrayTypeSymbol.prototype.getElementType = function () { + return this.elementType; + }; + PullArrayTypeSymbol.prototype.isGeneric = function () { + return true; + }; + + PullArrayTypeSymbol.prototype.setElementType = function (type) { + this.elementType = type; + }; + + PullArrayTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo) { + var elementMemberName = this.elementType ? (this.elementType.isArray() || this.elementType.isNamedTypeSymbol() ? this.elementType.getScopedNameEx(scopeSymbol, false, getPrettyTypeName, getTypeParamMarkerInfo) : this.elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + }; + + PullArrayTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var elementMemberName = this.elementType ? this.elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + }; + return PullArrayTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullArrayTypeSymbol = PullArrayTypeSymbol; + + function specializeToArrayType(typeToReplace, typeToSpecializeTo, resolver, context) { + var arrayInterfaceType = resolver.getCachedArrayType(); + + if (!arrayInterfaceType || (arrayInterfaceType.getKind() & 16 /* Interface */) === 0) { + return null; + } + + if (arrayInterfaceType.isGeneric()) { + var enclosingDecl = arrayInterfaceType.getDeclarations()[0]; + return specializeType(arrayInterfaceType, [typeToSpecializeTo], resolver, enclosingDecl, context); + } + + if (typeToSpecializeTo.getArrayType()) { + return typeToSpecializeTo.getArrayType(); + } + + var newArrayType = new PullArrayTypeSymbol(); + newArrayType.addDeclaration(arrayInterfaceType.getDeclarations()[0]); + + typeToSpecializeTo.setArrayType(newArrayType); + newArrayType.addOutgoingLink(typeToSpecializeTo, 4 /* ArrayOf */); + + var field = null; + var newField = null; + var fieldType = null; + + var method = null; + var methodType = null; + var newMethod = null; + var newMethodType = null; + + var signatures = null; + var newSignature = null; + + var parameters = null; + var newParameter = null; + var parameterType = null; + + var returnType = null; + var newReturnType = null; + + var members = arrayInterfaceType.getMembers(); + + for (var i = 0; i < members.length; i++) { + resolver.resolveDeclaredSymbol(members[i], null, context); + + if (members[i].getKind() === 65536 /* Method */) { + method = members[i]; + + resolver.resolveDeclaredSymbol(method, null, context); + + methodType = method.getType(); + + newMethod = new PullSymbol(method.getName(), 65536 /* Method */); + newMethodType = new PullFunctionTypeSymbol(); + newMethod.setType(newMethodType); + + newMethod.addDeclaration(method.getDeclarations()[0]); + + signatures = methodType.getCallSignatures(); + + for (var j = 0; j < signatures.length; j++) { + newSignature = new PullSignatureSymbol(1048576 /* CallSignature */); + newSignature.addDeclaration(signatures[j].getDeclarations()[0]); + + parameters = signatures[j].getParameters(); + returnType = signatures[j].getReturnType(); + + if (returnType === typeToReplace) { + newSignature.setReturnType(typeToSpecializeTo); + } else { + newSignature.setReturnType(returnType); + } + + for (var k = 0; k < parameters.length; k++) { + newParameter = new PullSymbol(parameters[k].getName(), parameters[k].getKind()); + + parameterType = parameters[k].getType(); + + if (parameterType === null) { + continue; + } + + if (parameterType === typeToReplace) { + newParameter.setType(typeToSpecializeTo); + } else { + newParameter.setType(parameterType); + } + + newSignature.addParameter(newParameter); + } + + newMethodType.addSignature(newSignature); + } + + newArrayType.addMember(newMethod, 5 /* PublicMember */); + } else { + field = members[i]; + + newField = new PullSymbol(field.getName(), field.getKind()); + newField.addDeclaration(field.getDeclarations()[0]); + + fieldType = field.getType(); + + if (fieldType === typeToReplace) { + newField.setType(typeToSpecializeTo); + } else { + newField.setType(fieldType); + } + + newArrayType.addMember(newField, 5 /* PublicMember */); + } + } + newArrayType.addOutgoingLink(arrayInterfaceType, 3 /* ArrayType */); + return newArrayType; + } + TypeScript.specializeToArrayType = specializeToArrayType; + + function typeWrapsTypeParameter(type, typeParameter) { + if (type.isTypeParameter()) { + return type == typeParameter; + } + + var typeArguments = type.getTypeArguments(); + + if (typeArguments) { + for (var i = 0; i < typeArguments.length; i++) { + if (typeWrapsTypeParameter(typeArguments[i], typeParameter)) { + return true; + } + } + } + + return false; + } + TypeScript.typeWrapsTypeParameter = typeWrapsTypeParameter; + + function getRootType(typeToSpecialize) { + var decl = typeToSpecialize.getDeclarations()[0]; + + if (!typeToSpecialize.isGeneric()) { + return typeToSpecialize; + } + + return (typeToSpecialize.getKind() & (8 /* Class */ | 16 /* Interface */)) ? decl.getSymbol().getType() : typeToSpecialize; + } + TypeScript.getRootType = getRootType; + + TypeScript.nSpecializationsCreated = 0; + TypeScript.nSpecializedSignaturesCreated = 0; + + function shouldSpecializeTypeParameterForTypeParameter(specialization, typeToSpecialize) { + if (specialization == typeToSpecialize) { + return false; + } + + if (!(specialization.isTypeParameter() && typeToSpecialize.isTypeParameter())) { + return true; + } + + var parent = specialization.getDeclarations()[0].getParentDecl(); + var targetParent = typeToSpecialize.getDeclarations()[0].getParentDecl(); + + if (parent == targetParent) { + return true; + } + + while (parent) { + if (parent.getFlags() & 16 /* Static */) { + return true; + } + + if (parent == targetParent) { + return false; + } + + parent = parent.getParentDecl(); + } + + return true; + } + TypeScript.shouldSpecializeTypeParameterForTypeParameter = shouldSpecializeTypeParameterForTypeParameter; + + function specializeType(typeToSpecialize, typeArguments, resolver, enclosingDecl, context, ast) { + if (typeToSpecialize.isPrimitive() || !typeToSpecialize.isGeneric()) { + return typeToSpecialize; + } + + var searchForExistingSpecialization = typeArguments != null; + + if (typeArguments === null || (context.specializingToAny && typeArguments.length)) { + typeArguments = []; + } + + if (typeToSpecialize.isTypeParameter()) { + if (context.specializingToAny) { + return resolver.semanticInfoChain.anyTypeSymbol; + } + + var substitution = context.findSpecializationForType(typeToSpecialize); + + if (substitution != typeToSpecialize) { + if (shouldSpecializeTypeParameterForTypeParameter(substitution, typeToSpecialize)) { + return substitution; + } + } + + if (typeArguments && typeArguments.length) { + if (shouldSpecializeTypeParameterForTypeParameter(typeArguments[0], typeToSpecialize)) { + return typeArguments[0]; + } + } + + return typeToSpecialize; + } + + if (typeToSpecialize.isArray()) { + if (typeToSpecialize.currentlyBeingSpecialized()) { + return typeToSpecialize; + } + + var newElementType = null; + + if (!context.specializingToAny) { + var elementType = (typeToSpecialize).getElementType(); + + newElementType = specializeType(elementType, typeArguments, resolver, enclosingDecl, context, ast); + } else { + newElementType = resolver.semanticInfoChain.anyTypeSymbol; + } + + var newArrayType = specializeType(resolver.getCachedArrayType(), [newElementType], resolver, enclosingDecl, context); + + return newArrayType; + } + + var typeParameters = typeToSpecialize.getTypeParameters(); + + if (!context.specializingToAny && searchForExistingSpecialization && (typeParameters.length > typeArguments.length)) { + searchForExistingSpecialization = false; + } + + var newType = null; + + var newTypeDecl = typeToSpecialize.getDeclarations()[0]; + + var rootType = getRootType(typeToSpecialize); + + var isArray = typeToSpecialize === resolver.getCachedArrayType() || typeToSpecialize.isArray(); + + if (searchForExistingSpecialization || context.specializingToAny) { + if (!typeArguments.length || context.specializingToAny) { + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = resolver.semanticInfoChain.anyTypeSymbol; + } + } + + if (isArray) { + newType = typeArguments[0].getArrayType(); + } else if (typeArguments.length) { + newType = rootType.getSpecialization(typeArguments); + } + + if (!newType && !typeParameters.length && context.specializingToAny) { + newType = rootType.getSpecialization([resolver.semanticInfoChain.anyTypeSymbol]); + } + + for (var i = 0; i < typeArguments.length; i++) { + if (!typeArguments[i].isTypeParameter() && (typeArguments[i] == rootType || typeWrapsTypeParameter(typeArguments[i], typeParameters[i]))) { + declAST = resolver.semanticInfoChain.getASTForDecl(newTypeDecl); + if (declAST && typeArguments[i] != resolver.getCachedArrayType()) { + diagnostic = context.postError(enclosingDecl.getScriptName(), declAST.minChar, declAST.getLength(), 225 /* A_generic_type_may_not_reference_itself_with_its_own_type_parameters */, null, enclosingDecl, true); + return resolver.getNewErrorTypeSymbol(diagnostic); + } else { + return resolver.semanticInfoChain.anyTypeSymbol; + } + } + } + } else { + var knownTypeArguments = typeToSpecialize.getTypeArguments(); + var typesToReplace = knownTypeArguments ? knownTypeArguments : typeParameters; + var diagnostic; + var declAST; + + for (var i = 0; i < typesToReplace.length; i++) { + if (!typesToReplace[i].isTypeParameter() && (typeArguments[i] == rootType || typeWrapsTypeParameter(typesToReplace[i], typeParameters[i]))) { + declAST = resolver.semanticInfoChain.getASTForDecl(newTypeDecl); + if (declAST && typeArguments[i] != resolver.getCachedArrayType()) { + diagnostic = context.postError(enclosingDecl.getScriptName(), declAST.minChar, declAST.getLength(), 225 /* A_generic_type_may_not_reference_itself_with_its_own_type_parameters */, null, enclosingDecl, true); + return resolver.getNewErrorTypeSymbol(diagnostic); + } else { + return resolver.semanticInfoChain.anyTypeSymbol; + } + } + + substitution = specializeType(typesToReplace[i], null, resolver, enclosingDecl, context, ast); + + typeArguments[i] = substitution != null ? substitution : typesToReplace[i]; + } + + newType = rootType.getSpecialization(typeArguments); + } + + var rootTypeParameters = rootType.getTypeParameters(); + + if (rootTypeParameters.length && (rootTypeParameters.length == typeArguments.length)) { + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i] != rootTypeParameters[i]) { + break; + } + } + + if (i == rootTypeParameters.length) { + return rootType; + } + } + + if (newType) { + if (!newType.isResolved() && !newType.currentlyBeingSpecialized()) { + typeToSpecialize.invalidateSpecializations(); + } else { + return newType; + } + } + + var prevInSpecialization = context.inSpecialization; + context.inSpecialization = true; + + TypeScript.nSpecializationsCreated++; + + newType = typeToSpecialize.isClass() ? new PullClassTypeSymbol(typeToSpecialize.getName()) : isArray ? new PullArrayTypeSymbol() : typeToSpecialize.isTypeParameter() ? new PullTypeVariableSymbol(typeToSpecialize.getName(), (typeToSpecialize).isFunctionTypeParameter()) : new PullTypeSymbol(typeToSpecialize.getName(), typeToSpecialize.getKind()); + newType.setRootSymbol(rootType); + + newType.setIsBeingSpecialized(); + + newType.setTypeArguments(typeArguments); + + rootType.addSpecialization(newType, typeArguments); + + if (isArray) { + (newType).setElementType(typeArguments[0]); + typeArguments[0].setArrayType(newType); + } + + if (typeToSpecialize.currentlyBeingSpecialized()) { + return newType; + } + + var prevCurrentlyBeingSpecialized = typeToSpecialize.currentlyBeingSpecialized(); + if (typeToSpecialize.getKind() == 33554432 /* ConstructorType */) { + typeToSpecialize.setIsBeingSpecialized(); + } + + var typeReplacementMap = {}; + + for (var i = 0; i < typeParameters.length; i++) { + if (typeParameters[i] != typeArguments[i]) { + typeReplacementMap[typeParameters[i].getSymbolID().toString()] = typeArguments[i]; + } + newType.addMember(typeParameters[i], 18 /* TypeParameter */, true); + } + + var extendedTypesToSpecialize = typeToSpecialize.getExtendedTypes(); + var typeDecl; + var typeAST; + var unitPath; + var decls = typeToSpecialize.getDeclarations(); + + if (extendedTypesToSpecialize.length) { + for (var i = 0; i < decls.length; i++) { + typeDecl = decls[i]; + typeAST = resolver.semanticInfoChain.getASTForDecl(typeDecl); + + if (typeAST.extendsList) { + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(typeDecl.getScriptName()); + context.pushTypeSpecializationCache(typeReplacementMap); + var extendTypeSymbol = resolver.resolveTypeReference(new TypeScript.TypeReference(typeAST.extendsList.members[0], 0), typeDecl, context).symbol; + resolver.setUnitPath(unitPath); + context.popTypeSpecializationCache(); + + newType.addExtendedType(extendTypeSymbol); + } + } + } + + var implementedTypesToSpecialize = typeToSpecialize.getImplementedTypes(); + + if (implementedTypesToSpecialize.length) { + for (var i = 0; i < decls.length; i++) { + typeDecl = decls[i]; + typeAST = resolver.semanticInfoChain.getASTForDecl(typeDecl); + + if (typeAST.implementsList) { + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(typeDecl.getScriptName()); + context.pushTypeSpecializationCache(typeReplacementMap); + var implementedTypeSymbol = resolver.resolveTypeReference(new TypeScript.TypeReference(typeAST.implementsList.members[0], 0), typeDecl, context).symbol; + resolver.setUnitPath(unitPath); + context.popTypeSpecializationCache(); + + newType.addImplementedType(implementedTypeSymbol); + } + } + } + + var callSignatures = typeToSpecialize.getCallSignatures(false); + var constructSignatures = typeToSpecialize.getConstructSignatures(false); + var indexSignatures = typeToSpecialize.getIndexSignatures(false); + var members = typeToSpecialize.getMembers(); + + var newSignature; + var signature; + + var decl = null; + var declAST = null; + var parameters; + var newParameters; + var returnType = null; + var prevSpecializationSignature = null; + + for (var i = 0; i < callSignatures.length; i++) { + signature = callSignatures[i]; + + if (!signature.currentlyBeingSpecialized()) { + context.pushTypeSpecializationCache(typeReplacementMap); + + decl = signature.getDeclarations()[0]; + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decl.getScriptName()); + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.mimicSignature(signature, resolver); + declAST = resolver.semanticInfoChain.getASTForDecl(decl); + + TypeScript.Debug.assert(declAST != null, "Call signature for type '" + typeToSpecialize.toString() + "' could not be specialized because of a stale declaration"); + + prevSpecializationSignature = decl.getSpecializingSignatureSymbol(); + decl.setSpecializingSignatureSymbol(newSignature); + resolver.resolveAST(declAST, false, newTypeDecl, context); + decl.setSpecializingSignatureSymbol(prevSpecializationSignature); + + parameters = signature.getParameters(); + newParameters = newSignature.getParameters(); + + for (var p = 0; p < parameters.length; p++) { + newParameters[p].setType(parameters[p].getType()); + } + newSignature.setResolved(); + + resolver.setUnitPath(unitPath); + + returnType = newSignature.getReturnType(); + + if (!returnType) { + newSignature.setReturnType(signature.getReturnType()); + } + + signature.setIsBeingSpecialized(); + newSignature.setRootSymbol(signature); + newSignature = specializeSignature(newSignature, true, typeReplacementMap, null, resolver, newTypeDecl, context); + signature.setIsSpecialized(); + + context.popTypeSpecializationCache(); + + if (!newSignature) { + context.inSpecialization = prevInSpecialization; + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + TypeScript.Debug.assert(false, "returning from call"); + return resolver.semanticInfoChain.anyTypeSymbol; + } + } else { + newSignature = signature; + } + + newType.addCallSignature(newSignature); + + if (newSignature.hasGenericParameter()) { + newType.setHasGenericSignature(); + } + } + + for (var i = 0; i < constructSignatures.length; i++) { + signature = constructSignatures[i]; + + if (!signature.currentlyBeingSpecialized()) { + context.pushTypeSpecializationCache(typeReplacementMap); + + decl = signature.getDeclarations()[0]; + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decl.getScriptName()); + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.mimicSignature(signature, resolver); + declAST = resolver.semanticInfoChain.getASTForDecl(decl); + + TypeScript.Debug.assert(declAST != null, "Construct signature for type '" + typeToSpecialize.toString() + "' could not be specialized because of a stale declaration"); + + prevSpecializationSignature = decl.getSpecializingSignatureSymbol(); + decl.setSpecializingSignatureSymbol(newSignature); + resolver.resolveAST(declAST, false, newTypeDecl, context); + decl.setSpecializingSignatureSymbol(prevSpecializationSignature); + + parameters = signature.getParameters(); + newParameters = newSignature.getParameters(); + + for (var p = 0; p < parameters.length; p++) { + newParameters[p].setType(parameters[p].getType()); + } + newSignature.setResolved(); + + resolver.setUnitPath(unitPath); + + returnType = newSignature.getReturnType(); + + if (!returnType) { + newSignature.setReturnType(signature.getReturnType()); + } + + signature.setIsBeingSpecialized(); + newSignature.setRootSymbol(signature); + newSignature = specializeSignature(newSignature, true, typeReplacementMap, null, resolver, newTypeDecl, context); + signature.setIsSpecialized(); + + context.popTypeSpecializationCache(); + + if (!newSignature) { + context.inSpecialization = prevInSpecialization; + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + TypeScript.Debug.assert(false, "returning from construct"); + return resolver.semanticInfoChain.anyTypeSymbol; + } + } else { + newSignature = signature; + } + + newType.addConstructSignature(newSignature); + + if (newSignature.hasGenericParameter()) { + newType.setHasGenericSignature(); + } + } + + for (var i = 0; i < indexSignatures.length; i++) { + signature = indexSignatures[i]; + + if (!signature.currentlyBeingSpecialized()) { + context.pushTypeSpecializationCache(typeReplacementMap); + + decl = signature.getDeclarations()[0]; + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decl.getScriptName()); + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.mimicSignature(signature, resolver); + declAST = resolver.semanticInfoChain.getASTForDecl(decl); + + TypeScript.Debug.assert(declAST != null, "Index signature for type '" + typeToSpecialize.toString() + "' could not be specialized because of a stale declaration"); + + prevSpecializationSignature = decl.getSpecializingSignatureSymbol(); + decl.setSpecializingSignatureSymbol(newSignature); + resolver.resolveAST(declAST, false, newTypeDecl, context); + decl.setSpecializingSignatureSymbol(prevSpecializationSignature); + + parameters = signature.getParameters(); + newParameters = newSignature.getParameters(); + + for (var p = 0; p < parameters.length; p++) { + newParameters[p].setType(parameters[p].getType()); + } + newSignature.setResolved(); + + resolver.setUnitPath(unitPath); + + returnType = newSignature.getReturnType(); + + if (!returnType) { + newSignature.setReturnType(signature.getReturnType()); + } + + signature.setIsBeingSpecialized(); + newSignature.setRootSymbol(signature); + newSignature = specializeSignature(newSignature, true, typeReplacementMap, null, resolver, newTypeDecl, context); + signature.setIsSpecialized(); + + context.popTypeSpecializationCache(); + + if (!newSignature) { + context.inSpecialization = prevInSpecialization; + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + TypeScript.Debug.assert(false, "returning from index"); + return resolver.semanticInfoChain.anyTypeSymbol; + } + } else { + newSignature = signature; + } + + newType.addIndexSignature(newSignature); + + if (newSignature.hasGenericParameter()) { + newType.setHasGenericSignature(); + } + } + + var field = null; + var newField = null; + + var fieldType = null; + var newFieldType = null; + var replacementType = null; + + var fieldSignatureSymbol = null; + + for (var i = 0; i < members.length; i++) { + field = members[i]; + field.setIsBeingSpecialized(); + + decls = field.getDeclarations(); + + newField = new PullSymbol(field.getName(), field.getKind()); + + newField.setRootSymbol(field); + + if (field.getIsOptional()) { + newField.setIsOptional(); + } + + if (!field.isResolved()) { + resolver.resolveDeclaredSymbol(field, newTypeDecl, context); + } + + fieldType = field.getType(); + + if (!fieldType) { + fieldType = newType; + } + + replacementType = typeReplacementMap[fieldType.getSymbolID().toString()]; + + if (replacementType) { + newField.setType(replacementType); + } else { + if (fieldType.isGeneric() && !fieldType.isFixed()) { + unitPath = resolver.getUnitPath(); + resolver.setUnitPath(decls[0].getScriptName()); + + context.pushTypeSpecializationCache(typeReplacementMap); + + newFieldType = specializeType(fieldType, !fieldType.getIsSpecialized() ? typeArguments : null, resolver, newTypeDecl, context, ast); + + resolver.setUnitPath(unitPath); + + context.popTypeSpecializationCache(); + + newField.setType(newFieldType); + } else { + newField.setType(fieldType); + } + } + field.setIsSpecialized(); + newType.addMember(newField, (field.hasFlag(2 /* Private */)) ? 6 /* PrivateMember */ : 5 /* PublicMember */); + } + + if (typeToSpecialize.isClass()) { + var constructorMethod = (typeToSpecialize).getConstructorMethod(); + + if (!constructorMethod.isResolved()) { + var prevIsSpecializingConstructorMethod = context.isSpecializingConstructorMethod; + context.isSpecializingConstructorMethod = true; + resolver.resolveDeclaredSymbol(constructorMethod, enclosingDecl, context); + context.isSpecializingConstructorMethod = prevIsSpecializingConstructorMethod; + } + + var newConstructorMethod = new PullSymbol(constructorMethod.getName(), 32768 /* ConstructorMethod */); + var newConstructorType = specializeType(constructorMethod.getType(), typeArguments, resolver, newTypeDecl, context, ast); + + newConstructorMethod.setType(newConstructorType); + + var constructorDecls = constructorMethod.getDeclarations(); + + newConstructorMethod.setRootSymbol(constructorMethod); + + (newType).setConstructorMethod(newConstructorMethod); + } + + newType.setIsSpecialized(); + + newType.setResolved(); + typeToSpecialize.setValueIsBeingSpecialized(prevCurrentlyBeingSpecialized); + context.inSpecialization = prevInSpecialization; + return newType; + } + TypeScript.specializeType = specializeType; + + function specializeSignature(signature, skipLocalTypeParameters, typeReplacementMap, typeArguments, resolver, enclosingDecl, context, ast) { + if (signature.currentlyBeingSpecialized()) { + return signature; + } + + if (!signature.isResolved() && !signature.isResolving()) { + resolver.resolveDeclaredSymbol(signature, enclosingDecl, context); + } + + var newSignature = signature.getSpecialization(typeArguments); + + if (newSignature) { + return newSignature; + } + + signature.setIsBeingSpecialized(); + + var prevInSpecialization = context.inSpecialization; + context.inSpecialization = true; + + newSignature = new PullSignatureSymbol(signature.getKind()); + TypeScript.nSpecializedSignaturesCreated++; + newSignature.setRootSymbol(signature); + + if (signature.hasVariableParamList()) { + newSignature.setHasVariableParamList(); + } + + if (signature.hasGenericParameter()) { + newSignature.setHasGenericParameter(); + } + + signature.addSpecialization(newSignature, typeArguments); + + var parameters = signature.getParameters(); + var typeParameters = signature.getTypeParameters(); + var returnType = signature.getReturnType(); + + for (var i = 0; i < typeParameters.length; i++) { + newSignature.addTypeParameter(typeParameters[i]); + } + + if (signature.hasGenericParameter()) { + newSignature.setHasGenericParameter(); + } + + var newParameter; + var newParameterType; + var newParameterElementType; + var parameterType; + var replacementParameterType; + var localTypeParameters = new TypeScript.BlockIntrinsics(); + var localSkipMap = null; + + if (skipLocalTypeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + localTypeParameters[typeParameters[i].getName()] = true; + if (!localSkipMap) { + localSkipMap = {}; + } + localSkipMap[typeParameters[i].getSymbolID().toString()] = typeParameters[i]; + } + } + + context.pushTypeSpecializationCache(typeReplacementMap); + + if (skipLocalTypeParameters && localSkipMap) { + context.pushTypeSpecializationCache(localSkipMap); + } + var newReturnType = (!localTypeParameters[returnType.getName()]) ? specializeType(returnType, null, resolver, enclosingDecl, context, ast) : returnType; + if (skipLocalTypeParameters && localSkipMap) { + context.popTypeSpecializationCache(); + } + context.popTypeSpecializationCache(); + + newSignature.setReturnType(newReturnType); + + for (var k = 0; k < parameters.length; k++) { + newParameter = new PullSymbol(parameters[k].getName(), parameters[k].getKind()); + newParameter.setRootSymbol(parameters[k]); + + parameterType = parameters[k].getType(); + + context.pushTypeSpecializationCache(typeReplacementMap); + if (skipLocalTypeParameters && localSkipMap) { + context.pushTypeSpecializationCache(localSkipMap); + } + newParameterType = !localTypeParameters[parameterType.getName()] ? specializeType(parameterType, null, resolver, enclosingDecl, context, ast) : parameterType; + if (skipLocalTypeParameters && localSkipMap) { + context.popTypeSpecializationCache(); + } + context.popTypeSpecializationCache(); + + if (parameters[k].getIsOptional()) { + newParameter.setIsOptional(); + } + + if (parameters[k].getIsVarArg()) { + newParameter.setIsVarArg(); + newSignature.setHasVariableParamList(); + } + + if (resolver.isTypeArgumentOrWrapper(newParameterType)) { + newSignature.setHasGenericParameter(); + } + + newParameter.setType(newParameterType); + newSignature.addParameter(newParameter, newParameter.getIsOptional()); + } + + signature.setIsSpecialized(); + + context.inSpecialization = prevInSpecialization; + + return newSignature; + } + TypeScript.specializeSignature = specializeSignature; + + function getIDForTypeSubstitutions(types) { + var substitution = ""; + + for (var i = 0; i < types.length; i++) { + substitution += types[i].getSymbolID().toString() + "#"; + } + + return substitution; + } + TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullSymbolBindingContext = (function () { + function PullSymbolBindingContext(semanticInfoChain, scriptName) { + this.semanticInfoChain = semanticInfoChain; + this.scriptName = scriptName; + this.parentChain = []; + this.declPath = []; + this.reBindingAfterChange = false; + this.startingDeclForRebind = TypeScript.pullDeclID; + this.semanticInfo = this.semanticInfoChain.getUnit(this.scriptName); + } + PullSymbolBindingContext.prototype.getParent = function (n) { + if (typeof n === "undefined") { n = 0; } + return this.parentChain ? this.parentChain[this.parentChain.length - 1 - n] : null; + }; + PullSymbolBindingContext.prototype.getDeclPath = function () { + return this.declPath; + }; + + PullSymbolBindingContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + this.declPath[this.declPath.length] = parentDecl.getName(); + } + }; + + PullSymbolBindingContext.prototype.popParent = function () { + if (this.parentChain.length) { + this.parentChain.length--; + this.declPath.length--; + } + }; + return PullSymbolBindingContext; + })(); + TypeScript.PullSymbolBindingContext = PullSymbolBindingContext; + + TypeScript.time_in_findSymbol = 0; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CandidateInferenceInfo = (function () { + function CandidateInferenceInfo() { + this.typeParameter = null; + this.isFixed = false; + this.inferenceCandidates = []; + } + CandidateInferenceInfo.prototype.addCandidate = function (candidate) { + if (!this.isFixed) { + this.inferenceCandidates[this.inferenceCandidates.length] = candidate; + } + }; + return CandidateInferenceInfo; + })(); + TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; + + var ArgumentInferenceContext = (function () { + function ArgumentInferenceContext() { + this.inferenceCache = {}; + this.candidateCache = {}; + } + ArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + var comboID = objectType.getSymbolID().toString() + "#" + parameterType.getSymbolID().toString(); + + if (this.inferenceCache[comboID]) { + return true; + } else { + this.inferenceCache[comboID] = true; + return false; + } + }; + + ArgumentInferenceContext.prototype.resetRelationshipCache = function () { + this.inferenceCache = {}; + }; + + ArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + var info = this.candidateCache[param.getSymbolID().toString()]; + + if (!info) { + info = new CandidateInferenceInfo(); + info.typeParameter = param; + this.candidateCache[param.getSymbolID().toString()] = info; + } + }; + + ArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + return this.candidateCache[param.getSymbolID().toString()]; + }; + + ArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate, fix) { + var info = this.getInferenceInfo(param); + + if (info) { + if (candidate) { + info.addCandidate(candidate); + } + + if (!info.isFixed) { + info.isFixed = fix; + } + } + }; + + ArgumentInferenceContext.prototype.getInferenceCandidates = function () { + var inferenceCandidates = []; + var info; + var val; + + for (var infoKey in this.candidateCache) { + info = this.candidateCache[infoKey]; + + for (var i = 0; i < info.inferenceCandidates.length; i++) { + val = {}; + val[info.typeParameter.getSymbolID().toString()] = info.inferenceCandidates[i]; + inferenceCandidates[inferenceCandidates.length] = val; + } + } + + return inferenceCandidates; + }; + + ArgumentInferenceContext.prototype.inferArgumentTypes = function (resolver, context) { + var info = null; + + var collection; + + var bestCommonType; + + var results = []; + + var unfit = false; + + for (var infoKey in this.candidateCache) { + info = this.candidateCache[infoKey]; + + if (!info.inferenceCandidates.length) { + results[results.length] = { param: info.typeParameter, type: resolver.semanticInfoChain.anyTypeSymbol }; + continue; + } + + collection = { + getLength: function () { + return info.inferenceCandidates.length; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return info.inferenceCandidates[index].getType(); + } + }; + + bestCommonType = resolver.widenType(resolver.findBestCommonType(info.inferenceCandidates[0], null, collection, context, new TypeScript.TypeComparisonInfo())); + + if (!bestCommonType) { + unfit = true; + } else { + for (var i = 0; i < results.length; i++) { + if (results[i].type == info.typeParameter) { + results[i].type = bestCommonType; + } + } + } + + results[results.length] = { param: info.typeParameter, type: bestCommonType }; + } + + return { results: results, unfit: unfit }; + }; + return ArgumentInferenceContext; + })(); + TypeScript.ArgumentInferenceContext = ArgumentInferenceContext; + + var PullContextualTypeContext = (function () { + function PullContextualTypeContext(contextualType, provisional, substitutions) { + this.contextualType = contextualType; + this.provisional = provisional; + this.substitutions = substitutions; + this.provisionallyTypedSymbols = []; + this.provisionalDiagnostic = []; + } + PullContextualTypeContext.prototype.recordProvisionallyTypedSymbol = function (symbol) { + this.provisionallyTypedSymbols[this.provisionallyTypedSymbols.length] = symbol; + }; + + PullContextualTypeContext.prototype.invalidateProvisionallyTypedSymbols = function () { + for (var i = 0; i < this.provisionallyTypedSymbols.length; i++) { + this.provisionallyTypedSymbols[i].invalidate(); + } + }; + + PullContextualTypeContext.prototype.postDiagnostic = function (error) { + this.provisionalDiagnostic[this.provisionalDiagnostic.length] = error; + }; + + PullContextualTypeContext.prototype.hadProvisionalErrors = function () { + return this.provisionalDiagnostic.length > 0; + }; + return PullContextualTypeContext; + })(); + TypeScript.PullContextualTypeContext = PullContextualTypeContext; + + var PullTypeResolutionContext = (function () { + function PullTypeResolutionContext() { + this.contextStack = []; + this.typeSpecializationStack = []; + this.genericASTResolutionStack = []; + this.resolvingTypeReference = false; + this.resolvingNamespaceMemberAccess = false; + this.resolveAggressively = false; + this.canUseTypeSymbol = false; + this.specializingToAny = false; + this.specializingToObject = false; + this.isResolvingClassExtendedType = false; + this.isSpecializingSignatureAtCallSite = false; + this.isSpecializingConstructorMethod = false; + this.isComparingSpecializedSignatures = false; + this.inSpecialization = false; + this.suppressErrors = false; + this.inBaseTypeResolution = false; + } + PullTypeResolutionContext.prototype.pushContextualType = function (type, provisional, substitutions) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, substitutions)); + }; + + PullTypeResolutionContext.prototype.popContextualType = function () { + var tc = this.contextStack.pop(); + + tc.invalidateProvisionallyTypedSymbols(); + + return tc; + }; + + PullTypeResolutionContext.prototype.findSubstitution = function (type) { + var substitution = null; + + if (this.contextStack.length) { + for (var i = this.contextStack.length - 1; i >= 0; i--) { + if (this.contextStack[i].substitutions) { + substitution = this.contextStack[i].substitutions[type.getSymbolID().toString()]; + + if (substitution) { + break; + } + } + } + } + + return substitution; + }; + + PullTypeResolutionContext.prototype.getContextualType = function () { + var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; + + if (context) { + var type = context.contextualType; + + if (!type) { + return null; + } + + if (type.isTypeParameter() && (type).getConstraint()) { + type = (type).getConstraint(); + } + + var substitution = this.findSubstitution(type); + + return substitution ? substitution : type; + } + + return null; + }; + + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + + PullTypeResolutionContext.prototype.isInBaseTypeResolution = function () { + return this.inBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.startBaseTypeResolution = function () { + var wasInBaseTypeResoltion = this.inBaseTypeResolution; + this.inBaseTypeResolution = true; + return wasInBaseTypeResoltion; + }; + + PullTypeResolutionContext.prototype.doneBaseTypeResolution = function (wasInBaseTypeResolution) { + this.inBaseTypeResolution = wasInBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { + var substitution = this.findSubstitution(type); + + symbol.setType(substitution ? substitution : type); + + if (this.contextStack.length && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); + } + }; + + PullTypeResolutionContext.prototype.pushTypeSpecializationCache = function (cache) { + this.typeSpecializationStack[this.typeSpecializationStack.length] = cache; + }; + + PullTypeResolutionContext.prototype.popTypeSpecializationCache = function () { + if (this.typeSpecializationStack.length) { + this.typeSpecializationStack.length--; + } + }; + + PullTypeResolutionContext.prototype.findSpecializationForType = function (type) { + var specialization = null; + + for (var i = this.typeSpecializationStack.length - 1; i >= 0; i--) { + specialization = (this.typeSpecializationStack[i])[type.getSymbolID().toString()]; + + if (specialization) { + return specialization; + } + } + + return type; + }; + + PullTypeResolutionContext.prototype.postError = function (fileName, offset, length, diagnosticCode, arguments, enclosingDecl, addToDecl) { + if (typeof arguments === "undefined") { arguments = null; } + if (typeof enclosingDecl === "undefined") { enclosingDecl = null; } + if (typeof addToDecl === "undefined") { addToDecl = false; } + var diagnostic = new TypeScript.SemanticDiagnostic(fileName, offset, length, diagnosticCode, arguments); + this.postDiagnostic(diagnostic, enclosingDecl, addToDecl); + + return diagnostic; + }; + + PullTypeResolutionContext.prototype.postDiagnostic = function (diagnostic, enclosingDecl, addToDecl) { + if (this.inProvisionalResolution()) { + (this.contextStack[this.contextStack.length - 1]).postDiagnostic(diagnostic); + } else if (!this.suppressErrors && enclosingDecl && addToDecl) { + enclosingDecl.addDiagnostic(diagnostic); + } + }; + + PullTypeResolutionContext.prototype.startResolvingTypeArguments = function (ast) { + this.genericASTResolutionStack[this.genericASTResolutionStack.length] = ast; + }; + + PullTypeResolutionContext.prototype.isResolvingTypeArguments = function (ast) { + for (var i = 0; i < this.genericASTResolutionStack.length; i++) { + if (this.genericASTResolutionStack[i].getID() === ast.getID()) { + return true; + } + } + + return false; + }; + + PullTypeResolutionContext.prototype.doneResolvingTypeArguments = function () { + this.genericASTResolutionStack.length--; + }; + return PullTypeResolutionContext; + })(); + TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SymbolAndDiagnostics = (function () { + function SymbolAndDiagnostics(symbol, symbolAlias, diagnostics) { + this.symbol = symbol; + this.symbolAlias = symbolAlias; + this.diagnostics = diagnostics; + } + SymbolAndDiagnostics.create = function (symbol, diagnostics) { + return new SymbolAndDiagnostics(symbol, null, diagnostics); + }; + + SymbolAndDiagnostics.empty = function () { + return SymbolAndDiagnostics._empty; + }; + + SymbolAndDiagnostics.fromSymbol = function (symbol) { + return new SymbolAndDiagnostics(symbol, null, null); + }; + + SymbolAndDiagnostics.fromAlias = function (symbol, alias) { + return new SymbolAndDiagnostics(symbol, alias, null); + }; + + SymbolAndDiagnostics.prototype.addDiagnostic = function (diagnostic) { + TypeScript.Debug.assert(this !== SymbolAndDiagnostics._empty); + + if (this.diagnostics === null) { + this.diagnostics = []; + } + + this.diagnostics.push(diagnostic); + }; + + SymbolAndDiagnostics.prototype.withoutDiagnostics = function () { + if (!this.diagnostics) { + return this; + } + + return SymbolAndDiagnostics.fromSymbol(this.symbol); + }; + SymbolAndDiagnostics._empty = new SymbolAndDiagnostics(null, null, null); + return SymbolAndDiagnostics; + })(); + TypeScript.SymbolAndDiagnostics = SymbolAndDiagnostics; + + var PullResolutionDataCache = (function () { + function PullResolutionDataCache() { + this.cacheSize = 16; + this.rdCache = []; + this.nextUp = 0; + for (var i = 0; i < this.cacheSize; i++) { + this.rdCache[i] = { + actuals: [], + exactCandidates: [], + conversionCandidates: [], + id: i + }; + } + } + PullResolutionDataCache.prototype.getResolutionData = function () { + var rd = null; + + if (this.nextUp < this.cacheSize) { + rd = this.rdCache[this.nextUp]; + } + + if (rd === null) { + this.cacheSize++; + rd = { + actuals: [], + exactCandidates: [], + conversionCandidates: [], + id: this.cacheSize + }; + this.rdCache[this.cacheSize] = rd; + } + + this.nextUp++; + + return rd; + }; + + PullResolutionDataCache.prototype.returnResolutionData = function (rd) { + rd.actuals.length = 0; + rd.exactCandidates.length = 0; + rd.conversionCandidates.length = 0; + + this.nextUp = rd.id; + }; + return PullResolutionDataCache; + })(); + TypeScript.PullResolutionDataCache = PullResolutionDataCache; + + var PullAdditionalCallResolutionData = (function () { + function PullAdditionalCallResolutionData() { + this.targetSymbol = null; + this.targetTypeSymbol = null; + this.resolvedSignatures = null; + this.candidateSignature = null; + this.actualParametersContextTypeSymbols = null; + } + return PullAdditionalCallResolutionData; + })(); + TypeScript.PullAdditionalCallResolutionData = PullAdditionalCallResolutionData; + + var PullAdditionalObjectLiteralResolutionData = (function () { + function PullAdditionalObjectLiteralResolutionData() { + this.membersContextTypeSymbols = null; + } + return PullAdditionalObjectLiteralResolutionData; + })(); + TypeScript.PullAdditionalObjectLiteralResolutionData = PullAdditionalObjectLiteralResolutionData; + + var PullTypeResolver = (function () { + function PullTypeResolver(compilationSettings, semanticInfoChain, unitPath) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this.unitPath = unitPath; + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this.cachedFunctionArgumentsSymbol = null; + this.assignableCache = {}; + this.subtypeCache = {}; + this.identicalCache = {}; + this.resolutionDataCache = new PullResolutionDataCache(); + this.currentUnit = null; + this.cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 1024 /* Variable */); + this.cachedFunctionArgumentsSymbol.setType(this.cachedIArgumentsInterfaceType() ? this.cachedIArgumentsInterfaceType() : this.semanticInfoChain.anyTypeSymbol); + this.cachedFunctionArgumentsSymbol.setResolved(); + + var functionArgumentsDecl = new TypeScript.PullDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, new TypeScript.TextSpan(0, 0), unitPath); + functionArgumentsDecl.setSymbol(this.cachedFunctionArgumentsSymbol); + this.cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); + + this.currentUnit = this.semanticInfoChain.getUnit(unitPath); + } + PullTypeResolver.prototype.cleanCachedGlobals = function () { + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this.cachedFunctionArgumentsSymbol = null; + + this.identicalCache = {}; + this.subtypeCache = {}; + this.assignableCache = {}; + }; + + PullTypeResolver.prototype.cachedArrayInterfaceType = function () { + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */); + } + + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedArrayInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedArrayInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedArrayInterfaceType; + }; + + PullTypeResolver.prototype.getCachedArrayType = function () { + return this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.cachedNumberInterfaceType = function () { + if (!this._cachedNumberInterfaceType) { + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */); + } + + if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedNumberInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedNumberInterfaceType; + }; + + PullTypeResolver.prototype.cachedStringInterfaceType = function () { + if (!this._cachedStringInterfaceType) { + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */); + } + + if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedStringInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedStringInterfaceType; + }; + + PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { + if (!this._cachedBooleanInterfaceType) { + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */); + } + + if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedBooleanInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedBooleanInterfaceType; + }; + + PullTypeResolver.prototype.cachedObjectInterfaceType = function () { + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */); + } + + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedObjectInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedObjectInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { + if (!this._cachedFunctionInterfaceType) { + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */); + } + + if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedFunctionInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedFunctionInterfaceType; + }; + + PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { + if (!this._cachedIArgumentsInterfaceType) { + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */); + } + + if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedIArgumentsInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedIArgumentsInterfaceType; + }; + + PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { + if (!this._cachedRegExpInterfaceType) { + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */); + } + + if (!this._cachedRegExpInterfaceType.isResolved()) { + this.resolveDeclaredSymbol(this._cachedRegExpInterfaceType, null, new TypeScript.PullTypeResolutionContext()); + } + + return this._cachedRegExpInterfaceType; + }; + + PullTypeResolver.prototype.getUnitPath = function () { + return this.unitPath; + }; + + PullTypeResolver.prototype.setUnitPath = function (unitPath) { + this.unitPath = unitPath; + + this.currentUnit = this.semanticInfoChain.getUnit(unitPath); + }; + + PullTypeResolver.prototype.getDeclForAST = function (ast) { + return this.semanticInfoChain.getDeclForAST(ast, this.unitPath); + }; + + PullTypeResolver.prototype.getSymbolAndDiagnosticsForAST = function (ast) { + return this.semanticInfoChain.getSymbolAndDiagnosticsForAST(ast, this.unitPath); + }; + + PullTypeResolver.prototype.setSymbolAndDiagnosticsForAST = function (ast, symbolAndDiagnostics, context) { + if (context && (context.inProvisionalResolution() || context.inSpecialization)) { + return; + } + + this.semanticInfoChain.setSymbolAndDiagnosticsForAST(ast, symbolAndDiagnostics, this.unitPath); + }; + + PullTypeResolver.prototype.getASTForSymbol = function (symbol) { + return this.semanticInfoChain.getASTForSymbol(symbol, this.unitPath); + }; + + PullTypeResolver.prototype.getASTForDecl = function (decl) { + return this.semanticInfoChain.getASTForDecl(decl); + }; + + PullTypeResolver.prototype.getNewErrorTypeSymbol = function (diagnostic, data) { + return new TypeScript.PullErrorTypeSymbol(diagnostic, this.semanticInfoChain.anyTypeSymbol, data); + }; + + PullTypeResolver.prototype.getEnclosingDecl = function (decl) { + var declPath = TypeScript.getPathToDecl(decl); + + if (!declPath.length) { + return null; + } else if (declPath.length > 1 && declPath[declPath.length - 1] === decl) { + return declPath[declPath.length - 2]; + } else { + return declPath[declPath.length - 1]; + } + }; + + PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { + if (!(symbol.getKind() & (65536 /* Method */ | 4096 /* Property */))) { + var containerType = !parent.isContainer() ? parent.getAssociatedContainerType() : parent; + + if (containerType && containerType.isContainer() && !TypeScript.PullHelpers.symbolIsEnum(parent)) { + if (symbol.hasFlag(1 /* Exported */)) { + return symbol; + } + + return null; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.getMemberSymbol = function (symbolName, declSearchKind, parent, searchContainedMembers) { + if (typeof searchContainedMembers === "undefined") { searchContainedMembers = false; } + var member = null; + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + member = parent.findMember(symbolName); + } else { + member = parent.findNestedType(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var containerType = parent.getAssociatedContainerType(); + + if (containerType) { + if (containerType.isClass()) { + return null; + } + + parent = containerType; + } + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + member = parent.findMember(symbolName); + } else { + member = parent.findNestedType(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var typeDeclarations = parent.getDeclarations(); + var childDecls = null; + + for (var j = 0; j < typeDeclarations.length; j++) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); + } + } + }; + + PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var symbol = null; + + var decl = null; + var childDecls; + var declSymbol = null; + var declMembers; + var pathDeclKind; + var valDecl = null; + var kind; + var instanceSymbol = null; + var instanceType = null; + var childSymbol = null; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.getKind(); + + if (decl.getFlags() & 2097152 /* DeclaredInAWithBlock */) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (pathDeclKind & (4 /* Container */ | 32 /* DynamicModule */)) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return childDecls[0].getSymbol(); + } + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + valDecl = childDecls[0]; + + if (valDecl) { + return valDecl.getSymbol(); + } + } + + instanceSymbol = (decl.getSymbol()).getInstanceSymbol(); + + if (instanceSymbol) { + instanceType = instanceSymbol.getType(); + + childSymbol = this.getMemberSymbol(symbolName, declSearchKind, instanceType); + + if (childSymbol && (childSymbol.getKind() & declSearchKind)) { + return childSymbol; + } + } + + childDecls = decl.searchChildDecls(symbolName, 256 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + + if (sym.isAlias()) { + return sym; + } + } + + valDecl = decl.getValueDecl(); + + if (valDecl) { + decl = valDecl; + } + } + + declSymbol = decl.getSymbol().getType(); + + var childSymbol = this.getMemberSymbol(symbolName, declSearchKind, declSymbol); + + if (childSymbol) { + return childSymbol; + } + } else if ((declSearchKind & (TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer)) || !(pathDeclKind & 8 /* Class */)) { + var candidateSymbol = null; + + if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === (decl).getFunctionExpressionName()) { + candidateSymbol = decl.getSymbol(); + } + + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + if (decl.getKind() & TypeScript.PullElementKind.SomeFunction) { + decl.ensureSymbolIsBound(); + } + return childDecls[0].getSymbol(); + } + + if (candidateSymbol) { + return candidateSymbol; + } + + if (declSearchKind & TypeScript.PullElementKind.SomeValue) { + childDecls = decl.searchChildDecls(symbolName, 256 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + + if (sym.isAlias()) { + return sym; + } + } + } + } + } + + symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + + return symbol; + }; + + PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { + var result = []; + var decl = null; + var childDecls; + var pathDeclKind; + var parameters; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.getKind(); + var declSymbol = decl.getSymbol(); + var declKind = decl.getKind(); + + if (declKind !== 8 /* Class */ && declKind !== 16 /* Interface */) { + this.addFilteredDecls(decl.getChildDecls(), declSearchKind, result); + } + + switch (declKind) { + case 4 /* Container */: + case 32 /* DynamicModule */: + if (declSymbol) { + var otherDecls = declSymbol.getDeclarations(); + for (var j = 0, m = otherDecls.length; j < m; j++) { + var otherDecl = otherDecls[j]; + if (otherDecl === decl) { + continue; + } + + var otherDeclChildren = otherDecl.getChildDecls(); + for (var k = 0, s = otherDeclChildren.length; k < s; k++) { + var otherDeclChild = otherDeclChildren[k]; + if ((otherDeclChild.getFlags() & 1 /* Exported */) && (otherDeclChild.getKind() & declSearchKind)) { + result.push(otherDeclChild); + } + } + } + } + + break; + + case 8 /* Class */: + case 16 /* Interface */: + if (declSymbol && declSymbol.isGeneric()) { + parameters = declSymbol.getTypeParameters(); + for (var k = 0; k < parameters.length; k++) { + result.push(parameters[k].getDeclarations()[0]); + } + } + + break; + + case 131072 /* FunctionExpression */: + var functionExpressionName = (decl).getFunctionExpressionName(); + if (declSymbol && functionExpressionName) { + result.push(declSymbol.getDeclarations()[0]); + } + + case 16384 /* Function */: + case 32768 /* ConstructorMethod */: + case 65536 /* Method */: + if (declSymbol) { + var functionType = declSymbol.getType(); + if (functionType.getHasGenericSignature()) { + var signatures = (pathDeclKind === 32768 /* ConstructorMethod */) ? functionType.getConstructSignatures() : functionType.getCallSignatures(); + if (signatures && signatures.length) { + for (var j = 0; j < signatures.length; j++) { + var signature = signatures[j]; + if (signature.isGeneric()) { + parameters = signature.getTypeParameters(); + for (var k = 0; k < parameters.length; k++) { + result.push(parameters[k].getDeclarations()[0]); + } + } + } + } + } + } + + break; + } + } + + var units = this.semanticInfoChain.units; + for (var i = 0, n = units.length; i < n; i++) { + var unit = units[i]; + if (unit === this.currentUnit && declPath.length != 0) { + continue; + } + var topLevelDecls = unit.getTopLevelDecls(); + if (topLevelDecls.length) { + for (var j = 0, m = topLevelDecls.length; j < m; j++) { + var topLevelDecl = topLevelDecls[j]; + if (topLevelDecl.getKind() === 1 /* Script */ || topLevelDecl.getKind() === 0 /* Global */) { + this.addFilteredDecls(topLevelDecl.getChildDecls(), declSearchKind, result); + } + } + } + } + + return result; + }; + + PullTypeResolver.prototype.addFilteredDecls = function (decls, declSearchKind, result) { + if (decls.length) { + for (var i = 0, n = decls.length; i < n; i++) { + var decl = decls[i]; + if (decl.getKind() & declSearchKind) { + result.push(decl); + } + } + } + }; + + PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl, context) { + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + + if (enclosingDecl && !declPath.length) { + declPath = [enclosingDecl]; + } + + var declSearchKind = TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer | TypeScript.PullElementKind.SomeValue; + + return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); + }; + + PullTypeResolver.prototype.getVisibleContextSymbols = function (enclosingDecl, context) { + var contextualTypeSymbol = context.getContextualType(); + if (!contextualTypeSymbol || this.isAnyOrEquivalent(contextualTypeSymbol)) { + return null; + } + + var declSearchKind = TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer | TypeScript.PullElementKind.SomeValue; + var members = contextualTypeSymbol.getAllMembers(declSearchKind, false); + + for (var i = 0; i < members.length; i++) { + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { + var prevCanUseTypeSymbol = context.canUseTypeSymbol; + context.canUseTypeSymbol = true; + var lhs = this.resolveAST(expression, false, enclosingDecl, context).symbol; + context.canUseTypeSymbol = prevCanUseTypeSymbol; + var lhsType = lhs.getType(); + + if (!lhsType) { + return null; + } + + if (this.isAnyOrEquivalent(lhsType)) { + return null; + } + + if (!lhsType.isResolved()) { + this.resolveDeclaredSymbol(lhsType, enclosingDecl, context); + } + + var includePrivate = false; + var containerSymbol = lhsType; + if (containerSymbol.getKind() === 33554432 /* ConstructorType */) { + containerSymbol = containerSymbol.getConstructSignatures()[0].getReturnType(); + } + + if (containerSymbol && containerSymbol.isClass()) { + var declPath = TypeScript.getPathToDecl(enclosingDecl); + if (declPath && declPath.length) { + var declarations = containerSymbol.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + var declaration = declarations[i]; + if (declPath.indexOf(declaration) >= 0) { + includePrivate = true; + break; + } + } + } + } + + var declSearchKind = TypeScript.PullElementKind.SomeType | TypeScript.PullElementKind.SomeContainer | TypeScript.PullElementKind.SomeValue; + + var members = []; + + if (lhsType.isContainer()) { + if ((lhsType).getExportAssignedContainerSymbol()) { + lhsType = (lhsType).getExportAssignedContainerSymbol(); + } + } + + if (lhsType.isTypeParameter()) { + var constraint = (lhsType).getConstraint(); + + if (constraint) { + lhsType = constraint; + members = lhsType.getAllMembers(declSearchKind, false); + } + } else { + if (lhs.getKind() == 67108864 /* EnumMember */) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } + + if (lhsType === this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { + lhsType = this.cachedNumberInterfaceType(); + } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { + lhsType = this.cachedStringInterfaceType(); + } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { + lhsType = this.cachedBooleanInterfaceType(); + } + + if (!lhsType.isResolved()) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, enclosingDecl, context); + + if (potentiallySpecializedType != lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + members = lhsType.getAllMembers(declSearchKind, includePrivate); + + if (lhsType.isContainer()) { + var associatedInstance = (lhsType).getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.getType(); + if (!instanceType.isResolved()) { + this.resolveDeclaredSymbol(instanceType, enclosingDecl, context); + } + var instanceMembers = instanceType.getAllMembers(declSearchKind, includePrivate); + members = members.concat(instanceMembers); + } + } else if (lhsType.isConstructor()) { + var prototypeStr = "prototype"; + var prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); + var parentDecl = lhsType.getDeclarations()[0]; + var prototypeDecl = new TypeScript.PullDecl(prototypeStr, prototypeStr, parentDecl.getKind(), parentDecl.getFlags(), parentDecl.getSpan(), parentDecl.getScriptName()); + this.currentUnit.addSynthesizedDecl(prototypeDecl); + prototypeDecl.setParentDecl(parentDecl); + prototypeSymbol.addDeclaration(prototypeDecl); + + members.push(prototypeSymbol); + } else { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.getType(); + if (!containerType.isResolved()) { + this.resolveDeclaredSymbol(containerType, enclosingDecl, context); + } + var containerMembers = containerType.getAllMembers(declSearchKind, includePrivate); + members = members.concat(containerMembers); + } + } + } + + if (lhsType.getCallSignatures().length && this.cachedFunctionInterfaceType()) { + members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, false)); + } + + for (var i = 0; i < members.length; i++) { + if (!members[i].isResolved()) { + this.resolveDeclaredSymbol(members[i], enclosingDecl, context); + } + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.isAnyOrEquivalent = function (type) { + return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); + }; + + PullTypeResolver.prototype.isNumberOrEquivalent = function (type) { + return (type === this.semanticInfoChain.numberTypeSymbol) || (this.cachedNumberInterfaceType() && type === this.cachedNumberInterfaceType()); + }; + + PullTypeResolver.prototype.isTypeArgumentOrWrapper = function (type) { + if (!type) { + return false; + } + + if (!type.isGeneric()) { + return false; + } + + if (type.isTypeParameter()) { + return true; + } + + if (type.isArray()) { + return this.isTypeArgumentOrWrapper((type).getElementType()); + } + + var typeArguments = type.getTypeArguments(); + + if (typeArguments) { + for (var i = 0; i < typeArguments.length; i++) { + if (this.isTypeArgumentOrWrapper(typeArguments[i])) { + return true; + } + } + } else { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.isArrayOrEquivalent = function (type) { + return (type.isArray() && (type).getElementType()) || type == this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.findTypeSymbolForDynamicModule = function (idText, currentFileName, search) { + var originalIdText = idText; + var symbol = search(idText); + + if (symbol === null) { + if (!symbol) { + idText = TypeScript.swapQuotes(originalIdText); + symbol = search(idText); + } + + if (!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".ts"; + symbol = search(idText); + } + + if (!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; + symbol = search(idText); + } + + if (!symbol && !TypeScript.isRelative(originalIdText)) { + idText = originalIdText; + + var strippedIdText = TypeScript.stripQuotes(idText); + + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + + while (symbol === null && path != "") { + idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); + symbol = search(idText); + + if (symbol === null) { + idText = TypeScript.changePathToDTS(idText); + symbol = search(idText); + } + + if (symbol === null) { + if (path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbol = function (symbol, enclosingDecl, context) { + var savedResolvingTypeReference = context.resolvingTypeReference; + context.resolvingTypeReference = false; + + var result = this.resolveDeclaredSymbolWorker(symbol, enclosingDecl, context); + context.resolvingTypeReference = savedResolvingTypeReference; + + return result; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbolWorker = function (symbol, enclosingDecl, context) { + if (!symbol || symbol.isResolved()) { + return symbol; + } + + if (symbol.isResolving()) { + if (!symbol.currentlyBeingSpecialized()) { + if (!symbol.isType()) { + symbol.setType(this.semanticInfoChain.anyTypeSymbol); + } + + return symbol; + } + } + + var thisUnit = this.unitPath; + + var decls = symbol.getDeclarations(); + + var ast = null; + + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + + ast = this.semanticInfoChain.getASTForDecl(decl); + + if (!ast || ast.nodeType === 80 /* Member */) { + this.setUnitPath(thisUnit); + return symbol; + } + + this.setUnitPath(decl.getScriptName()); + this.resolveAST(ast, false, enclosingDecl, context); + } + + var typeArgs = symbol.isType() ? (symbol).getTypeArguments() : null; + + if (typeArgs && typeArgs.length) { + var typeParameters = (symbol).getTypeParameters(); + var typeCache = {}; + + for (var i = 0; i < typeParameters.length; i++) { + typeCache[typeParameters[i].getSymbolID().toString()] = typeArgs[i]; + } + + context.pushTypeSpecializationCache(typeCache); + var rootType = TypeScript.getRootType(symbol.getType()); + + var specializedSymbol = TypeScript.specializeType(rootType, typeArgs, this, enclosingDecl, context, ast); + + context.popTypeSpecializationCache(); + + symbol = specializedSymbol; + } + + this.setUnitPath(thisUnit); + + return symbol; + }; + + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { + var containerDecl = this.getDeclForAST(ast); + var containerSymbol = containerDecl.getSymbol(); + + if (containerSymbol.isResolved()) { + return containerSymbol; + } + + containerSymbol.setResolved(); + + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + if (containerDecl.getKind() != 64 /* Enum */) { + var instanceSymbol = containerSymbol.getInstanceSymbol(); + + if (instanceSymbol) { + this.resolveDeclaredSymbol(instanceSymbol, containerDecl.getParentDecl(), context); + } + + var members = ast.members.members; + + for (var i = 0; i < members.length; i++) { + if (members[i].nodeType == 87 /* ExportAssignment */) { + this.resolveExportAssignmentStatement(members[i], containerDecl, context); + break; + } + } + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (typeRef) { + if (typeRef.nodeType != 11 /* TypeRef */) { + return false; + } + + if (typeRef.term.nodeType == 20 /* Name */) { + return true; + } else if (typeRef.term.nodeType == 32 /* MemberAccessExpression */) { + var binex = typeRef.term; + + if (binex.operand2.nodeType == 20 /* Name */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.resolveReferenceTypeDeclaration = function (typeDeclAST, context) { + var typeDecl = this.getDeclForAST(typeDeclAST); + var enclosingDecl = this.getEnclosingDecl(typeDecl); + var typeDeclSymbol = typeDecl.getSymbol(); + var typeDeclIsClass = typeDeclAST.nodeType === 13 /* ClassDeclaration */; + var hasVisited = this.getSymbolAndDiagnosticsForAST(typeDeclAST) != null; + var extendedTypes = []; + var implementedTypes = []; + + if ((typeDeclSymbol.isResolved() && hasVisited) || (typeDeclSymbol.isResolving() && !context.isInBaseTypeResolution())) { + return typeDeclSymbol; + } + + var wasResolving = typeDeclSymbol.isResolving(); + typeDeclSymbol.startResolving(); + + if (!typeDeclSymbol.isResolved()) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], typeDecl, context); + } + } + + var typeRefDecls = typeDeclSymbol.getDeclarations(); + + for (var i = 0; i < typeRefDecls.length; i++) { + var childDecls = typeRefDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + var wasInBaseTypeResolution = context.startBaseTypeResolution(); + + if (!typeDeclIsClass && !hasVisited) { + typeDeclSymbol.resetKnownBaseTypeCount(); + } + + if (typeDeclAST.extendsList) { + var savedIsResolvingClassExtendedType = context.isResolvingClassExtendedType; + if (typeDeclIsClass) { + context.isResolvingClassExtendedType = true; + } + + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < typeDeclAST.extendsList.members.length; i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var parentType = this.resolveTypeReference(new TypeScript.TypeReference(typeDeclAST.extendsList.members[i], 0), typeDecl, context).symbol; + + if (typeDeclSymbol.isValidBaseKind(parentType, true)) { + var resolvedParentType = parentType; + extendedTypes[extendedTypes.length] = parentType; + if (parentType.isGeneric() && parentType.isResolved() && !parentType.getIsSpecialized()) { + parentType = this.specializeTypeToAny(parentType, enclosingDecl, context); + typeDecl.addDiagnostic(new TypeScript.Diagnostic(typeDecl.getScriptName(), typeDeclAST.minChar, typeDeclAST.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */)); + } + if (!typeDeclSymbol.hasBase(parentType)) { + this.setSymbolAndDiagnosticsForAST(typeDeclAST.extendsList.members[i], SymbolAndDiagnostics.fromSymbol(resolvedParentType), context); + typeDeclSymbol.addExtendedType(parentType); + + var specializations = typeDeclSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + specializations[j].addExtendedType(parentType); + } + } + } + } + + context.isResolvingClassExtendedType = savedIsResolvingClassExtendedType; + } + + if (!typeDeclSymbol.isResolved() && !wasResolving) { + var baseTypeSymbols = typeDeclSymbol.getExtendedTypes(); + for (var i = 0; i < baseTypeSymbols.length; i++) { + var baseType = baseTypeSymbols[i]; + + for (var j = 0; j < extendedTypes.length; j++) { + if (baseType == extendedTypes[j]) { + break; + } + } + + if (j == extendedTypes.length) { + typeDeclSymbol.removeExtendedType(baseType); + } + } + } + + if (typeDeclAST.implementsList && typeDeclIsClass) { + var extendsCount = typeDeclAST.extendsList ? typeDeclAST.extendsList.members.length : 0; + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < typeDeclAST.implementsList.members.length); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var implementedType = this.resolveTypeReference(new TypeScript.TypeReference(typeDeclAST.implementsList.members[i - extendsCount], 0), typeDecl, context).symbol; + + if (typeDeclSymbol.isValidBaseKind(implementedType, false)) { + var resolvedImplementedType = implementedType; + implementedTypes[implementedTypes.length] = implementedType; + if (implementedType.isGeneric() && implementedType.isResolved() && !implementedType.getIsSpecialized()) { + implementedType = this.specializeTypeToAny(implementedType, enclosingDecl, context); + typeDecl.addDiagnostic(new TypeScript.Diagnostic(typeDecl.getScriptName(), typeDeclAST.minChar, typeDeclAST.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */)); + this.setSymbolAndDiagnosticsForAST(typeDeclAST.implementsList.members[i - extendsCount], SymbolAndDiagnostics.fromSymbol(implementedType), context); + typeDeclSymbol.addImplementedType(implementedType); + } else if (!typeDeclSymbol.hasBase(implementedType)) { + this.setSymbolAndDiagnosticsForAST(typeDeclAST.implementsList.members[i - extendsCount], SymbolAndDiagnostics.fromSymbol(resolvedImplementedType), context); + typeDeclSymbol.addImplementedType(implementedType); + } + } + } + } + + if (!typeDeclSymbol.isResolved() && !wasResolving) { + var baseTypeSymbols = typeDeclSymbol.getImplementedTypes(); + for (var i = 0; i < baseTypeSymbols.length; i++) { + var baseType = baseTypeSymbols[i]; + + for (var j = 0; j < implementedTypes.length; j++) { + if (baseType == implementedTypes[j]) { + break; + } + } + + if (j == implementedTypes.length) { + typeDeclSymbol.removeImplementedType(baseType); + } + } + } + + context.doneBaseTypeResolution(wasInBaseTypeResolution); + if (wasInBaseTypeResolution && (typeDeclAST.implementsList || typeDeclAST.extendsList)) { + return typeDeclSymbol; + } + + if (!typeDeclSymbol.isResolved()) { + var typeDeclMembers = typeDeclSymbol.getMembers(); + for (var i = 0; i < typeDeclMembers.length; i++) { + this.resolveDeclaredSymbol(typeDeclMembers[i], typeDecl, context); + } + + if (!typeDeclIsClass) { + var callSignatures = typeDeclSymbol.getCallSignatures(); + for (var i = 0; i < callSignatures.length; i++) { + this.resolveDeclaredSymbol(callSignatures[i], typeDecl, context); + } + + var constructSignatures = typeDeclSymbol.getConstructSignatures(); + for (var i = 0; i < constructSignatures.length; i++) { + this.resolveDeclaredSymbol(constructSignatures[i], typeDecl, context); + } + + var indexSignatures = typeDeclSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignatures.length; i++) { + this.resolveDeclaredSymbol(indexSignatures[i], typeDecl, context); + } + } + } + + this.setSymbolAndDiagnosticsForAST(typeDeclAST.name, SymbolAndDiagnostics.fromSymbol(typeDeclSymbol), context); + this.setSymbolAndDiagnosticsForAST(typeDeclAST, SymbolAndDiagnostics.fromSymbol(typeDeclSymbol), context); + + typeDeclSymbol.setResolved(); + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { + var classDecl = this.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + if (classDeclSymbol.isResolved()) { + return classDeclSymbol; + } + + this.resolveReferenceTypeDeclaration(classDeclAST, context); + + var constructorMethod = classDeclSymbol.getConstructorMethod(); + var extendedTypes = classDeclSymbol.getExtendedTypes(); + var parentType = extendedTypes.length ? extendedTypes[0] : null; + + if (constructorMethod) { + var constructorTypeSymbol = constructorMethod.getType(); + + var constructSignatures = constructorTypeSymbol.getConstructSignatures(); + + if (!constructSignatures.length) { + var constructorSignature; + + if (parentType) { + var parentClass = parentType; + var parentConstructor = parentClass.getConstructorMethod(); + var parentConstructorType = parentConstructor.getType(); + var parentConstructSignatures = parentConstructorType.getConstructSignatures(); + + var parentConstructSignature; + var parentParameters; + for (var i = 0; i < parentConstructSignatures.length; i++) { + parentConstructSignature = parentConstructSignatures[i]; + parentParameters = parentConstructSignature.getParameters(); + + constructorSignature = parentConstructSignature.isDefinition() ? new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + constructorSignature.setReturnType(classDeclSymbol); + + for (var j = 0; j < parentParameters.length; j++) { + constructorSignature.addParameter(parentParameters[j], parentParameters[j].getIsOptional()); + } + + var typeParameters = constructorTypeSymbol.getTypeParameters(); + + for (var j = 0; j < typeParameters.length; j++) { + constructorSignature.addTypeParameter(typeParameters[j]); + } + + constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorSignature.addDeclaration(classDecl); + } + } else { + constructorSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + constructorSignature.setReturnType(classDeclSymbol); + constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorSignature.addDeclaration(classDecl); + + var typeParameters = constructorTypeSymbol.getTypeParameters(); + + for (var i = 0; i < typeParameters.length; i++) { + constructorSignature.addTypeParameter(typeParameters[i]); + } + } + } + + if (!classDeclSymbol.isResolved()) { + return classDeclSymbol; + } + + var constructorMembers = constructorTypeSymbol.getMembers(); + + this.resolveDeclaredSymbol(constructorMethod, classDecl, context); + + for (var i = 0; i < constructorMembers.length; i++) { + this.resolveDeclaredSymbol(constructorMembers[i], classDecl, context); + } + + if (parentType) { + var parentConstructorSymbol = (parentType).getConstructorMethod(); + var parentConstructorTypeSymbol = parentConstructorSymbol.getType(); + + if (!constructorTypeSymbol.hasBase(parentConstructorTypeSymbol)) { + constructorTypeSymbol.addExtendedType(parentConstructorTypeSymbol); + } + } + } + + return classDeclSymbol; + }; + + PullTypeResolver.prototype.resolveInterfaceDeclaration = function (interfaceDeclAST, context) { + var interfaceDecl = this.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveReferenceTypeDeclaration(interfaceDeclAST, context); + return interfaceDeclSymbol; + }; + + PullTypeResolver.prototype.resolveImportDeclaration = function (importStatementAST, context) { + var _this = this; + var importDecl = this.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + var aliasName = importStatementAST.id.text; + var aliasedType = null; + + if (importDeclSymbol.isResolved()) { + return importDeclSymbol; + } + + importDeclSymbol.startResolving(); + + if (importStatementAST.alias.nodeType === 11 /* TypeRef */) { + aliasedType = this.resolveTypeReference(importStatementAST.alias, enclosingDecl, context).symbol; + } else if (importStatementAST.alias.nodeType === 20 /* Name */) { + var text = (importStatementAST.alias).actualText; + + if (!TypeScript.isQuoted(text)) { + aliasedType = this.resolveTypeReference(new TypeScript.TypeReference(importStatementAST.alias, 0), enclosingDecl, context).symbol; + } else { + var modPath = (importStatementAST.alias).actualText; + var declPath = TypeScript.getPathToDecl(enclosingDecl); + + importStatementAST.isDynamicImport = true; + + aliasedType = this.findTypeSymbolForDynamicModule(modPath, importDecl.getScriptName(), function (s) { + return _this.getSymbolFromDeclPath(s, declPath, TypeScript.PullElementKind.SomeContainer); + }); + + if (!aliasedType) { + importDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.currentUnit.getPath(), importStatementAST.minChar, importStatementAST.getLength(), 140 /* Unable_to_resolve_external_module__0_ */, [text])); + aliasedType = this.semanticInfoChain.anyTypeSymbol; + } + } + } + + if (aliasedType) { + if (!aliasedType.isContainer()) { + importDecl.addDiagnostic(new TypeScript.Diagnostic(this.currentUnit.getPath(), importStatementAST.minChar, importStatementAST.getLength(), 141 /* Module_cannot_be_aliased_to_a_non_module_type */)); + aliasedType = this.semanticInfoChain.anyTypeSymbol; + } else if ((aliasedType).getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + + importDeclSymbol.setAliasedType(aliasedType); + importDeclSymbol.setResolved(); + + this.semanticInfoChain.setSymbolAndDiagnosticsForAST(importStatementAST.alias, SymbolAndDiagnostics.fromSymbol(aliasedType), this.unitPath); + } + + return importDeclSymbol; + }; + + PullTypeResolver.prototype.resolveExportAssignmentStatement = function (exportAssignmentAST, enclosingDecl, context) { + var id = exportAssignmentAST.id.text; + var valueSymbol = null; + var typeSymbol = null; + var containerSymbol = null; + + var parentSymbol = enclosingDecl.getSymbol(); + + if (!parentSymbol.isType() && (parentSymbol).isContainer()) { + enclosingDecl.addDiagnostic(new TypeScript.Diagnostic(enclosingDecl.getScriptName(), exportAssignmentAST.minChar, exportAssignmentAST.getLength(), 230 /* Export_assignments_may_only_be_used_in_External_modules */)); + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var declPath = enclosingDecl !== null ? [enclosingDecl] : []; + + containerSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeContainer); + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.getKind() & TypeScript.PullElementKind.AcceptableAlias) != 0; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.getKind() == 256 /* TypeAlias */) { + if (!containerSymbol.isResolved()) { + this.resolveDeclaredSymbol(containerSymbol, enclosingDecl, context); + } + var aliasedType = (containerSymbol).getType(); + + if (aliasedType.getKind() != 32 /* DynamicModule */) { + acceptableAlias = true; + } else { + var aliasedAssignedValue = (containerSymbol).getExportAssignedValueSymbol(); + var aliasedAssignedType = (containerSymbol).getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = (containerSymbol).getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + if (aliasedAssignedValue) { + valueSymbol = aliasedAssignedValue; + } + if (aliasedAssignedType) { + typeSymbol = aliasedAssignedType; + } + if (aliasedAssignedContainer) { + containerSymbol = aliasedAssignedContainer; + } + acceptableAlias = true; + } + } + } + + if (!acceptableAlias) { + enclosingDecl.addDiagnostic(new TypeScript.Diagnostic(enclosingDecl.getScriptName(), exportAssignmentAST.minChar, exportAssignmentAST.getLength(), 231 /* Export_assignments_may_only_be_made_with_acceptable_kinds */)); + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + } + + if (!valueSymbol) { + valueSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeValue); + } + if (!typeSymbol) { + typeSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeType); + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + return SymbolAndDiagnostics.create(this.semanticInfoChain.voidTypeSymbol, [context.postError(enclosingDecl.getScriptName(), exportAssignmentAST.minChar, exportAssignmentAST.getLength(), 164 /* Could_not_find_symbol__0_ */, [id])]); + } + + if (valueSymbol) { + if (!valueSymbol.isResolved()) { + this.resolveDeclaredSymbol(valueSymbol, enclosingDecl, context); + } + (parentSymbol).setExportAssignedValueSymbol(valueSymbol); + } + if (typeSymbol) { + if (!typeSymbol.isResolved()) { + this.resolveDeclaredSymbol(typeSymbol, enclosingDecl, context); + } + + (parentSymbol).setExportAssignedTypeSymbol(typeSymbol); + } + if (containerSymbol) { + if (!containerSymbol.isResolved()) { + this.resolveDeclaredSymbol(containerSymbol, enclosingDecl, context); + } + + (parentSymbol).setExportAssignedContainerSymbol(containerSymbol); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignature = function (funcDeclAST, enclosingDecl, context) { + var funcDeclSymbol = null; + + var functionDecl = this.getDeclForAST(funcDeclAST); + + if (!functionDecl || !functionDecl.hasSymbol()) { + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + if (enclosingDecl) { + declCollectionContext.pushParent(enclosingDecl); + } + + TypeScript.getAstWalkerFactory().walk(funcDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + functionDecl = this.getDeclForAST(funcDeclAST); + this.currentUnit.addSynthesizedDecl(functionDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + binder.setUnit(this.unitPath); + if (functionDecl.getKind() === 33554432 /* ConstructorType */) { + binder.bindConstructorTypeDeclarationToPullSymbol(functionDecl); + } else { + binder.bindFunctionTypeDeclarationToPullSymbol(functionDecl); + } + } + + funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.getKind() === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, enclosingDecl, context).symbol; + + signature.setReturnType(returnTypeSymbol); + + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + + if (funcDeclSymbol) { + funcDeclSymbol.getType().setHasGenericSignature(); + } + } + } else { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveFunctionTypeSignatureParameter(funcDeclAST.arguments.members[i], signature, enclosingDecl, context); + } + } + + if (funcDeclSymbol && signature.hasGenericParameter()) { + funcDeclSymbol.getType().setHasGenericSignature(); + } + + if (signature.hasGenericParameter()) { + if (funcDeclSymbol) { + funcDeclSymbol.getType().setHasGenericSignature(); + } + } + + funcDeclSymbol.setResolved(); + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignatureParameter = function (argDeclAST, signature, enclosingDecl, context) { + var paramDecl = this.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeExpr) { + var typeRef = this.resolveTypeReference(argDeclAST.typeExpr, enclosingDecl, context).symbol; + + if (paramSymbol.getIsVarArg() && !(typeRef.isArray() || typeRef == this.cachedArrayInterfaceType())) { + var diagnostic = context.postError(this.unitPath, argDeclAST.minChar, argDeclAST.getLength(), 228 /* Rest_parameters_must_be_array_types */, null, enclosingDecl); + typeRef = this.getNewErrorTypeSymbol(diagnostic); + } + + context.setTypeInContext(paramSymbol, typeRef); + + if (this.isTypeArgumentOrWrapper(typeRef)) { + signature.setHasGenericParameter(); + } + } else { + if (paramSymbol.getIsVarArg() && paramSymbol.getType()) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, TypeScript.specializeToArrayType(this.cachedArrayInterfaceType(), paramSymbol.getType(), this, context)); + } else { + context.setTypeInContext(paramSymbol, paramSymbol.getType()); + } + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveFunctionExpressionParameter = function (argDeclAST, contextParam, enclosingDecl, context) { + var paramDecl = this.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeExpr) { + var typeRef = this.resolveTypeReference(argDeclAST.typeExpr, enclosingDecl, context).symbol; + + if (paramSymbol.getIsVarArg() && !(typeRef.isArray() || typeRef == this.cachedArrayInterfaceType())) { + var diagnostic = context.postError(this.unitPath, argDeclAST.minChar, argDeclAST.getLength(), 228 /* Rest_parameters_must_be_array_types */, null, enclosingDecl); + typeRef = this.getNewErrorTypeSymbol(diagnostic); + } + + context.setTypeInContext(paramSymbol, typeRef); + } else { + if (paramSymbol.getIsVarArg() && paramSymbol.getType()) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, TypeScript.specializeToArrayType(this.cachedArrayInterfaceType(), paramSymbol.getType(), this, context)); + } else { + context.setTypeInContext(paramSymbol, paramSymbol.getType()); + } + } else if (contextParam) { + context.setTypeInContext(paramSymbol, contextParam.getType()); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveInterfaceTypeReference = function (interfaceDeclAST, enclosingDecl, context) { + var interfaceSymbol = null; + + var interfaceDecl = this.getDeclForAST(interfaceDeclAST); + + if (!interfaceDecl) { + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + if (enclosingDecl) { + declCollectionContext.pushParent(enclosingDecl); + } + + TypeScript.getAstWalkerFactory().walk(interfaceDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var interfaceDecl = this.getDeclForAST(interfaceDeclAST); + this.currentUnit.addSynthesizedDecl(interfaceDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + + binder.setUnit(this.unitPath); + binder.bindObjectTypeDeclarationToPullSymbol(interfaceDecl); + } + + interfaceSymbol = interfaceDecl.getSymbol(); + + if (interfaceDeclAST.members) { + var memberDecl = null; + var memberSymbol = null; + var memberType = null; + var typeMembers = interfaceDeclAST.members; + + for (var i = 0; i < typeMembers.members.length; i++) { + memberDecl = this.getDeclForAST(typeMembers.members[i]); + memberSymbol = (memberDecl.getKind() & TypeScript.PullElementKind.SomeSignature) ? memberDecl.getSignatureSymbol() : memberDecl.getSymbol(); + + this.resolveDeclaredSymbol(memberSymbol, enclosingDecl, context); + + memberType = memberSymbol.getType(); + + if ((memberType && memberType.isGeneric()) || (memberSymbol.isSignature() && (memberSymbol).isGeneric())) { + interfaceSymbol.setHasGenericMember(); + } + } + } + + interfaceSymbol.setResolved(); + + return interfaceSymbol; + }; + + PullTypeResolver.prototype.resolveTypeReference = function (typeRef, enclosingDecl, context) { + if (typeRef === null) { + return null; + } + + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(typeRef); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeTypeReferenceSymbol(typeRef, enclosingDecl, context); + + if (!symbolAndDiagnostics.symbol.isGeneric()) { + this.setSymbolAndDiagnosticsForAST(typeRef, symbolAndDiagnostics, context); + } + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (typeRef, enclosingDecl, context) { + var typeDeclSymbol = null; + var diagnostic = null; + var symbolAndDiagnostic = null; + + if (typeRef.term.nodeType === 20 /* Name */) { + var prevResolvingTypeReference = context.resolvingTypeReference; + context.resolvingTypeReference = true; + symbolAndDiagnostic = this.resolveTypeNameExpression(typeRef.term, enclosingDecl, context); + typeDeclSymbol = symbolAndDiagnostic.symbol; + + context.resolvingTypeReference = prevResolvingTypeReference; + } else if (typeRef.term.nodeType === 12 /* FunctionDeclaration */) { + typeDeclSymbol = this.resolveFunctionTypeSignature(typeRef.term, enclosingDecl, context); + } else if (typeRef.term.nodeType === 14 /* InterfaceDeclaration */) { + typeDeclSymbol = this.resolveInterfaceTypeReference(typeRef.term, enclosingDecl, context); + } else if (typeRef.term.nodeType === 10 /* GenericType */) { + symbolAndDiagnostic = this.resolveGenericTypeReference(typeRef.term, enclosingDecl, context); + typeDeclSymbol = symbolAndDiagnostic.symbol; + } else if (typeRef.term.nodeType === 32 /* MemberAccessExpression */) { + var dottedName = typeRef.term; + + prevResolvingTypeReference = context.resolvingTypeReference; + symbolAndDiagnostic = this.resolveDottedTypeNameExpression(dottedName, enclosingDecl, context); + typeDeclSymbol = symbolAndDiagnostic.symbol; + context.resolvingTypeReference = prevResolvingTypeReference; + } else if (typeRef.term.nodeType === 5 /* StringLiteral */) { + var stringConstantAST = typeRef.term; + typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.actualText); + var decl = new TypeScript.PullDecl(stringConstantAST.actualText, stringConstantAST.actualText, typeDeclSymbol.getKind(), null, new TypeScript.TextSpan(stringConstantAST.minChar, stringConstantAST.getLength()), enclosingDecl.getScriptName()); + this.currentUnit.addSynthesizedDecl(decl); + typeDeclSymbol.addDeclaration(decl); + } + + if (!typeDeclSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, typeRef.term.minChar, typeRef.term.getLength(), 146 /* Unable_to_resolve_type */)]); + } + + if (typeDeclSymbol.isError()) { + return SymbolAndDiagnostics.fromSymbol(typeDeclSymbol); + } + + if (typeRef.arrayCount) { + var arraySymbol = typeDeclSymbol.getArrayType(); + + if (!arraySymbol) { + if (!this.cachedArrayInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedArrayInterfaceType(), enclosingDecl, context); + } + + if (typeDeclSymbol.isNamedTypeSymbol() && typeDeclSymbol.isGeneric() && !typeDeclSymbol.isTypeParameter() && typeDeclSymbol.isResolved() && !typeDeclSymbol.getIsSpecialized() && typeDeclSymbol.getTypeParameters().length && (typeDeclSymbol.getTypeArguments() == null && !this.isArrayOrEquivalent(typeDeclSymbol)) && this.isTypeRefWithoutTypeArgs(typeRef)) { + context.postError(this.unitPath, typeRef.minChar, typeRef.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + typeDeclSymbol = this.specializeTypeToAny(typeDeclSymbol, enclosingDecl, context); + } + + arraySymbol = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, typeDeclSymbol, this, context); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (typeRef.arrayCount > 1) { + for (var arity = typeRef.arrayCount - 1; arity > 0; arity--) { + var existingArraySymbol = arraySymbol.getArrayType(); + + if (!existingArraySymbol) { + arraySymbol = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, arraySymbol, this, context); + } else { + arraySymbol = existingArraySymbol; + } + } + } + + typeDeclSymbol = arraySymbol; + } + + return SymbolAndDiagnostics.fromSymbol(typeDeclSymbol); + }; + + PullTypeResolver.prototype.resolveVariableDeclaration = function (varDecl, context, enclosingDecl) { + var decl = this.getDeclForAST(varDecl); + + if (enclosingDecl && decl.getKind() == 2048 /* Parameter */) { + enclosingDecl.ensureSymbolIsBound(); + } + + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (declSymbol.isResolved()) { + var declType = declSymbol.getType(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + var valSymbol = valDecl.getSymbol(); + + if (valSymbol && !valSymbol.isResolved()) { + valSymbol.setType(declType); + valSymbol.setResolved(); + } + } + + return declType; + } + + if (declSymbol.isResolving()) { + if (!context.inSpecialization) { + declSymbol.setType(this.semanticInfoChain.anyTypeSymbol); + declSymbol.setResolved(); + return declSymbol; + } + } + + declSymbol.startResolving(); + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + + var diagnostic = null; + + if (varDecl.typeExpr) { + var typeExprSymbol = this.resolveTypeReference(varDecl.typeExpr, wrapperDecl, context).symbol; + + if (!typeExprSymbol) { + diagnostic = context.postError(this.unitPath, varDecl.minChar, varDecl.getLength(), 147 /* Unable_to_resolve_type_of__0_ */, [varDecl.id.actualText], decl); + declSymbol.setType(this.getNewErrorTypeSymbol(diagnostic)); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else if (typeExprSymbol.isError()) { + context.setTypeInContext(declSymbol, typeExprSymbol); + } else { + if (typeExprSymbol.isNamedTypeSymbol() && typeExprSymbol.isGeneric() && !typeExprSymbol.isTypeParameter() && typeExprSymbol.isResolved() && !typeExprSymbol.getIsSpecialized() && typeExprSymbol.getTypeParameters().length && (typeExprSymbol.getTypeArguments() == null && !this.isArrayOrEquivalent(typeExprSymbol)) && this.isTypeRefWithoutTypeArgs(varDecl.typeExpr)) { + context.postError(this.unitPath, varDecl.typeExpr.minChar, varDecl.typeExpr.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + typeExprSymbol = this.specializeTypeToAny(typeExprSymbol, enclosingDecl, context); + } + + if (typeExprSymbol.isContainer()) { + var exportedTypeSymbol = (typeExprSymbol).getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceSymbol = (typeExprSymbol.getType()).getInstanceSymbol(); + + if (!instanceSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceSymbol)) { + typeExprSymbol = this.getNewErrorTypeSymbol(diagnostic); + } else { + typeExprSymbol = instanceSymbol.getType(); + } + } + } else if (declSymbol.getIsVarArg() && !(typeExprSymbol.isArray() || typeExprSymbol == this.cachedArrayInterfaceType())) { + var diagnostic = context.postError(this.unitPath, varDecl.minChar, varDecl.getLength(), 228 /* Rest_parameters_must_be_array_types */, null, enclosingDecl); + typeExprSymbol = this.getNewErrorTypeSymbol(diagnostic); + } + + context.setTypeInContext(declSymbol, typeExprSymbol); + + if (declParameterSymbol) { + declParameterSymbol.setType(typeExprSymbol); + } + + if ((varDecl.nodeType === 19 /* Parameter */) && enclosingDecl && ((typeExprSymbol.isGeneric() && !typeExprSymbol.isArray()) || this.isTypeArgumentOrWrapper(typeExprSymbol))) { + var signature = enclosingDecl.getSpecializingSignatureSymbol(); + + if (signature) { + signature.setHasGenericParameter(); + } + } + } + } else if (varDecl.init) { + var initExprSymbolAndDiagnostics = this.resolveAST(varDecl.init, false, wrapperDecl, context); + var initExprSymbol = initExprSymbolAndDiagnostics && initExprSymbolAndDiagnostics.symbol; + + if (!initExprSymbol) { + diagnostic = context.postError(this.unitPath, varDecl.minChar, varDecl.getLength(), 147 /* Unable_to_resolve_type_of__0_ */, [varDecl.id.actualText], decl); + + context.setTypeInContext(declSymbol, this.getNewErrorTypeSymbol(diagnostic)); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + context.setTypeInContext(declSymbol, this.widenType(initExprSymbol.getType())); + initExprSymbol.addOutgoingLink(declSymbol, 2 /* ProvidesInferredType */); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, initExprSymbol.getType()); + initExprSymbol.addOutgoingLink(declParameterSymbol, 2 /* ProvidesInferredType */); + } + } + } else if (declSymbol.getKind() === 4 /* Container */) { + instanceSymbol = (declSymbol).getInstanceSymbol(); + var instanceType = instanceSymbol.getType(); + + if (instanceType) { + context.setTypeInContext(declSymbol, instanceType); + } else { + context.setTypeInContext(declSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + var defaultType = this.semanticInfoChain.anyTypeSymbol; + + if (declSymbol.getIsVarArg()) { + defaultType = TypeScript.specializeToArrayType(this.cachedArrayInterfaceType(), defaultType, this, context); + } + + context.setTypeInContext(declSymbol, defaultType); + + if (declParameterSymbol) { + declParameterSymbol.setType(defaultType); + } + } + + declSymbol.setResolved(); + + if (declParameterSymbol) { + declParameterSymbol.setResolved(); + } + + return declSymbol; + }; + + PullTypeResolver.prototype.resolveTypeParameterDeclaration = function (typeParameterAST, context) { + var typeParameterDecl = this.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + if (typeParameterSymbol.isResolved() || typeParameterSymbol.isResolving()) { + return typeParameterSymbol; + } + + typeParameterSymbol.startResolving(); + + if (typeParameterAST.constraint) { + var enclosingDecl = this.getEnclosingDecl(typeParameterDecl); + var constraintTypeSymbol = this.resolveTypeReference(typeParameterAST.constraint, enclosingDecl, context).symbol; + + if (constraintTypeSymbol.isNamedTypeSymbol() && constraintTypeSymbol.isGeneric() && !constraintTypeSymbol.isTypeParameter() && constraintTypeSymbol.getTypeParameters().length && (constraintTypeSymbol.getTypeArguments() == null && !this.isArrayOrEquivalent(constraintTypeSymbol)) && constraintTypeSymbol.isResolved() && this.isTypeRefWithoutTypeArgs(typeParameterAST.constraint)) { + context.postError(this.unitPath, typeParameterAST.constraint.minChar, typeParameterAST.constraint.getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + constraintTypeSymbol = this.specializeTypeToAny(constraintTypeSymbol, enclosingDecl, context); + } + + if (constraintTypeSymbol) { + typeParameterSymbol.setConstraint(constraintTypeSymbol); + } + } + + typeParameterSymbol.setResolved(); + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionBodyReturnTypes = function (funcDeclAST, signature, useContextualType, enclosingDecl, context) { + var _this = this; + var returnStatements = []; + + var enclosingDeclStack = [enclosingDecl]; + + var preFindReturnExpressionTypes = function (ast, parent, walker) { + var go = true; + + switch (ast.nodeType) { + case 12 /* FunctionDeclaration */: + go = false; + break; + + case 93 /* ReturnStatement */: + var returnStatement = ast; + returnStatements[returnStatements.length] = { returnStatement: returnStatement, enclosingDecl: enclosingDeclStack[enclosingDeclStack.length - 1] }; + go = false; + break; + + case 101 /* CatchClause */: + case 99 /* WithStatement */: + enclosingDeclStack[enclosingDeclStack.length] = _this.getDeclForAST(ast); + break; + + default: + break; + } + + walker.options.goChildren = go; + + return ast; + }; + + var postFindReturnExpressionEnclosingDecls = function (ast, parent, walker) { + switch (ast.nodeType) { + case 101 /* CatchClause */: + case 99 /* WithStatement */: + enclosingDeclStack.length--; + break; + default: + break; + } + + walker.options.goChildren = true; + + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(funcDeclAST.block, preFindReturnExpressionTypes, postFindReturnExpressionEnclosingDecls); + + if (!returnStatements.length) { + signature.setReturnType(this.semanticInfoChain.voidTypeSymbol); + } else { + var returnExpressionSymbols = []; + var returnType; + + for (var i = 0; i < returnStatements.length; i++) { + if (returnStatements[i].returnStatement.returnExpression) { + returnType = this.resolveAST(returnStatements[i].returnStatement.returnExpression, useContextualType, returnStatements[i].enclosingDecl, context).symbol.getType(); + + if (returnType.isError()) { + signature.setReturnType(returnType); + return; + } + + returnExpressionSymbols[returnExpressionSymbols.length] = returnType; + } + } + + if (!returnExpressionSymbols.length) { + signature.setReturnType(this.semanticInfoChain.voidTypeSymbol); + } else { + var collection = { + getLength: function () { + return returnExpressionSymbols.length; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return returnExpressionSymbols[index].getType(); + } + }; + + returnType = this.findBestCommonType(returnExpressionSymbols[0], null, collection, context, new TypeScript.TypeComparisonInfo()); + + if (useContextualType && returnType == this.semanticInfoChain.anyTypeSymbol) { + var contextualType = context.getContextualType(); + + if (contextualType) { + returnType = contextualType; + } + } + + signature.setReturnType(returnType ? this.widenType(returnType) : this.semanticInfoChain.anyTypeSymbol); + + if (this.isTypeArgumentOrWrapper(returnType)) { + var functionDecl = this.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + + if (functionSymbol) { + functionSymbol.getType().setHasGenericSignature(); + } + } + + for (var i = 0; i < returnExpressionSymbols.length; i++) { + returnExpressionSymbols[i].addOutgoingLink(signature, 2 /* ProvidesInferredType */); + } + } + } + }; + + PullTypeResolver.prototype.resolveFunctionDeclaration = function (funcDeclAST, context) { + var funcDecl = this.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSpecializingSignatureSymbol(); + + var hadError = false; + + var isConstructor = funcDeclAST.isConstructor || TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 1024 /* ConstructMember */); + + if (signature) { + if (signature.isResolved()) { + return funcSymbol; + } + + if (isConstructor && !signature.isResolving()) { + var classAST = funcDeclAST.classDecl; + + if (classAST) { + var classDecl = this.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved() && !classSymbol.isResolving()) { + this.resolveDeclaredSymbol(classSymbol, this.getEnclosingDecl(classDecl), context); + } + } + } + + var diagnostic; + + if (signature.isResolving()) { + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, funcDecl, context).symbol; + if (!returnTypeSymbol) { + diagnostic = context.postError(this.unitPath, funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), 197 /* Cannot_resolve_return_type_reference */, null, funcDecl); + signature.setReturnType(this.getNewErrorTypeSymbol(diagnostic)); + hadError = true; + } else { + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + if (funcSymbol) { + funcSymbol.getType().setHasGenericSignature(); + } + } + signature.setReturnType(returnTypeSymbol); + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 198 /* Constructors_cannot_have_a_return_type_of__void_ */, null, funcDecl, true); + } + } + } else { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } + + signature.setResolved(); + return funcSymbol; + } + + signature.startResolving(); + + if (funcDeclAST.typeArguments) { + for (var i = 0; i < funcDeclAST.typeArguments.members.length; i++) { + this.resolveTypeParameterDeclaration(funcDeclAST.typeArguments.members[i], context); + } + } + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveVariableDeclaration(funcDeclAST.arguments.members[i], context, funcDecl); + } + } + + if (signature.isGeneric()) { + if (funcSymbol) { + funcSymbol.getType().setHasGenericSignature(); + } + } + + if (funcDeclAST.returnTypeAnnotation) { + var prevReturnTypeSymbol = signature.getReturnType(); + + returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, funcDecl, context).symbol; + + if (!returnTypeSymbol) { + diagnostic = context.postError(this.unitPath, funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), 197 /* Cannot_resolve_return_type_reference */, null, funcDecl); + signature.setReturnType(this.getNewErrorTypeSymbol(diagnostic)); + + hadError = true; + } else if (!(this.isTypeArgumentOrWrapper(returnTypeSymbol) && prevReturnTypeSymbol && !this.isTypeArgumentOrWrapper(prevReturnTypeSymbol))) { + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + + if (funcSymbol) { + funcSymbol.getType().setHasGenericSignature(); + } + } + + signature.setReturnType(returnTypeSymbol); + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 198 /* Constructors_cannot_have_a_return_type_of__void_ */, null, funcDecl, true); + } + } + } else if (!funcDeclAST.isConstructor) { + if (funcDeclAST.isSignature()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, false, funcDecl, context); + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveGetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var getterSymbol = accessorSymbol.getGetter(); + var getterTypeSymbol = getterSymbol.getType(); + + var signature = getterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + var diagnostic; + + if (signature) { + if (signature.isResolved()) { + return accessorSymbol; + } + + if (signature.isResolving()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + signature.setResolved(); + + return accessorSymbol; + } + + signature.startResolving(); + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveVariableDeclaration(funcDeclAST.arguments.members[i], context, funcDecl); + } + } + + if (signature.hasGenericParameter()) { + if (getterSymbol) { + getterTypeSymbol.setHasGenericSignature(); + } + } + + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, funcDecl, context).symbol; + + if (!returnTypeSymbol) { + diagnostic = context.postError(this.unitPath, funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), 197 /* Cannot_resolve_return_type_reference */, null, funcDecl); + signature.setReturnType(this.getNewErrorTypeSymbol(diagnostic)); + + hadError = true; + } else { + if (this.isTypeArgumentOrWrapper(returnTypeSymbol)) { + signature.setHasGenericParameter(); + + if (getterSymbol) { + getterTypeSymbol.setHasGenericSignature(); + } + } + + signature.setReturnType(returnTypeSymbol); + } + } else { + if (funcDeclAST.isSignature()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, false, funcDecl, context); + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + var accessorType = signature.getReturnType(); + + var setter = accessorSymbol.getSetter(); + + if (setter) { + var setterType = setter.getType(); + var setterSig = setterType.getCallSignatures()[0]; + + if (setterSig.isResolved()) { + var setterParameters = setterSig.getParameters(); + + if (setterParameters.length) { + var setterParameter = setterParameters[0]; + var setterParameterType = setterParameter.getType(); + + if (!this.typesAreIdentical(accessorType, setterParameterType)) { + diagnostic = context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 165 /* _get__and__set__accessor_must_have_the_same_type */, null, this.getEnclosingDecl(funcDecl)); + accessorSymbol.setType(this.getNewErrorTypeSymbol(diagnostic)); + } + } + } else { + accessorSymbol.setType(accessorType); + } + } else { + accessorSymbol.setType(accessorType); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var setterSymbol = accessorSymbol.getSetter(); + var setterTypeSymbol = setterSymbol.getType(); + + var signature = setterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + + if (signature) { + if (signature.isResolved()) { + return accessorSymbol; + } + + if (signature.isResolving()) { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + signature.setResolved(); + + return accessorSymbol; + } + + signature.startResolving(); + + if (funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + this.resolveVariableDeclaration(funcDeclAST.arguments.members[i], context, funcDecl); + } + } + + if (signature.hasGenericParameter()) { + if (setterSymbol) { + setterTypeSymbol.setHasGenericSignature(); + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + var parameters = signature.getParameters(); + + var getter = accessorSymbol.getGetter(); + + var accessorType = parameters.length ? parameters[0].getType() : getter ? getter.getType() : this.semanticInfoChain.undefinedTypeSymbol; + + if (getter) { + var getterType = getter.getType(); + var getterSig = getterType.getCallSignatures()[0]; + + if (accessorType == this.semanticInfoChain.undefinedTypeSymbol) { + accessorType = getterType; + } + + if (getterSig.isResolved()) { + var getterReturnType = getterSig.getReturnType(); + + if (!this.typesAreIdentical(accessorType, getterReturnType)) { + if (this.isAnyOrEquivalent(accessorType)) { + accessorSymbol.setType(getterReturnType); + if (!accessorType.isError()) { + parameters[0].setType(getterReturnType); + } + } else { + var diagnostic = context.postError(this.unitPath, funcDeclAST.minChar, funcDeclAST.getLength(), 165 /* _get__and__set__accessor_must_have_the_same_type */, null, this.getEnclosingDecl(funcDecl)); + accessorSymbol.setType(this.getNewErrorTypeSymbol(diagnostic)); + } + } + } else { + accessorSymbol.setType(accessorType); + } + } else { + accessorSymbol.setType(accessorType); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.resolveAST = function (ast, inContextuallyTypedAssignment, enclosingDecl, context) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + switch (ast.nodeType) { + case 101 /* CatchClause */: + case 99 /* WithStatement */: + case 2 /* Script */: + return SymbolAndDiagnostics.fromSymbol(null); + + case 15 /* ModuleDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveModuleDeclaration(ast, context)); + + case 14 /* InterfaceDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveInterfaceDeclaration(ast, context)); + + case 13 /* ClassDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveClassDeclaration(ast, context)); + + case 17 /* VariableDeclarator */: + case 19 /* Parameter */: + return SymbolAndDiagnostics.fromSymbol(this.resolveVariableDeclaration(ast, context, enclosingDecl)); + + case 9 /* TypeParameter */: + return SymbolAndDiagnostics.fromSymbol(this.resolveTypeParameterDeclaration(ast, context)); + + case 16 /* ImportDeclaration */: + return SymbolAndDiagnostics.fromSymbol(this.resolveImportDeclaration(ast, context)); + + case 22 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 10 /* GenericType */: + return this.resolveGenericTypeReference(ast, enclosingDecl, context); + + case 20 /* Name */: + if (context.resolvingTypeReference) { + return this.resolveTypeNameExpression(ast, enclosingDecl, context); + } else { + return this.resolveNameExpression(ast, enclosingDecl, context); + } + + case 32 /* MemberAccessExpression */: + if (context.resolvingTypeReference) { + return this.resolveDottedTypeNameExpression(ast, enclosingDecl, context); + } else { + return this.resolveDottedNameExpression(ast, enclosingDecl, context); + } + + case 10 /* GenericType */: + return this.resolveGenericTypeReference(ast, enclosingDecl, context); + + case 12 /* FunctionDeclaration */: { + var funcDecl = ast; + + if (funcDecl.isGetAccessor()) { + return SymbolAndDiagnostics.fromSymbol(this.resolveGetAccessorDeclaration(funcDecl, context)); + } else if (funcDecl.isSetAccessor()) { + return SymbolAndDiagnostics.fromSymbol(this.resolveSetAccessorDeclaration(funcDecl, context)); + } else if (inContextuallyTypedAssignment || (funcDecl.getFunctionFlags() & 8192 /* IsFunctionExpression */) || (funcDecl.getFunctionFlags() & 2048 /* IsFatArrowFunction */) || (funcDecl.getFunctionFlags() & 16384 /* IsFunctionProperty */)) { + return SymbolAndDiagnostics.fromSymbol(this.resolveFunctionExpression(funcDecl, inContextuallyTypedAssignment, enclosingDecl, context)); + } else { + return SymbolAndDiagnostics.fromSymbol(this.resolveFunctionDeclaration(funcDecl, context)); + } + } + + case 21 /* ArrayLiteralExpression */: + return this.resolveArrayLiteralExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 29 /* ThisExpression */: + return this.resolveThisExpression(ast, enclosingDecl, context); + + case 30 /* SuperExpression */: + return this.resolveSuperExpression(ast, enclosingDecl, context); + + case 36 /* InvocationExpression */: + return this.resolveCallExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 37 /* ObjectCreationExpression */: + return this.resolveNewExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 78 /* CastExpression */: + return this.resolveTypeAssertionExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 11 /* TypeRef */: + return this.resolveTypeReference(ast, enclosingDecl, context); + + case 87 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, enclosingDecl, context); + + case 7 /* NumericLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + case 5 /* StringLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + case 8 /* NullLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.nullTypeSymbol); + case 3 /* TrueLiteral */: + case 4 /* FalseLiteral */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + case 24 /* VoidExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + + case 38 /* AssignmentExpression */: + return this.resolveAssignmentStatement(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 73 /* LogicalNotExpression */: + case 57 /* NotEqualsWithTypeConversionExpression */: + case 56 /* EqualsWithTypeConversionExpression */: + case 58 /* EqualsExpression */: + case 59 /* NotEqualsExpression */: + case 60 /* LessThanExpression */: + case 61 /* LessThanOrEqualExpression */: + case 63 /* GreaterThanOrEqualExpression */: + case 62 /* GreaterThanExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + + case 64 /* AddExpression */: + case 39 /* AddAssignmentExpression */: + return this.resolveArithmeticExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 40 /* SubtractAssignmentExpression */: + case 42 /* MultiplyAssignmentExpression */: + case 41 /* DivideAssignmentExpression */: + case 43 /* ModuloAssignmentExpression */: + case 46 /* OrAssignmentExpression */: + case 44 /* AndAssignmentExpression */: + + case 72 /* BitwiseNotExpression */: + case 65 /* SubtractExpression */: + case 66 /* MultiplyExpression */: + case 67 /* DivideExpression */: + case 68 /* ModuloExpression */: + case 53 /* BitwiseOrExpression */: + case 55 /* BitwiseAndExpression */: + case 26 /* PlusExpression */: + case 27 /* NegateExpression */: + case 76 /* PostIncrementExpression */: + case 74 /* PreIncrementExpression */: + case 77 /* PostDecrementExpression */: + case 75 /* PreDecrementExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + + case 69 /* LeftShiftExpression */: + case 70 /* SignedRightShiftExpression */: + case 71 /* UnsignedRightShiftExpression */: + case 47 /* LeftShiftAssignmentExpression */: + case 48 /* SignedRightShiftAssignmentExpression */: + case 49 /* UnsignedRightShiftAssignmentExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + + case 35 /* ElementAccessExpression */: + return this.resolveIndexExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 51 /* LogicalOrExpression */: + return this.resolveLogicalOrExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 52 /* LogicalAndExpression */: + return this.resolveLogicalAndExpression(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 34 /* TypeOfExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + + case 95 /* ThrowStatement */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + + case 28 /* DeleteExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + + case 50 /* ConditionalExpression */: + return this.resolveConditionalExpression(ast, enclosingDecl, context); + + case 6 /* RegularExpressionLiteral */: + return this.resolveRegularExpressionLiteral(); + + case 79 /* ParenthesizedExpression */: + return this.resolveParenthesizedExpression(ast, enclosingDecl, context); + + case 88 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, inContextuallyTypedAssignment, enclosingDecl, context); + + case 33 /* InstanceOfExpression */: + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveRegularExpressionLiteral = function () { + if (this.cachedRegExpInterfaceType()) { + return SymbolAndDiagnostics.fromSymbol(this.cachedRegExpInterfaceType()); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + }; + + PullTypeResolver.prototype.isNameOrMemberAccessExpression = function (ast) { + var checkAST = ast; + + while (checkAST) { + if (checkAST.nodeType === 88 /* ExpressionStatement */) { + checkAST = (checkAST).expression; + } else if (checkAST.nodeType === 79 /* ParenthesizedExpression */) { + checkAST = (checkAST).expression; + } else if (checkAST.nodeType === 20 /* Name */) { + return true; + } else if (checkAST.nodeType === 32 /* MemberAccessExpression */) { + return true; + } else { + return false; + } + } + }; + + PullTypeResolver.prototype.resolveNameSymbol = function (nameSymbol, context) { + if (nameSymbol && !context.canUseTypeSymbol && nameSymbol != this.semanticInfoChain.undefinedTypeSymbol && nameSymbol != this.semanticInfoChain.nullTypeSymbol && (nameSymbol.isPrimitive() || !(nameSymbol.getKind() & TypeScript.PullElementKind.SomeValue))) { + nameSymbol = null; + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.resolveNameExpression = function (nameAST, enclosingDecl, context) { + var nameSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(nameAST); + var foundCached = nameSymbolAndDiagnostics != null; + + if (!foundCached) { + nameSymbolAndDiagnostics = this.computeNameExpression(nameAST, enclosingDecl, context); + } + + var nameSymbol = nameSymbolAndDiagnostics.symbol; + if (!nameSymbol.isResolved()) { + this.resolveDeclaredSymbol(nameSymbol, enclosingDecl, context); + } + + if (!foundCached && !this.isAnyOrEquivalent(nameSymbol.getType())) { + this.setSymbolAndDiagnosticsForAST(nameAST, nameSymbolAndDiagnostics, context); + } + + return nameSymbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, enclosingDecl, context) { + if (nameAST.isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var id = nameAST.text; + + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + + if (enclosingDecl && !declPath.length) { + declPath = [enclosingDecl]; + } + + var aliasSymbol = null; + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, TypeScript.PullElementKind.SomeValue); + + if (!nameSymbol && id === "arguments" && enclosingDecl && (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction)) { + nameSymbol = this.cachedFunctionArgumentsSymbol; + + if (this.cachedIArgumentsInterfaceType() && !this.cachedIArgumentsInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), enclosingDecl, context); + } + } + + if (!nameSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, id), [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 164 /* Could_not_find_symbol__0_ */, [nameAST.actualText])]); + } + + if (nameSymbol.isType() && nameSymbol.isAlias()) { + aliasSymbol = nameSymbol; + + (aliasSymbol).setIsUsedAsValue(); + + if (!nameSymbol.isResolved()) { + this.resolveDeclaredSymbol(nameSymbol, enclosingDecl, context); + } + + var exportAssignmentSymbol = (nameSymbol).getExportAssignedValueSymbol(); + + if (exportAssignmentSymbol) { + nameSymbol = exportAssignmentSymbol; + } else { + aliasSymbol = null; + } + } + + return SymbolAndDiagnostics.fromAlias(nameSymbol, aliasSymbol); + }; + + PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(dottedNameAST); + var foundCached = symbolAndDiagnostics != null; + + if (!foundCached) { + symbolAndDiagnostics = this.computeDottedNameExpressionSymbol(dottedNameAST, enclosingDecl, context); + } + + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + if (symbol && !symbol.isResolved()) { + this.resolveDeclaredSymbol(symbol, enclosingDecl, context); + } + + if (!foundCached && !this.isAnyOrEquivalent(symbol.getType())) { + this.setSymbolAndDiagnosticsForAST(dottedNameAST, symbolAndDiagnostics, context); + this.setSymbolAndDiagnosticsForAST(dottedNameAST.operand2, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.isPrototypeMember = function (dottedNameAST, enclosingDecl, context) { + var rhsName = (dottedNameAST.operand2).text; + if (rhsName === "prototype") { + var prevCanUseTypeSymbol = context.canUseTypeSymbol; + context.canUseTypeSymbol = true; + var lhsType = this.resolveAST(dottedNameAST.operand1, false, enclosingDecl, context).symbol.getType(); + context.canUseTypeSymbol = prevCanUseTypeSymbol; + + if (lhsType) { + if (lhsType.isClass() || lhsType.isConstructor()) { + return true; + } else { + var classInstanceType = lhsType.getAssociatedContainerType(); + + if (classInstanceType && classInstanceType.isClass()) { + return true; + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.computeDottedNameExpressionSymbol = function (dottedNameAST, enclosingDecl, context) { + if ((dottedNameAST.operand2).isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var rhsName = (dottedNameAST.operand2).text; + var prevCanUseTypeSymbol = context.canUseTypeSymbol; + context.canUseTypeSymbol = true; + var lhs = this.resolveAST(dottedNameAST.operand1, false, enclosingDecl, context).symbol; + context.canUseTypeSymbol = prevCanUseTypeSymbol; + var lhsType = lhs.getType(); + + if (lhs.isAlias()) { + (lhs).setIsUsedAsValue(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return SymbolAndDiagnostics.fromSymbol(lhsType); + } + + if (!lhsType) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 162 /* Could_not_find_enclosing_symbol_for_dotted_name__0_ */, [(dottedNameAST.operand2).actualText])]); + } + + if ((lhsType === this.semanticInfoChain.numberTypeSymbol || (lhs.getKind() == 67108864 /* EnumMember */)) && this.cachedNumberInterfaceType()) { + lhsType = this.cachedNumberInterfaceType(); + } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { + lhsType = this.cachedStringInterfaceType(); + } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { + lhsType = this.cachedBooleanInterfaceType(); + } + + if (!lhsType.isResolved()) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, enclosingDecl, context); + + if (potentiallySpecializedType != lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + if (lhsType.isContainer() && !lhsType.isAlias()) { + var instanceSymbol = (lhsType).getInstanceSymbol(); + + if (instanceSymbol) { + lhsType = instanceSymbol.getType(); + } + } + + if (this.isPrototypeMember(dottedNameAST, enclosingDecl, context)) { + if (lhsType.isClass()) { + return SymbolAndDiagnostics.fromSymbol(lhsType); + } else { + var classInstanceType = lhsType.getAssociatedContainerType(); + + if (classInstanceType && classInstanceType.isClass()) { + return SymbolAndDiagnostics.fromSymbol(classInstanceType); + } + } + } + + if (lhsType.isTypeParameter()) { + lhsType = this.substituteUpperBoundForType(lhsType); + } + + var nameSymbol = null; + if (!(lhs.isType() && (lhs).isClass() && this.isNameOrMemberAccessExpression(dottedNameAST.operand1)) && !nameSymbol) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, lhsType); + nameSymbol = this.resolveNameSymbol(nameSymbol, context); + } + + if (!nameSymbol) { + if (lhsType.isClass()) { + var staticType = (lhsType).getConstructorMethod().getType(); + + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, staticType); + + if (!nameSymbol) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, lhsType); + } + } else if ((lhsType.getCallSignatures().length || lhsType.getConstructSignatures().length) && this.cachedFunctionInterfaceType()) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, this.cachedFunctionInterfaceType()); + } else if (lhsType.isContainer()) { + var containerType = (lhsType.isAlias() ? (lhsType).getType() : lhsType); + var associatedInstance = containerType.getInstanceSymbol(); + + if (associatedInstance) { + var instanceType = associatedInstance.getType(); + + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, instanceType); + } + } else { + var associatedType = lhsType.getAssociatedContainerType(); + + if (associatedType && !associatedType.isClass()) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, associatedType); + } + } + + nameSymbol = this.resolveNameSymbol(nameSymbol, context); + + if (!nameSymbol && !lhsType.isPrimitive() && this.cachedObjectInterfaceType()) { + nameSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeValue, this.cachedObjectInterfaceType()); + } + + if (!nameSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, rhsName), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 163 /* The_property__0__does_not_exist_on_value_of_type__1__ */, [(dottedNameAST.operand2).actualText, lhsType.getDisplayName()])]); + } + } + + return SymbolAndDiagnostics.fromSymbol(nameSymbol); + }; + + PullTypeResolver.prototype.resolveTypeNameExpression = function (nameAST, enclosingDecl, context) { + var typeNameSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(nameAST); + + if (!typeNameSymbolAndDiagnostics || !typeNameSymbolAndDiagnostics.symbol.isType()) { + typeNameSymbolAndDiagnostics = this.computeTypeNameExpression(nameAST, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(nameAST, typeNameSymbolAndDiagnostics, context); + } + + var typeNameSymbol = typeNameSymbolAndDiagnostics && typeNameSymbolAndDiagnostics.symbol; + if (!typeNameSymbol.isResolved()) { + var savedResolvingNamespaceMemberAccess = context.resolvingNamespaceMemberAccess; + context.resolvingNamespaceMemberAccess = false; + this.resolveDeclaredSymbol(typeNameSymbol, enclosingDecl, context); + context.resolvingNamespaceMemberAccess = savedResolvingNamespaceMemberAccess; + } + + if (typeNameSymbol && !(typeNameSymbol.isTypeParameter() && (typeNameSymbol).isFunctionTypeParameter() && context.isSpecializingSignatureAtCallSite && !context.isSpecializingConstructorMethod)) { + var substitution = context.findSpecializationForType(typeNameSymbol); + + if (typeNameSymbol.isTypeParameter() && (substitution != typeNameSymbol)) { + if (TypeScript.shouldSpecializeTypeParameterForTypeParameter(substitution, typeNameSymbol)) { + typeNameSymbol = substitution; + } + } + + if (typeNameSymbol != typeNameSymbolAndDiagnostics.symbol) { + return SymbolAndDiagnostics.fromSymbol(typeNameSymbol); + } + } + + return typeNameSymbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeTypeNameExpression = function (nameAST, enclosingDecl, context) { + if (nameAST.isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var id = nameAST.text; + + if (id === "any") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } else if (id === "string") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + } else if (id === "number") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (id === "bool") { + if (this.compilationSettings.disallowBool && !this.currentUnit.getProperties().unitContainsBool) { + this.currentUnit.getProperties().unitContainsBool = true; + return SymbolAndDiagnostics.create(this.semanticInfoChain.booleanTypeSymbol, [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 167 /* Use_of_deprecated__bool__type__Use__boolean__instead */)]); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } + } else if (id === "boolean") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } else if (id === "void") { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.voidTypeSymbol); + } else { + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + + if (enclosingDecl && !declPath.length) { + declPath = [enclosingDecl]; + } + + var kindToCheckFirst = context.resolvingNamespaceMemberAccess ? TypeScript.PullElementKind.SomeContainer : TypeScript.PullElementKind.SomeType; + var kindToCheckSecond = context.resolvingNamespaceMemberAccess ? TypeScript.PullElementKind.SomeType : TypeScript.PullElementKind.SomeContainer; + + var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); + + if (!typeNameSymbol) { + typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckSecond); + } + + if (!typeNameSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, id), [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 164 /* Could_not_find_symbol__0_ */, [nameAST.actualText])]); + } + + if (typeNameSymbol.isAlias()) { + if (!typeNameSymbol.isResolved()) { + var savedResolvingNamespaceMemberAccess = context.resolvingNamespaceMemberAccess; + context.resolvingNamespaceMemberAccess = false; + this.resolveDeclaredSymbol(typeNameSymbol, enclosingDecl, context); + context.resolvingNamespaceMemberAccess = savedResolvingNamespaceMemberAccess; + } + + var aliasedType = (typeNameSymbol).getType(); + + if (aliasedType && !aliasedType.isResolved()) { + this.resolveDeclaredSymbol(aliasedType, enclosingDecl, context); + } + + var exportAssignmentSymbol = (typeNameSymbol).getExportAssignedTypeSymbol(); + + if (exportAssignmentSymbol) { + typeNameSymbol = exportAssignmentSymbol; + } + } + + if (typeNameSymbol.isTypeParameter()) { + if (enclosingDecl && (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction) && (enclosingDecl.getFlags() & 16 /* Static */)) { + var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); + + if (parentDecl.getKind() == 8 /* Class */) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, nameAST.minChar, nameAST.getLength(), 226 /* Static_methods_cannot_reference_class_type_parameters */)]); + } + } + } + } + + return SymbolAndDiagnostics.fromSymbol(typeNameSymbol); + }; + + PullTypeResolver.prototype.addDiagnostic = function (diagnostics, diagnostic) { + if (!diagnostics) { + diagnostics = []; + } + + diagnostics.push(diagnostic); + return diagnostics; + }; + + PullTypeResolver.prototype.resolveGenericTypeReference = function (genericTypeAST, enclosingDecl, context) { + var savedResolvingTypeReference = context.resolvingTypeReference; + context.resolvingTypeReference = true; + var genericTypeSymbol = this.resolveAST(genericTypeAST.name, false, enclosingDecl, context).symbol.getType(); + context.resolvingTypeReference = savedResolvingTypeReference; + + if (genericTypeSymbol.isError()) { + return SymbolAndDiagnostics.fromSymbol(genericTypeSymbol); + } + + if (!genericTypeSymbol.isResolving() && !genericTypeSymbol.isResolved()) { + this.resolveDeclaredSymbol(genericTypeSymbol, enclosingDecl, context); + } + + var typeArgs = []; + + if (!context.isResolvingTypeArguments(genericTypeAST)) { + context.startResolvingTypeArguments(genericTypeAST); + + if (genericTypeAST.typeArguments && genericTypeAST.typeArguments.members.length) { + for (var i = 0; i < genericTypeAST.typeArguments.members.length; i++) { + var typeArg = this.resolveTypeReference(genericTypeAST.typeArguments.members[i], enclosingDecl, context).symbol; + + if (typeArg.isNamedTypeSymbol() && typeArg.isGeneric() && !typeArg.isTypeParameter() && typeArg.isResolved() && !typeArg.getIsSpecialized() && typeArg.getTypeParameters().length && (typeArg.getTypeArguments() == null && !this.isArrayOrEquivalent(typeArg)) && this.isTypeRefWithoutTypeArgs(genericTypeAST.typeArguments.members[i])) { + context.postError(this.unitPath, genericTypeAST.typeArguments.members[i].minChar, genericTypeAST.typeArguments.members[i].getLength(), 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl, true); + typeArg = this.specializeTypeToAny(typeArg, enclosingDecl, context); + } + + typeArgs[i] = context.findSpecializationForType(typeArg); + } + } + + context.doneResolvingTypeArguments(); + } + + var typeParameters = genericTypeSymbol.getTypeParameters(); + + if (typeArgs.length && typeArgs.length != typeParameters.length) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, genericTypeAST.minChar, genericTypeAST.getLength(), 159 /* Generic_type__0__requires_1_type_argument_s_ */, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])]); + } + + var specializedSymbol = TypeScript.specializeType(genericTypeSymbol, typeArgs, this, enclosingDecl, context, genericTypeAST); + + var typeConstraint = null; + var upperBound = null; + var diagnostics = null; + + for (var iArg = 0; (iArg < typeArgs.length) && (iArg < typeParameters.length); iArg++) { + typeArg = typeArgs[iArg]; + typeConstraint = typeParameters[iArg].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { + if (typeParameters[j] == typeConstraint) { + typeConstraint = typeArgs[j]; + } + } + } + + if (typeArg.isTypeParameter()) { + upperBound = (typeArg).getConstraint(); + + if (upperBound) { + typeArg = upperBound; + } + } + + if (typeArg.isResolving()) { + return SymbolAndDiagnostics.fromSymbol(specializedSymbol); + } + if (!this.sourceIsAssignableToTarget(typeArg, typeConstraint, context)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, genericTypeAST.minChar, genericTypeAST.getLength(), 155 /* Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_ */, [typeArg.toString(true), typeConstraint.toString(true), typeParameters[iArg].toString(true)])); + } + } + } + + return SymbolAndDiagnostics.create(specializedSymbol, diagnostics); + }; + + PullTypeResolver.prototype.resolveDottedTypeNameExpression = function (dottedNameAST, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(dottedNameAST); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeDottedTypeNameExpression(dottedNameAST, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(dottedNameAST, symbolAndDiagnostics, context); + } + + var symbol = symbolAndDiagnostics.symbol; + if (!symbol.isResolved()) { + this.resolveDeclaredSymbol(symbol, enclosingDecl, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeDottedTypeNameExpression = function (dottedNameAST, enclosingDecl, context) { + if ((dottedNameAST.operand2).isMissing()) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var rhsName = (dottedNameAST.operand2).text; + + var savedResolvingTypeReference = context.resolvingTypeReference; + var savedResolvingNamespaceMemberAccess = context.resolvingNamespaceMemberAccess; + context.resolvingNamespaceMemberAccess = true; + context.resolvingTypeReference = true; + var lhs = this.resolveAST(dottedNameAST.operand1, false, enclosingDecl, context).symbol; + context.resolvingTypeReference = savedResolvingTypeReference; + context.resolvingNamespaceMemberAccess = savedResolvingNamespaceMemberAccess; + + var lhsType = lhs.getType(); + + if (context.isResolvingClassExtendedType) { + if (lhs.isAlias()) { + (lhs).setIsUsedAsValue(); + } + } + + if (this.isAnyOrEquivalent(lhsType)) { + return SymbolAndDiagnostics.fromSymbol(lhsType); + } + + if (!lhsType) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 162 /* Could_not_find_enclosing_symbol_for_dotted_name__0_ */, [(dottedNameAST.operand2).actualText])]); + } + + var childTypeSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeType, lhsType); + + if (!childTypeSymbol && lhsType.isContainer()) { + var exportedContainer = (lhsType).getExportAssignedContainerSymbol(); + + if (exportedContainer) { + childTypeSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeType, exportedContainer); + } + } + + if (!childTypeSymbol && enclosingDecl) { + var parentDecl = enclosingDecl; + + while (parentDecl) { + if (parentDecl.getKind() & TypeScript.PullElementKind.SomeContainer) { + break; + } + + parentDecl = parentDecl.getParentDecl(); + } + + if (parentDecl) { + var enclosingSymbolType = parentDecl.getSymbol().getType(); + + if (enclosingSymbolType === lhsType) { + childTypeSymbol = this.getMemberSymbol(rhsName, TypeScript.PullElementKind.SomeType, lhsType); + } + } + } + + if (!childTypeSymbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null, rhsName), [context.postError(this.unitPath, dottedNameAST.operand2.minChar, dottedNameAST.operand2.getLength(), 163 /* The_property__0__does_not_exist_on_value_of_type__1__ */, [(dottedNameAST.operand2).actualText, lhsType.getName()])]); + } + + return SymbolAndDiagnostics.fromSymbol(childTypeSymbol); + }; + + PullTypeResolver.prototype.resolveFunctionExpression = function (funcDeclAST, inContextuallyTypedAssignment, enclosingDecl, context) { + var funcDeclSymbol = null; + var functionDecl = this.getDeclForAST(funcDeclAST); + + if (functionDecl && functionDecl.hasSymbol()) { + funcDeclSymbol = functionDecl.getSymbol(); + if (funcDeclSymbol.isResolved()) { + return funcDeclSymbol; + } + } + + var shouldContextuallyType = inContextuallyTypedAssignment; + + var assigningFunctionTypeSymbol = null; + var assigningFunctionSignature = null; + + if (funcDeclAST.returnTypeAnnotation) { + shouldContextuallyType = false; + } + + if (shouldContextuallyType && funcDeclAST.arguments) { + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + if ((funcDeclAST.arguments.members[i]).typeExpr) { + shouldContextuallyType = false; + break; + } + } + } + + if (shouldContextuallyType) { + assigningFunctionTypeSymbol = context.getContextualType(); + + if (assigningFunctionTypeSymbol) { + this.resolveDeclaredSymbol(assigningFunctionTypeSymbol, enclosingDecl, context); + + if (assigningFunctionTypeSymbol) { + assigningFunctionSignature = assigningFunctionTypeSymbol.getCallSignatures()[0]; + } + } + } + + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + if (enclosingDecl) { + declCollectionContext.pushParent(enclosingDecl); + } + + TypeScript.getAstWalkerFactory().walk(funcDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var functionDecl = this.getDeclForAST(funcDeclAST); + this.currentUnit.addSynthesizedDecl(functionDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + binder.setUnit(this.unitPath); + binder.bindFunctionExpressionToPullSymbol(functionDecl); + + funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.getType().getCallSignatures()[0]; + + if (funcDeclAST.arguments) { + var contextParams = []; + var contextParam = null; + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.getParameters(); + } + + for (var i = 0; i < funcDeclAST.arguments.members.length; i++) { + if ((i < contextParams.length) && !contextParams[i].getIsVarArg()) { + contextParam = contextParams[i]; + } else if (contextParams.length && contextParams[contextParams.length - 1].getIsVarArg()) { + contextParam = (contextParams[contextParams.length - 1].getType()).getElementType(); + } + + this.resolveFunctionExpressionParameter(funcDeclAST.arguments.members[i], contextParam, functionDecl, context); + } + } + + if (funcDeclAST.returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(funcDeclAST.returnTypeAnnotation, functionDecl, context).symbol; + + signature.setReturnType(returnTypeSymbol); + } else { + if (assigningFunctionSignature) { + var returnType = assigningFunctionSignature.getReturnType(); + + if (returnType) { + context.pushContextualType(returnType, context.inProvisionalResolution(), null); + + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, true, functionDecl, context); + context.popContextualType(); + } else { + signature.setReturnType(this.semanticInfoChain.anyTypeSymbol); + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, signature, false, functionDecl, context); + } + } + + if (assigningFunctionTypeSymbol) { + funcDeclSymbol.addOutgoingLink(assigningFunctionTypeSymbol, 1 /* ContextuallyTypedAs */); + } + + funcDeclSymbol.setResolved(); + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveThisExpression = function (ast, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(ast); + + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeThisExpressionSymbol(ast, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(ast, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeThisExpressionSymbol = function (ast, enclosingDecl, context) { + if (enclosingDecl) { + var enclosingDeclKind = enclosingDecl.getKind(); + var diagnostics; + + if (enclosingDeclKind === 4 /* Container */) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.currentUnit.getPath(), ast.minChar, ast.getLength(), 176 /* _this__cannot_be_referenced_within_module_bodies */)]); + } else if (!(enclosingDeclKind & (TypeScript.PullElementKind.SomeFunction | 1 /* Script */ | TypeScript.PullElementKind.SomeBlock))) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.currentUnit.getPath(), ast.minChar, ast.getLength(), 177 /* _this__must_only_be_used_inside_a_function_or_script_context */)]); + } else { + var declPath = TypeScript.getPathToDecl(enclosingDecl); + + if (declPath.length) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.getKind(); + var declFlags = decl.getFlags(); + + if (declFlags & 16 /* Static */) { + break; + } else if (declKind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(declFlags, 8192 /* FatArrow */)) { + break; + } else if (declKind === 16384 /* Function */) { + break; + } else if (declKind === 8 /* Class */) { + var classSymbol = decl.getSymbol(); + return SymbolAndDiagnostics.fromSymbol(classSymbol); + } + } + } + } + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveSuperExpression = function (ast, enclosingDecl, context) { + if (!enclosingDecl) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var declPath = enclosingDecl !== null ? TypeScript.getPathToDecl(enclosingDecl) : []; + var classSymbol = null; + + if (declPath.length) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declFlags = decl.getFlags(); + + if (decl.getKind() === 131072 /* FunctionExpression */ && !(declFlags & 8192 /* FatArrow */)) { + break; + } else if (declFlags & 16 /* Static */) { + break; + } else if (decl.getKind() === 8 /* Class */) { + classSymbol = decl.getSymbol(); + + break; + } + } + } + + if (classSymbol) { + if (!classSymbol.isResolved()) { + this.resolveDeclaredSymbol(classSymbol, enclosingDecl, context); + } + + var parents = classSymbol.getExtendedTypes(); + + if (parents.length) { + return SymbolAndDiagnostics.fromSymbol(parents[0]); + } + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(expressionAST); + + if (!symbolAndDiagnostics || additionalResults) { + symbolAndDiagnostics = this.computeObjectLiteralExpression(expressionAST, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults); + this.setSymbolAndDiagnosticsForAST(expressionAST, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeObjectLiteralExpression = function (expressionAST, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var objectLitAST = expressionAST; + var span = TypeScript.TextSpan.fromBounds(objectLitAST.minChar, objectLitAST.limChar); + + var objectLitDecl = new TypeScript.PullDecl("", "", 512 /* ObjectLiteral */, 0 /* None */, span, this.unitPath); + this.currentUnit.addSynthesizedDecl(objectLitDecl); + + if (enclosingDecl) { + objectLitDecl.setParentDecl(enclosingDecl); + } + + this.currentUnit.setDeclForAST(objectLitAST, objectLitDecl); + this.currentUnit.setASTForDecl(objectLitDecl, objectLitAST); + + var typeSymbol = new TypeScript.PullTypeSymbol("", 16 /* Interface */); + typeSymbol.addDeclaration(objectLitDecl); + objectLitDecl.setSymbol(typeSymbol); + + var memberDecls = objectLitAST.operand; + + var contextualType = null; + + if (inContextuallyTypedAssignment) { + contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, enclosingDecl, context); + } + + if (memberDecls) { + var binex; + var memberSymbol; + var assigningSymbol = null; + var acceptedContextualType = false; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols = []; + } + + for (var i = 0, len = memberDecls.members.length; i < len; i++) { + binex = memberDecls.members[i]; + + var id = binex.operand1; + var text; + var actualText; + + if (id.nodeType === 20 /* Name */) { + actualText = (id).actualText; + text = (id).text; + } else if (id.nodeType === 5 /* StringLiteral */) { + actualText = (id).actualText; + text = (id).text; + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + span = TypeScript.TextSpan.fromBounds(binex.minChar, binex.limChar); + + var decl = new TypeScript.PullDecl(text, actualText, 4096 /* Property */, 4 /* Public */, span, this.unitPath); + this.currentUnit.addSynthesizedDecl(decl); + + objectLitDecl.addChildDecl(decl); + decl.setParentDecl(objectLitDecl); + + this.semanticInfoChain.getUnit(this.unitPath).setDeclForAST(binex, decl); + this.semanticInfoChain.getUnit(this.unitPath).setASTForDecl(decl, binex); + + memberSymbol = new TypeScript.PullSymbol(text, 4096 /* Property */); + + memberSymbol.addDeclaration(decl); + decl.setSymbol(memberSymbol); + + if (contextualType) { + assigningSymbol = this.getMemberSymbol(text, TypeScript.PullElementKind.SomeValue, contextualType); + + if (assigningSymbol) { + this.resolveDeclaredSymbol(assigningSymbol, enclosingDecl, context); + + context.pushContextualType(assigningSymbol.getType(), context.inProvisionalResolution(), null); + + acceptedContextualType = true; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols[i] = assigningSymbol.getType(); + } + } + } + + if (binex.operand2.nodeType === 12 /* FunctionDeclaration */) { + var funcDeclAST = binex.operand2; + + if (funcDeclAST.isAccessor()) { + var semanticInfo = this.semanticInfoChain.getUnit(this.unitPath); + var declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + + declCollectionContext.scriptName = this.unitPath; + + declCollectionContext.pushParent(objectLitDecl); + + TypeScript.getAstWalkerFactory().walk(funcDeclAST, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var functionDecl = this.getDeclForAST(funcDeclAST); + this.currentUnit.addSynthesizedDecl(functionDecl); + + var binder = new TypeScript.PullSymbolBinder(this.semanticInfoChain); + binder.setUnit(this.unitPath); + + if (funcDeclAST.isGetAccessor()) { + binder.bindGetAccessorDeclarationToPullSymbol(functionDecl); + } else { + binder.bindSetAccessorDeclarationToPullSymbol(functionDecl); + } + } + } + + var memberExprType = this.resolveAST(binex.operand2, assigningSymbol != null, enclosingDecl, context).symbol; + + if (acceptedContextualType) { + context.popContextualType(); + acceptedContextualType = false; + } + + context.setTypeInContext(memberSymbol, memberExprType.getType()); + + memberSymbol.setResolved(); + + this.setSymbolAndDiagnosticsForAST(binex.operand1, SymbolAndDiagnostics.fromSymbol(memberSymbol), context); + + typeSymbol.addMember(memberSymbol, 5 /* PublicMember */); + } + } + + typeSymbol.setResolved(); + return SymbolAndDiagnostics.fromSymbol(typeSymbol); + }; + + PullTypeResolver.prototype.resolveArrayLiteralExpression = function (arrayLit, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(arrayLit); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeArrayLiteralExpressionSymbol(arrayLit, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(arrayLit, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeArrayLiteralExpressionSymbol = function (arrayLit, inContextuallyTypedAssignment, enclosingDecl, context) { + var elements = arrayLit.operand; + var elementType = this.semanticInfoChain.anyTypeSymbol; + var elementTypes = []; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var contextualElementType = null; + comparisonInfo.onlyCaptureFirstError = true; + + if (inContextuallyTypedAssignment) { + var contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, enclosingDecl, context); + + if (contextualType && contextualType.isArray()) { + contextualElementType = contextualType.getElementType(); + } + } + + if (elements) { + if (inContextuallyTypedAssignment) { + context.pushContextualType(contextualElementType, context.inProvisionalResolution(), null); + } + + for (var i = 0; i < elements.members.length; i++) { + elementTypes[elementTypes.length] = this.resolveAST(elements.members[i], inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + } + + if (inContextuallyTypedAssignment) { + context.popContextualType(); + } + } + + if (contextualElementType && !contextualElementType.isTypeParameter()) { + elementType = contextualElementType; + + for (var i = 0; i < elementTypes.length; i++) { + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var currentElementType = elementTypes[i]; + var currentElementAST = elements.members[i]; + if (!this.sourceIsAssignableToTarget(currentElementType, contextualElementType, context, comparisonInfo)) { + var message; + if (comparisonInfo.message) { + message = context.postError(this.getUnitPath(), currentElementAST.minChar, currentElementAST.getLength(), 81 /* Cannot_convert__0__to__1__NL__2 */, [currentElementType.toString(), contextualElementType.toString(), comparisonInfo.message]); + } else { + message = context.postError(this.getUnitPath(), currentElementAST.minChar, currentElementAST.getLength(), 80 /* Cannot_convert__0__to__1_ */, [currentElementType.toString(), contextualElementType.toString()]); + } + + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [message]); + } + } + } else { + if (elementTypes.length) { + elementType = elementTypes[0]; + } else if (contextualElementType) { + elementType = contextualElementType; + } + + var collection = { + getLength: function () { + return elements.members.length; + }, + setTypeAtIndex: function (index, type) { + elementTypes[index] = type; + }, + getTypeAtIndex: function (index) { + return elementTypes[index]; + } + }; + + elementType = this.findBestCommonType(elementType, null, collection, context, comparisonInfo); + + if (elementType === this.semanticInfoChain.undefinedTypeSymbol || elementType === this.semanticInfoChain.nullTypeSymbol) { + elementType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!elementType) { + elementType = this.semanticInfoChain.anyTypeSymbol; + } else if (contextualType && !contextualType.isTypeParameter()) { + if (this.sourceIsAssignableToTarget(elementType, contextualType, context)) { + elementType = contextualType; + } + } + } + + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + if (!this.cachedArrayInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedArrayInterfaceType(), enclosingDecl, context); + } + + arraySymbol = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, elementType, this, context); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + } + + return SymbolAndDiagnostics.fromSymbol(arraySymbol); + }; + + PullTypeResolver.prototype.resolveIndexExpression = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(callEx); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeIndexExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(callEx, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeIndexExpressionSymbol = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context) { + var targetSymbol = this.resolveAST(callEx.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol; + + var targetTypeSymbol = targetSymbol.getType(); + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return SymbolAndDiagnostics.fromSymbol(targetTypeSymbol); + } + + var elementType = targetTypeSymbol.getElementType(); + + var indexType = this.resolveAST(callEx.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + var isNumberIndex = indexType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(indexType); + + if (elementType && isNumberIndex) { + return SymbolAndDiagnostics.fromSymbol(elementType); + } + + if (callEx.operand2.nodeType === 5 /* StringLiteral */ || callEx.operand2.nodeType === 7 /* NumericLiteral */) { + var memberName = callEx.operand2.nodeType === 5 /* StringLiteral */ ? TypeScript.stripQuotes((callEx.operand2).actualText) : TypeScript.quoteStr((callEx.operand2).value.toString()); + + var member = this.getMemberSymbol(memberName, TypeScript.PullElementKind.SomeValue, targetTypeSymbol); + + if (member) { + return SymbolAndDiagnostics.fromSymbol(member.getType()); + } + } + + var signatures = targetTypeSymbol.getIndexSignatures(); + + var stringSignature = null; + var numberSignature = null; + var signature = null; + var paramSymbols; + var paramType; + + for (var i = 0; i < signatures.length; i++) { + if (stringSignature && numberSignature) { + break; + } + + signature = signatures[i]; + + paramSymbols = signature.getParameters(); + + if (paramSymbols.length) { + paramType = paramSymbols[0].getType(); + + if (paramType === this.semanticInfoChain.stringTypeSymbol) { + stringSignature = signatures[i]; + continue; + } else if (paramType === this.semanticInfoChain.numberTypeSymbol || paramType.getKind() === 64 /* Enum */) { + numberSignature = signatures[i]; + continue; + } + } + } + + if (numberSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol)) { + var returnType = numberSignature.getReturnType(); + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { + var returnType = stringSignature.getReturnType(); + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + var returnType = this.semanticInfoChain.anyTypeSymbol; + return SymbolAndDiagnostics.fromSymbol(returnType); + } else { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.getUnitPath(), callEx.minChar, callEx.getLength(), 77 /* Value_of_type__0__is_not_indexable_by_type__1_ */, [targetTypeSymbol.toString(false), indexType.toString(false)])]); + } + }; + + PullTypeResolver.prototype.resolveBitwiseOperator = function (expressionAST, inContextuallyTypedAssignment, enclosingDecl, context) { + var binex = expressionAST; + + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + if (this.sourceIsSubtypeOfTarget(leftType, this.semanticInfoChain.numberTypeSymbol, context) && this.sourceIsSubtypeOfTarget(rightType, this.semanticInfoChain.numberTypeSymbol, context)) { + return this.semanticInfoChain.numberTypeSymbol; + } else if ((leftType === this.semanticInfoChain.booleanTypeSymbol) && (rightType === this.semanticInfoChain.booleanTypeSymbol)) { + return this.semanticInfoChain.booleanTypeSymbol; + } else if (this.isAnyOrEquivalent(leftType)) { + if ((this.isAnyOrEquivalent(rightType) || (rightType === this.semanticInfoChain.numberTypeSymbol) || (rightType === this.semanticInfoChain.booleanTypeSymbol))) { + return this.semanticInfoChain.anyTypeSymbol; + } + } else if (this.isAnyOrEquivalent(rightType)) { + if ((leftType === this.semanticInfoChain.numberTypeSymbol) || (leftType === this.semanticInfoChain.booleanTypeSymbol)) { + return this.semanticInfoChain.anyTypeSymbol; + } + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveArithmeticExpression = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + if (this.isNullOrUndefinedType(leftType)) { + leftType = rightType; + } + if (this.isNullOrUndefinedType(rightType)) { + rightType = leftType; + } + + leftType = this.widenType(leftType); + rightType = this.widenType(rightType); + + if (binex.nodeType === 64 /* AddExpression */ || binex.nodeType === 39 /* AddAssignmentExpression */) { + if (leftType === this.semanticInfoChain.stringTypeSymbol || rightType === this.semanticInfoChain.stringTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + } else if (leftType === this.semanticInfoChain.numberTypeSymbol && rightType === this.semanticInfoChain.numberTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (this.sourceIsSubtypeOfTarget(leftType, this.semanticInfoChain.numberTypeSymbol, context) && this.sourceIsSubtypeOfTarget(rightType, this.semanticInfoChain.numberTypeSymbol, context)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else { + if (leftType === this.semanticInfoChain.numberTypeSymbol && rightType === this.semanticInfoChain.numberTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (this.sourceIsSubtypeOfTarget(leftType, this.semanticInfoChain.numberTypeSymbol, context) && this.sourceIsSubtypeOfTarget(rightType, this.semanticInfoChain.numberTypeSymbol, context)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else if (this.isAnyOrEquivalent(leftType) || this.isAnyOrEquivalent(rightType)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } + }; + + PullTypeResolver.prototype.resolveLogicalOrExpression = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(binex); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeLogicalOrExpressionSymbol(binex, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(binex, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeLogicalOrExpressionSymbol = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + if (this.isAnyOrEquivalent(leftType) || this.isAnyOrEquivalent(rightType)) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } else if (leftType === this.semanticInfoChain.booleanTypeSymbol) { + if (rightType === this.semanticInfoChain.booleanTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.booleanTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else if (leftType === this.semanticInfoChain.numberTypeSymbol) { + if (rightType === this.semanticInfoChain.numberTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.numberTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else if (leftType === this.semanticInfoChain.stringTypeSymbol) { + if (rightType === this.semanticInfoChain.stringTypeSymbol) { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.stringTypeSymbol); + } else { + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + } else if (this.sourceIsSubtypeOfTarget(leftType, rightType, context)) { + return SymbolAndDiagnostics.fromSymbol(rightType); + } else if (this.sourceIsSubtypeOfTarget(rightType, leftType, context)) { + return SymbolAndDiagnostics.fromSymbol(leftType); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + }; + + PullTypeResolver.prototype.resolveLogicalAndExpression = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + return SymbolAndDiagnostics.fromSymbol(this.resolveAST(binex.operand2, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType()); + }; + + PullTypeResolver.prototype.resolveConditionalExpression = function (trinex, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(trinex); + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeConditionalExpressionSymbol(trinex, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(trinex, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeConditionalExpressionSymbol = function (trinex, enclosingDecl, context) { + var leftType = this.resolveAST(trinex.operand2, false, enclosingDecl, context).symbol.getType(); + var rightType = this.resolveAST(trinex.operand3, false, enclosingDecl, context).symbol.getType(); + + var symbol = null; + if (this.typesAreIdentical(leftType, rightType)) { + symbol = leftType; + } else if (this.sourceIsSubtypeOfTarget(leftType, rightType, context) || this.sourceIsSubtypeOfTarget(rightType, leftType, context)) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return rightType; + } + }; + + var bestCommonType = this.findBestCommonType(leftType, null, collection, context); + + if (bestCommonType) { + symbol = bestCommonType; + } + } + + if (!symbol) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.getUnitPath(), trinex.minChar, trinex.getLength(), 160 /* Type_of_conditional_expression_cannot_be_determined__Best_common_type_could_not_be_found_between__0__and__1_ */, [leftType.toString(false), rightType.toString(false)])]); + } + + return SymbolAndDiagnostics.fromSymbol(symbol); + }; + + PullTypeResolver.prototype.resolveParenthesizedExpression = function (ast, enclosingDecl, context) { + return this.resolveAST(ast.expression, false, enclosingDecl, context).withoutDiagnostics(); + }; + + PullTypeResolver.prototype.resolveExpressionStatement = function (ast, inContextuallyTypedAssignment, enclosingDecl, context) { + return this.resolveAST(ast.expression, inContextuallyTypedAssignment, enclosingDecl, context).withoutDiagnostics(); + }; + + PullTypeResolver.prototype.resolveCallExpression = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + if (additionalResults) { + return this.computeCallExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults); + } + + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(callEx); + if (!symbolAndDiagnostics || !symbolAndDiagnostics.symbol.isResolved()) { + symbolAndDiagnostics = this.computeCallExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, null); + this.setSymbolAndDiagnosticsForAST(callEx, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeCallExpressionSymbol = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var targetSymbol = this.resolveAST(callEx.target, inContextuallyTypedAssignment, enclosingDecl, context).symbol; + var targetAST = this.getLastIdentifierInTarget(callEx); + + var targetTypeSymbol = targetSymbol.getType(); + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + if (callEx.typeArguments) { + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), [context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 223 /* Untyped_function_calls_may_not_accept_type_arguments */)]); + } + + return SymbolAndDiagnostics.fromSymbol(this.semanticInfoChain.anyTypeSymbol); + } + + var diagnostics = []; + var isSuperCall = false; + + if (callEx.target.nodeType === 30 /* SuperExpression */) { + isSuperCall = true; + + if (targetTypeSymbol.isClass()) { + targetSymbol = (targetTypeSymbol).getConstructorMethod(); + targetTypeSymbol = targetSymbol.getType(); + } else { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 158 /* Calls_to__super__are_only_valid_inside_a_class */)); + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), diagnostics); + } + } + + var signatures = isSuperCall ? (targetTypeSymbol).getConstructSignatures() : (targetTypeSymbol).getCallSignatures(); + + if (!signatures.length && (targetTypeSymbol.getKind() == 33554432 /* ConstructorType */)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 227 /* Value_of_type__0__is_not_callable__Did_you_mean_to_include__new___ */, [targetTypeSymbol.toString()])); + } + + var typeArgs = null; + var typeReplacementMap = null; + var couldNotFindGenericOverload = false; + var couldNotAssignToConstraint; + + if (callEx.typeArguments) { + typeArgs = []; + + if (callEx.typeArguments && callEx.typeArguments.members.length) { + for (var i = 0; i < callEx.typeArguments.members.length; i++) { + var typeArg = this.resolveTypeReference(callEx.typeArguments.members[i], enclosingDecl, context).symbol; + typeArgs[i] = context.findSpecializationForType(typeArg); + } + } + } else if (isSuperCall && targetTypeSymbol.isGeneric()) { + typeArgs = targetTypeSymbol.getTypeArguments(); + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var prevSpecializingToAny = context.specializingToAny; + var prevSpecializing = context.isSpecializingSignatureAtCallSite; + var beforeResolutionSignatures = signatures; + var triedToInferTypeArgs; + + for (var i = 0; i < signatures.length; i++) { + typeParameters = signatures[i].getTypeParameters(); + couldNotAssignToConstraint = false; + triedToInferTypeArgs = false; + + if (signatures[i].isGeneric() && typeParameters.length && !signatures[i].isFixed()) { + if (typeArgs) { + inferredTypeArgs = typeArgs; + } else if (callEx.arguments) { + inferredTypeArgs = this.inferArgumentTypesForSignature(signatures[i], callEx.arguments, new TypeScript.TypeComparisonInfo(), enclosingDecl, context); + triedToInferTypeArgs = true; + } + + if (inferredTypeArgs) { + typeReplacementMap = {}; + + if (inferredTypeArgs.length) { + if (inferredTypeArgs.length != typeParameters.length) { + continue; + } + + for (var j = 0; j < typeParameters.length; j++) { + typeReplacementMap[typeParameters[j].getSymbolID().toString()] = inferredTypeArgs[j]; + } + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { + if (typeParameters[k] == typeConstraint) { + typeConstraint = inferredTypeArgs[k]; + } + } + } + if (typeConstraint.isTypeParameter()) { + context.pushTypeSpecializationCache(typeReplacementMap); + typeConstraint = TypeScript.specializeType(typeConstraint, null, this, enclosingDecl, context); + context.popTypeSpecializationCache(); + } + context.isComparingSpecializedSignatures = true; + if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, context)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 155 /* Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_ */, [inferredTypeArgs[j].toString(true), typeConstraint.toString(true), typeParameters[j].toString(true)])); + couldNotAssignToConstraint = true; + } + context.isComparingSpecializedSignatures = false; + + if (couldNotAssignToConstraint) { + break; + } + } + } + } else { + if (triedToInferTypeArgs) { + if (signatures[i].parametersAreFixed()) { + if (signatures[i].hasGenericParameter()) { + context.specializingToAny = true; + } else { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } else { + continue; + } + } + + context.specializingToAny = true; + } + + if (couldNotAssignToConstraint) { + continue; + } + + context.isSpecializingSignatureAtCallSite = true; + specializedSignature = TypeScript.specializeSignature(signatures[i], false, typeReplacementMap, inferredTypeArgs, this, enclosingDecl, context); + + context.isSpecializingSignatureAtCallSite = prevSpecializing; + context.specializingToAny = prevSpecializingToAny; + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } + } else { + if (!(callEx.typeArguments && callEx.typeArguments.members.length)) { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } + } + + if (signatures.length && !resolvedSignatures.length) { + couldNotFindGenericOverload = true; + } + + signatures = resolvedSignatures; + } + + var errorCondition = null; + + if (!signatures.length) { + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures && beforeResolutionSignatures.length ? beforeResolutionSignatures[0] : null; + + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + } + + if (!couldNotFindGenericOverload) { + if (this.cachedFunctionInterfaceType() && this.sourceIsSubtypeOfTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), context)) { + return SymbolAndDiagnostics.create(this.semanticInfoChain.anyTypeSymbol, diagnostics); + } + + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, callEx.minChar, callEx.getLength(), 157 /* Unable_to_invoke_type_with_no_call_signatures */)); + errorCondition = this.getNewErrorTypeSymbol(null); + } else { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, callEx.minChar, callEx.getLength(), 156 /* Could_not_select_overload_for__call__expression */)); + errorCondition = this.getNewErrorTypeSymbol(null); + } + + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + var signature = this.resolveOverloads(callEx, signatures, enclosingDecl, callEx.typeArguments != null, context, diagnostics); + var useBeforeResolutionSignatures = signature == null; + + if (!signature) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 156 /* Could_not_select_overload_for__call__expression */)); + + errorCondition = this.getNewErrorTypeSymbol(null); + + if (!signatures.length) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + signature = signatures[0]; + + if (callEx.arguments) { + for (var k = 0, n = callEx.arguments.members.length; k < n; k++) { + var arg = callEx.arguments.members[k]; + var argSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(arg); + var argSymbol = argSymbolAndDiagnostics && argSymbolAndDiagnostics.symbol; + + if (argSymbol) { + var argType = argSymbol.getType(); + if (arg.nodeType === 12 /* FunctionDeclaration */) { + if (!this.canApplyContextualTypeToFunction(argType, arg, true)) { + continue; + } + } + + argSymbol.invalidate(); + } + } + } + } + + if (!signature.isGeneric() && callEx.typeArguments) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 224 /* Non_generic_functions_may_not_accept_type_arguments */)); + } + + var returnType = signature.getReturnType(); + + var actualParametersContextTypeSymbols = []; + if (callEx.arguments) { + var len = callEx.arguments.members.length; + var params = signature.getParameters(); + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVariableParamList())) { + if (typeReplacementMap) { + context.pushTypeSpecializationCache(typeReplacementMap); + } + this.resolveDeclaredSymbol(params[i], signatureDecl, context); + if (typeReplacementMap) { + context.popTypeSpecializationCache(); + } + contextualType = params[i].getType(); + } else if (signature.hasVariableParamList()) { + contextualType = params[params.length - 1].getType(); + if (contextualType.isArray()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.arguments.members[i], contextualType != null, enclosingDecl, context); + + if (contextualType) { + context.popContextualType(); + contextualType = null; + } + } + } + + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + if (useBeforeResolutionSignatures && beforeResolutionSignatures) { + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures[0]; + } else { + additionalResults.resolvedSignatures = signatures; + additionalResults.candidateSignature = signature; + } + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + } + + if (errorCondition) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + }; + + PullTypeResolver.prototype.resolveNewExpression = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + if (additionalResults) { + return this.computeNewExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults); + } + + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(callEx); + if (!symbolAndDiagnostics || !symbolAndDiagnostics.symbol.isResolved()) { + symbolAndDiagnostics = this.computeNewExpressionSymbol(callEx, inContextuallyTypedAssignment, enclosingDecl, context, null); + this.setSymbolAndDiagnosticsForAST(callEx, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeNewExpressionSymbol = function (callEx, inContextuallyTypedAssignment, enclosingDecl, context, additionalResults) { + var returnType = null; + + var targetSymbol = this.resolveAST(callEx.target, inContextuallyTypedAssignment, enclosingDecl, context).symbol; + var targetTypeSymbol = targetSymbol.isType() ? targetSymbol : targetSymbol.getType(); + + var targetAST = this.getLastIdentifierInTarget(callEx); + + if (targetTypeSymbol.isClass()) { + targetTypeSymbol = (targetTypeSymbol).getConstructorMethod().getType(); + } + + var constructSignatures = targetTypeSymbol.getConstructSignatures(); + + var typeArgs = null; + var typeReplacementMap = null; + var usedCallSignaturesInstead = false; + var couldNotAssignToConstraint; + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return SymbolAndDiagnostics.fromSymbol(targetTypeSymbol); + } + + if (!constructSignatures.length) { + constructSignatures = targetTypeSymbol.getCallSignatures(); + usedCallSignaturesInstead = true; + } + + var diagnostics = []; + if (constructSignatures.length) { + if (callEx.typeArguments) { + typeArgs = []; + + if (callEx.typeArguments && callEx.typeArguments.members.length) { + for (var i = 0; i < callEx.typeArguments.members.length; i++) { + var typeArg = this.resolveTypeReference(callEx.typeArguments.members[i], enclosingDecl, context).symbol; + typeArgs[i] = context.findSpecializationForType(typeArg); + } + } + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var prevSpecializingToAny = context.specializingToAny; + var prevIsSpecializing = context.isSpecializingSignatureAtCallSite = true; + var triedToInferTypeArgs; + + for (var i = 0; i < constructSignatures.length; i++) { + couldNotAssignToConstraint = false; + + if (constructSignatures[i].isGeneric() && !constructSignatures[i].isFixed()) { + if (typeArgs) { + inferredTypeArgs = typeArgs; + } else if (callEx.arguments) { + inferredTypeArgs = this.inferArgumentTypesForSignature(constructSignatures[i], callEx.arguments, new TypeScript.TypeComparisonInfo(), enclosingDecl, context); + triedToInferTypeArgs = true; + } + + if (inferredTypeArgs) { + typeParameters = constructSignatures[i].getTypeParameters(); + + typeReplacementMap = {}; + + if (inferredTypeArgs.length) { + if (inferredTypeArgs.length < typeParameters.length) { + continue; + } + + for (var j = 0; j < typeParameters.length; j++) { + typeReplacementMap[typeParameters[j].getSymbolID().toString()] = inferredTypeArgs[j]; + } + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { + if (typeParameters[k] == typeConstraint) { + typeConstraint = inferredTypeArgs[k]; + } + } + } + if (typeConstraint.isTypeParameter()) { + context.pushTypeSpecializationCache(typeReplacementMap); + typeConstraint = TypeScript.specializeType(typeConstraint, null, this, enclosingDecl, context); + context.popTypeSpecializationCache(); + } + + context.isComparingSpecializedSignatures = true; + if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, context)) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 155 /* Type__0__does_not_satisfy_the_constraint__1__for_type_parameter__2_ */, [inferredTypeArgs[j].toString(true), typeConstraint.toString(true), typeParameters[j].toString(true)])); + couldNotAssignToConstraint = true; + } + context.isComparingSpecializedSignatures = false; + + if (couldNotAssignToConstraint) { + break; + } + } + } + } else { + if (triedToInferTypeArgs) { + if (constructSignatures[i].parametersAreFixed()) { + if (constructSignatures[i].hasGenericParameter()) { + context.specializingToAny = true; + } else { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } else { + continue; + } + } + + context.specializingToAny = true; + } + + if (couldNotAssignToConstraint) { + continue; + } + + context.isSpecializingSignatureAtCallSite = true; + specializedSignature = TypeScript.specializeSignature(constructSignatures[i], false, typeReplacementMap, inferredTypeArgs, this, enclosingDecl, context); + + context.specializingToAny = prevSpecializingToAny; + context.isSpecializingSignatureAtCallSite = prevIsSpecializing; + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } + } else { + if (!(callEx.typeArguments && callEx.typeArguments.members.length)) { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } + } + + constructSignatures = resolvedSignatures; + } + + var signature = this.resolveOverloads(callEx, constructSignatures, enclosingDecl, callEx.typeArguments != null, context, diagnostics); + + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = []; + } + + if (!constructSignatures.length && diagnostics) { + var result = this.getNewErrorTypeSymbol(null); + return SymbolAndDiagnostics.create(result, diagnostics); + } + + var errorCondition = null; + + if (!signature) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 154 /* Could_not_select_overload_for__new__expression */)); + + errorCondition = this.getNewErrorTypeSymbol(null); + + if (!constructSignatures.length) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + signature = constructSignatures[0]; + + if (callEx.arguments) { + for (var k = 0, n = callEx.arguments.members.length; k < n; k++) { + var arg = callEx.arguments.members[k]; + var argSymbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(arg); + var argSymbol = argSymbolAndDiagnostics && argSymbolAndDiagnostics.symbol; + + if (argSymbol) { + var argType = argSymbol.getType(); + if (arg.nodeType === 12 /* FunctionDeclaration */) { + if (!this.canApplyContextualTypeToFunction(argType, arg, true)) { + continue; + } + } + + argSymbol.invalidate(); + } + } + } + } + + returnType = signature.getReturnType(); + + if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { + if (typeArgs && typeArgs.length) { + returnType = TypeScript.specializeType(returnType, typeArgs, this, enclosingDecl, context, callEx); + } else { + returnType = this.specializeTypeToAny(returnType, enclosingDecl, context); + } + } + + if (usedCallSignaturesInstead) { + if (returnType != this.semanticInfoChain.voidTypeSymbol) { + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 153 /* Call_signatures_used_in_a__new__expression_must_have_a__void__return_type */)); + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), diagnostics); + } else { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (!returnType) { + returnType = signature.getReturnType(); + + if (!returnType) { + returnType = targetTypeSymbol; + } + } + + var actualParametersContextTypeSymbols = []; + if (callEx.arguments) { + var len = callEx.arguments.members.length; + var params = signature.getParameters(); + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVariableParamList())) { + if (typeReplacementMap) { + context.pushTypeSpecializationCache(typeReplacementMap); + } + this.resolveDeclaredSymbol(params[i], signatureDecl, context); + if (typeReplacementMap) { + context.popTypeSpecializationCache(); + } + contextualType = params[i].getType(); + } else if (signature.hasVariableParamList()) { + contextualType = params[params.length - 1].getType(); + if (contextualType.isArray()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.arguments.members[i], contextualType != null, enclosingDecl, context); + + if (contextualType) { + context.popContextualType(); + contextualType = null; + } + } + } + + if (additionalResults) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.targetTypeSymbol = targetTypeSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + } + + if (errorCondition) { + return SymbolAndDiagnostics.create(errorCondition, diagnostics); + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return SymbolAndDiagnostics.fromSymbol(returnType); + } else if (targetTypeSymbol.isClass()) { + return SymbolAndDiagnostics.fromSymbol(returnType); + } + + diagnostics = this.addDiagnostic(diagnostics, context.postError(this.unitPath, targetAST.minChar, targetAST.getLength(), 152 /* Invalid__new__expression */)); + + return SymbolAndDiagnostics.create(this.getNewErrorTypeSymbol(null), diagnostics); + }; + + PullTypeResolver.prototype.resolveTypeAssertionExpression = function (assertionExpression, inContextuallyTypedAssignment, enclosingDecl, context) { + return this.resolveTypeReference(assertionExpression.castTerm, enclosingDecl, context); + }; + + PullTypeResolver.prototype.resolveAssignmentStatement = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var symbolAndDiagnostics = this.getSymbolAndDiagnosticsForAST(binex); + + if (!symbolAndDiagnostics) { + symbolAndDiagnostics = this.computeAssignmentStatementSymbol(binex, inContextuallyTypedAssignment, enclosingDecl, context); + this.setSymbolAndDiagnosticsForAST(binex, symbolAndDiagnostics, context); + } + + return symbolAndDiagnostics; + }; + + PullTypeResolver.prototype.computeAssignmentStatementSymbol = function (binex, inContextuallyTypedAssignment, enclosingDecl, context) { + var leftType = this.resolveAST(binex.operand1, inContextuallyTypedAssignment, enclosingDecl, context).symbol.getType(); + + context.pushContextualType(leftType, context.inProvisionalResolution(), null); + this.resolveAST(binex.operand2, true, enclosingDecl, context); + context.popContextualType(); + + return SymbolAndDiagnostics.fromSymbol(leftType); + }; + + PullTypeResolver.prototype.resolveBoundDecls = function (decl, context) { + if (!decl) { + return; + } + + switch (decl.getKind()) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.resolveBoundDecls(childDecls[i], context); + } + break; + case 32 /* DynamicModule */: + case 4 /* Container */: + case 64 /* Enum */: + var moduleDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveModuleDeclaration(moduleDecl, context); + break; + case 16 /* Interface */: + var interfaceDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveInterfaceDeclaration(interfaceDecl, context); + break; + case 8 /* Class */: + var classDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveClassDeclaration(classDecl, context); + break; + case 65536 /* Method */: + case 16384 /* Function */: + var funcDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveFunctionDeclaration(funcDecl, context); + break; + case 262144 /* GetAccessor */: + funcDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveGetAccessorDeclaration(funcDecl, context); + break; + case 524288 /* SetAccessor */: + funcDecl = this.semanticInfoChain.getASTForDecl(decl); + this.resolveSetAccessorDeclaration(funcDecl, context); + break; + case 4096 /* Property */: + case 1024 /* Variable */: + case 2048 /* Parameter */: + var varDecl = this.semanticInfoChain.getASTForDecl(decl); + + if (varDecl) { + this.resolveVariableDeclaration(varDecl, context); + } + break; + } + }; + + PullTypeResolver.prototype.mergeOrdered = function (a, b, context, comparisonInfo) { + if (this.isAnyOrEquivalent(a) || this.isAnyOrEquivalent(b)) { + return this.semanticInfoChain.anyTypeSymbol; + } else if (a === b) { + return a; + } else if ((b === this.semanticInfoChain.nullTypeSymbol) && a != this.semanticInfoChain.nullTypeSymbol) { + return a; + } else if ((a === this.semanticInfoChain.nullTypeSymbol) && (b != this.semanticInfoChain.nullTypeSymbol)) { + return b; + } else if ((a === this.semanticInfoChain.voidTypeSymbol) && (b === this.semanticInfoChain.voidTypeSymbol || b === this.semanticInfoChain.undefinedTypeSymbol || b === this.semanticInfoChain.nullTypeSymbol)) { + return a; + } else if ((a === this.semanticInfoChain.voidTypeSymbol) && (b === this.semanticInfoChain.anyTypeSymbol)) { + return b; + } else if ((b === this.semanticInfoChain.undefinedTypeSymbol) && a != this.semanticInfoChain.voidTypeSymbol) { + return a; + } else if ((a === this.semanticInfoChain.undefinedTypeSymbol) && (b != this.semanticInfoChain.undefinedTypeSymbol)) { + return b; + } else if (a.isTypeParameter() && !b.isTypeParameter()) { + return b; + } else if (!a.isTypeParameter() && b.isTypeParameter()) { + return a; + } else if (a.isArray() && b.isArray()) { + if (a.getElementType() === b.getElementType()) { + return a; + } else { + var mergedET = this.mergeOrdered(a.getElementType(), b.getElementType(), context, comparisonInfo); + if (mergedET) { + var mergedArrayType = mergedET.getArrayType(); + + if (!mergedArrayType) { + mergedArrayType = TypeScript.specializeToArrayType(this.semanticInfoChain.elementTypeSymbol, mergedET, this, context); + } + + return mergedArrayType; + } + } + } else if (this.sourceIsSubtypeOfTarget(a, b, context, comparisonInfo)) { + return b; + } else if (this.sourceIsSubtypeOfTarget(b, a, context, comparisonInfo)) { + return a; + } + + return null; + }; + + PullTypeResolver.prototype.widenType = function (type) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol || type.isError()) { + return this.semanticInfoChain.anyTypeSymbol; + } + + return type; + }; + + PullTypeResolver.prototype.isNullOrUndefinedType = function (type) { + return type === this.semanticInfoChain.nullTypeSymbol || type === this.semanticInfoChain.undefinedTypeSymbol; + }; + + PullTypeResolver.prototype.canApplyContextualType = function (type) { + if (!type) { + return true; + } + + var kind = type.getKind(); + + if ((kind & 8388608 /* ObjectType */) != 0) { + return true; + } + if ((kind & 16 /* Interface */) != 0) { + return true; + } else if ((kind & TypeScript.PullElementKind.SomeFunction) != 0) { + return this.canApplyContextualTypeToFunction(type, this.semanticInfoChain.getASTForDecl(type.getDeclarations[0]), true); + } else if ((kind & 128 /* Array */) != 0) { + return true; + } else if (type == this.semanticInfoChain.anyTypeSymbol || kind != 2 /* Primitive */) { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.findBestCommonType = function (initialType, targetType, collection, context, comparisonInfo) { + var len = collection.getLength(); + var nlastChecked = 0; + var bestCommonType = initialType; + + if (targetType && this.canApplyContextualType(bestCommonType)) { + if (bestCommonType) { + bestCommonType = this.mergeOrdered(bestCommonType, targetType, context); + } else { + bestCommonType = targetType; + } + } + + var convergenceType = bestCommonType; + + while (nlastChecked < len) { + for (var i = 0; i < len; i++) { + if (i === nlastChecked) { + continue; + } + + if (convergenceType && (bestCommonType = this.mergeOrdered(convergenceType, collection.getTypeAtIndex(i), context, comparisonInfo))) { + convergenceType = bestCommonType; + } + + if (bestCommonType === null || this.isAnyOrEquivalent(bestCommonType)) { + break; + } else if (targetType && !(bestCommonType.isTypeParameter() || targetType.isTypeParameter())) { + collection.setTypeAtIndex(i, targetType); + } + } + + if (convergenceType && bestCommonType) { + break; + } + + nlastChecked++; + if (nlastChecked < len) { + convergenceType = collection.getTypeAtIndex(nlastChecked); + } + } + + if (!bestCommonType) { + var emptyTypeDecl = new TypeScript.PullDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, new TypeScript.TextSpan(0, 0), this.currentUnit.getPath()); + var emptyType = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); + + emptyTypeDecl.setSymbol(emptyType); + emptyType.addDeclaration(emptyTypeDecl); + + bestCommonType = emptyType; + } + + return bestCommonType; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, val) { + if (t1 === t2) { + return true; + } + + if (!t1 || !t2) { + return false; + } + + if (val && t1.isPrimitive() && (t1).isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { + return (val.nodeType === 5 /* StringLiteral */) && (TypeScript.stripQuotes((val).actualText) === TypeScript.stripQuotes(t1.getName())); + } + + if (val && t2.isPrimitive() && (t2).isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { + return (val.nodeType === 5 /* StringLiteral */) && (TypeScript.stripQuotes((val).actualText) === TypeScript.stripQuotes(t2.getName())); + } + + if (t1.isPrimitive() && (t1).isStringConstant() && t2.isPrimitive() && (t2).isStringConstant()) { + return TypeScript.stripQuotes(t1.getName()) === TypeScript.stripQuotes(t2.getName()); + } + + if (t1.isPrimitive() || t2.isPrimitive()) { + return false; + } + + if (t1.isClass()) { + return false; + } + + if (t1.isError() && t2.isError()) { + return true; + } + + if (t1.isTypeParameter()) { + if (!t2.isTypeParameter()) { + return false; + } + + var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); + var t2ParentDeclaration = t2.getDeclarations()[0].getParentDecl(); + + if (t1ParentDeclaration === t2ParentDeclaration) { + return this.symbolsShareDeclaration(t1, t2); + } else { + return true; + } + } + + var comboId = t2.getSymbolID().toString() + "#" + t1.getSymbolID().toString(); + + if (this.identicalCache[comboId] != undefined) { + return true; + } + + if ((t1.getKind() & 64 /* Enum */) || (t2.getKind() & 64 /* Enum */)) { + return t1.getAssociatedContainerType() === t2 || t2.getAssociatedContainerType() === t1; + } + + if (t1.isArray() || t2.isArray()) { + if (!(t1.isArray() && t2.isArray())) { + return false; + } + this.identicalCache[comboId] = false; + var ret = this.typesAreIdentical(t1.getElementType(), t2.getElementType()); + if (ret) { + this.identicalCache[comboId] = true; + } else { + this.identicalCache[comboId] = undefined; + } + + return ret; + } + + if (t1.isPrimitive() != t2.isPrimitive()) { + return false; + } + + this.identicalCache[comboId] = false; + + if (t1.hasMembers() && t2.hasMembers()) { + var t1Members = t1.getMembers(); + var t2Members = t2.getMembers(); + + if (t1Members.length != t2Members.length) { + this.identicalCache[comboId] = undefined; + return false; + } + + var t1MemberSymbol = null; + var t2MemberSymbol = null; + + var t1MemberType = null; + var t2MemberType = null; + + for (var iMember = 0; iMember < t1Members.length; iMember++) { + t1MemberSymbol = t1Members[iMember]; + t2MemberSymbol = this.getMemberSymbol(t1MemberSymbol.getName(), TypeScript.PullElementKind.SomeValue, t2); + + if (!t2MemberSymbol || (t1MemberSymbol.getIsOptional() != t2MemberSymbol.getIsOptional())) { + this.identicalCache[comboId] = undefined; + return false; + } + + t1MemberType = t1MemberSymbol.getType(); + t2MemberType = t2MemberSymbol.getType(); + + if (t1MemberType && t2MemberType && (this.identicalCache[t2MemberType.getSymbolID().toString() + "#" + t1MemberType.getSymbolID().toString()] != undefined)) { + continue; + } + + if (!this.typesAreIdentical(t1MemberType, t2MemberType)) { + this.identicalCache[comboId] = undefined; + return false; + } + } + } else if (t1.hasMembers() || t2.hasMembers()) { + this.identicalCache[comboId] = undefined; + return false; + } + + var t1CallSigs = t1.getCallSignatures(); + var t2CallSigs = t2.getCallSignatures(); + + var t1ConstructSigs = t1.getConstructSignatures(); + var t2ConstructSigs = t2.getConstructSignatures(); + + var t1IndexSigs = t1.getIndexSignatures(); + var t2IndexSigs = t2.getIndexSignatures(); + + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs)) { + this.identicalCache[comboId] = undefined; + return false; + } + + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs)) { + this.identicalCache[comboId] = undefined; + return false; + } + + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs)) { + this.identicalCache[comboId] = undefined; + return false; + } + + this.identicalCache[comboId] = true; + return true; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + if (sg1 === sg2) { + return true; + } + + if (!sg1 || !sg2) { + return false; + } + + if (sg1.length != sg2.length) { + return false; + } + + var sig1 = null; + var sig2 = null; + var sigsMatch = false; + + for (var iSig1 = 0; iSig1 < sg1.length; iSig1++) { + sig1 = sg1[iSig1]; + + for (var iSig2 = 0; iSig2 < sg2.length; iSig2++) { + sig2 = sg2[iSig2]; + + if (this.signaturesAreIdentical(sig1, sig2)) { + sigsMatch = true; + break; + } + } + + if (sigsMatch) { + sigsMatch = false; + continue; + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2) { + if (s1.hasVariableParamList() != s2.hasVariableParamList()) { + return false; + } + + if (s1.getNonOptionalParameterCount() != s2.getNonOptionalParameterCount()) { + return false; + } + + var s1Params = s1.getParameters(); + var s2Params = s2.getParameters(); + + if (s1Params.length != s2Params.length) { + return false; + } + + if (!this.typesAreIdentical(s1.getReturnType(), s2.getReturnType())) { + return false; + } + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + if (!this.typesAreIdentical(s1Params[iParam].getType(), s2Params[iParam].getType())) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.substituteUpperBoundForType = function (type) { + if (!type || !type.isTypeParameter()) { + return type; + } + + var constraint = (type).getConstraint(); + + if (constraint) { + return this.substituteUpperBoundForType(constraint); + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType(); + } + + return type; + }; + + PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { + var decls1 = symbol1.getDeclarations(); + var decls2 = symbol2.getDeclarations(); + + if (decls1.length && decls2.length) { + return decls1[0].isEqual(decls2[0]); + } + + return false; + }; + + PullTypeResolver.prototype.sourceIsSubtypeOfTarget = function (source, target, context, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceMembersAreSubtypeOfTargetMembers = function (source, target, context, comparisonInfo) { + return this.sourceMembersAreRelatableToTargetMembers(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourcePropertyIsSubtypeOfTargetProperty = function (source, target, sourceProp, targetProp, context, comparisonInfo) { + return this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreSubtypeOfTargetCallSignatures = function (source, target, context, comparisonInfo) { + return this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures = function (source, target, context, comparisonInfo) { + return this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures = function (source, target, context, comparisonInfo) { + return this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.typeIsSubtypeOfFunction = function (source, context) { + var callSignatures = source.getCallSignatures(); + + if (callSignatures.length) { + return true; + } + + var constructSignatures = source.getConstructSignatures(); + + if (constructSignatures.length) { + return true; + } + + if (this.cachedFunctionInterfaceType()) { + return this.sourceIsSubtypeOfTarget(source, this.cachedFunctionInterfaceType(), context); + } + + return false; + }; + + PullTypeResolver.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, context, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.signatureIsSubtypeOfTarget = function (s1, s2, context, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, context, comparisonInfo, isInProvisionalResolution) { + if (typeof isInProvisionalResolution === "undefined") { isInProvisionalResolution = false; } + var cache = isInProvisionalResolution ? {} : this.assignableCache; + return this.sourceIsRelatableToTarget(source, target, true, cache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, context, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, context, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, context, comparisonInfo); + }; + + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + if (source === target) { + return true; + } + + if (!(source && target)) { + return true; + } + + if (context.specializingToAny && (target.isTypeParameter() || source.isTypeParameter())) { + return true; + } + + if (context.specializingToObject) { + if (target.isTypeParameter()) { + target = this.cachedObjectInterfaceType(); + } + if (source.isTypeParameter()) { + target = this.cachedObjectInterfaceType(); + } + } + + var sourceSubstitution = source; + + if (source == this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { + if (!this.cachedStringInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedStringInterfaceType(), null, context); + } + sourceSubstitution = this.cachedStringInterfaceType(); + } else if (source == this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { + if (!this.cachedNumberInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedNumberInterfaceType(), null, context); + } + sourceSubstitution = this.cachedNumberInterfaceType(); + } else if (source == this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { + if (!this.cachedBooleanInterfaceType().isResolved()) { + this.resolveDeclaredSymbol(this.cachedBooleanInterfaceType(), null, context); + } + sourceSubstitution = this.cachedBooleanInterfaceType(); + } else if (TypeScript.PullHelpers.symbolIsEnum(source) && this.cachedNumberInterfaceType()) { + sourceSubstitution = this.cachedNumberInterfaceType(); + } else if (source.isTypeParameter()) { + sourceSubstitution = this.substituteUpperBoundForType(source); + } + + var comboId = source.getSymbolID().toString() + "#" + target.getSymbolID().toString(); + + if (comparisonCache[comboId] != undefined) { + return true; + } + + if (assignableTo) { + if (this.isAnyOrEquivalent(source) || this.isAnyOrEquivalent(target)) { + return true; + } + + if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && (target).isStringConstant()) { + return comparisonInfo && comparisonInfo.stringConstantVal && (comparisonInfo.stringConstantVal.nodeType === 5 /* StringLiteral */) && (TypeScript.stripQuotes((comparisonInfo.stringConstantVal).actualText) === TypeScript.stripQuotes(target.getName())); + } + } else { + if (this.isAnyOrEquivalent(target)) { + return true; + } + + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && (source).isStringConstant()) { + return true; + } + } + + if (source.isPrimitive() && (source).isStringConstant() && target.isPrimitive() && (target).isStringConstant()) { + return TypeScript.stripQuotes(source.getName()) === TypeScript.stripQuotes(target.getName()); + } + + if (source === this.semanticInfoChain.undefinedTypeSymbol) { + return true; + } + + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target != this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + return true; + } + + if (target == this.semanticInfoChain.voidTypeSymbol) { + if (source == this.semanticInfoChain.anyTypeSymbol || source == this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + return true; + } + + return false; + } else if (source == this.semanticInfoChain.voidTypeSymbol) { + if (target == this.semanticInfoChain.anyTypeSymbol) { + return true; + } + + return false; + } + + if (target === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(source)) { + return true; + } + + if (source === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(target)) { + return true; + } + + if (TypeScript.PullHelpers.symbolIsEnum(target) && TypeScript.PullHelpers.symbolIsEnum(source)) { + return this.symbolsShareDeclaration(target, source); + } + + if ((source.getKind() & 64 /* Enum */) || (target.getKind() & 64 /* Enum */)) { + return false; + } + + if (source.isArray() && target.isArray()) { + comparisonCache[comboId] = false; + var ret = this.sourceIsRelatableToTarget(source.getElementType(), target.getElementType(), assignableTo, comparisonCache, context, comparisonInfo); + if (ret) { + comparisonCache[comboId] = true; + } else { + comparisonCache[comboId] = undefined; + } + + return ret; + } else if (source.isArray() && target == this.cachedArrayInterfaceType()) { + return true; + } else if (target.isArray() && source == this.cachedArrayInterfaceType()) { + return true; + } + + if (source.isPrimitive() && target.isPrimitive()) { + return false; + } else if (source.isPrimitive() != target.isPrimitive()) { + if (target.isPrimitive()) { + return false; + } + } + + if (target.isTypeParameter()) { + if (source.isTypeParameter() && (source == sourceSubstitution)) { + var targetParentDeclaration = target.getDeclarations()[0].getParentDecl(); + var sourceParentDeclaration = source.getDeclarations()[0].getParentDecl(); + + if (targetParentDeclaration !== sourceParentDeclaration) { + return this.symbolsShareDeclaration(target, source); + } else { + return true; + } + } else { + if (context.isComparingSpecializedSignatures) { + target = this.substituteUpperBoundForType(target); + } else { + return false; + } + } + } + + comparisonCache[comboId] = false; + + if (sourceSubstitution.hasBase(target)) { + comparisonCache[comboId] = true; + return true; + } + + if (this.cachedObjectInterfaceType() && target === this.cachedObjectInterfaceType()) { + return true; + } + + if (this.cachedFunctionInterfaceType() && (sourceSubstitution.getCallSignatures().length || sourceSubstitution.getConstructSignatures().length) && target === this.cachedFunctionInterfaceType()) { + return true; + } + + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(sourceSubstitution, target, assignableTo, comparisonCache, context, comparisonInfo)) { + comparisonCache[comboId] = undefined; + return false; + } + + comparisonCache[comboId] = true; + return true; + }; + + PullTypeResolver.prototype.sourceMembersAreRelatableToTargetMembers = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetProps = target.getAllMembers(TypeScript.PullElementKind.SomeValue, true); + + for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { + var targetProp = targetProps[itargetProp]; + var sourceProp = this.getMemberSymbol(targetProp.getName(), TypeScript.PullElementKind.SomeValue, source); + + if (!targetProp.isResolved()) { + this.resolveDeclaredSymbol(targetProp, null, context); + } + + var targetPropType = targetProp.getType(); + + if (!sourceProp) { + if (this.cachedObjectInterfaceType()) { + sourceProp = this.getMemberSymbol(targetProp.getName(), TypeScript.PullElementKind.SomeValue, this.cachedObjectInterfaceType()); + } + + if (!sourceProp) { + if (this.cachedFunctionInterfaceType() && (targetPropType.getCallSignatures().length || targetPropType.getConstructSignatures().length)) { + sourceProp = this.getMemberSymbol(targetProp.getName(), TypeScript.PullElementKind.SomeValue, this.cachedFunctionInterfaceType()); + } + + if (!sourceProp) { + if (!(targetProp.getIsOptional())) { + if (comparisonInfo) { + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(240 /* Type__0__is_missing_property__1__from_type__2_ */, [source.toString(), targetProp.getScopedNameEx().toString(), target.toString()])); + } + return false; + } + continue; + } + } + } + + if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, context, comparisonInfo)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, context, comparisonInfo) { + var targetPropIsPrivate = targetProp.hasFlag(2 /* Private */); + var sourcePropIsPrivate = sourceProp.hasFlag(2 /* Private */); + + if (targetPropIsPrivate != sourcePropIsPrivate) { + if (comparisonInfo) { + if (targetPropIsPrivate) { + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(244 /* Property__0__defined_as_public_in_type__1__is_defined_as_private_in_type__2_ */, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(), targetProp.getContainer().toString()])); + } else { + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(243 /* Property__0__defined_as_private_in_type__1__is_defined_as_public_in_type__2_ */, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(), targetProp.getContainer().toString()])); + } + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + } + return false; + } else if (sourcePropIsPrivate && targetPropIsPrivate) { + var targetDecl = targetProp.getDeclarations()[0]; + var sourceDecl = sourceProp.getDeclarations()[0]; + + if (!targetDecl.isEqual(sourceDecl)) { + if (comparisonInfo) { + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(245 /* Types__0__and__1__define_property__2__as_private */, [sourceProp.getContainer().toString(), targetProp.getContainer().toString(), targetProp.getScopedNameEx().toString()])); + } + return false; + } + } + + if (!sourceProp.isResolved()) { + this.resolveDeclaredSymbol(sourceProp, null, context); + } + + var sourcePropType = sourceProp.getType(); + var targetPropType = targetProp.getType(); + + if (targetPropType && sourcePropType && (comparisonCache[sourcePropType.getSymbolID().toString() + "#" + targetPropType.getSymbolID().toString()] != undefined)) { + return true; + } + + var comparisonInfoPropertyTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoPropertyTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + if (!this.sourceIsRelatableToTarget(sourcePropType, targetPropType, assignableTo, comparisonCache, context, comparisonInfoPropertyTypeCheck)) { + if (comparisonInfo) { + comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; + var message; + if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(242 /* Types_of_property__0__of_types__1__and__2__are_incompatible__NL__3 */, [targetProp.getScopedNameEx().toString(), source.toString(), target.toString(), comparisonInfoPropertyTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(241 /* Types_of_property__0__of_types__1__and__2__are_incompatible */, [targetProp.getScopedNameEx().toString(), source.toString(), target.toString()]); + } + comparisonInfo.addMessage(message); + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetCallSigs = target.getCallSignatures(); + + if (targetCallSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + + var sourceCallSigs = source.getCallSignatures(); + if (!this.signatureGroupIsRelatableToTarget(sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, context, comparisonInfoSignatuesTypeCheck)) { + if (comparisonInfo) { + var message; + if (sourceCallSigs.length && targetCallSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(247 /* Call_signatures_of_types__0__and__1__are_incompatible__NL__2 */, [source.toString(), target.toString(), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(246 /* Call_signatures_of_types__0__and__1__are_incompatible */, [source.toString(), target.toString()]); + } + } else { + var hasSig = targetCallSigs.length ? target.toString() : source.toString(); + var lacksSig = !targetCallSigs.length ? target.toString() : source.toString(); + message = TypeScript.getDiagnosticMessage(248 /* Type__0__requires_a_call_signature__but_Type__1__lacks_one */, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreRelatableToTargetConstructSignatures = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetConstructSigs = target.getConstructSignatures(); + if (targetConstructSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + + var sourceConstructSigs = source.getConstructSignatures(); + if (!this.signatureGroupIsRelatableToTarget(sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, context, comparisonInfoSignatuesTypeCheck)) { + if (comparisonInfo) { + var message; + if (sourceConstructSigs.length && targetConstructSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(250 /* Construct_signatures_of_types__0__and__1__are_incompatible__NL__2 */, [source.toString(), target.toString(), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(249 /* Construct_signatures_of_types__0__and__1__are_incompatible */, [source.toString(), target.toString()]); + } + } else { + var hasSig = targetConstructSigs.length ? target.toString() : source.toString(); + var lacksSig = !targetConstructSigs.length ? target.toString() : source.toString(); + message = TypeScript.getDiagnosticMessage(251 /* Type__0__requires_a_construct_signature__but_Type__1__lacks_one */, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, context, comparisonInfo) { + var targetIndexSigs = target.getIndexSignatures(); + + if (targetIndexSigs.length) { + var sourceIndexSigs = source.getIndexSignatures(); + + var targetIndex = !targetIndexSigs.length && this.cachedObjectInterfaceType() ? this.cachedObjectInterfaceType().getIndexSignatures() : targetIndexSigs; + var sourceIndex = !sourceIndexSigs.length && this.cachedObjectInterfaceType() ? this.cachedObjectInterfaceType().getIndexSignatures() : sourceIndexSigs; + + var sourceStringSig = null; + var sourceNumberSig = null; + + var targetStringSig = null; + var targetNumberSig = null; + + var params; + + for (var i = 0; i < targetIndex.length; i++) { + if (targetStringSig && targetNumberSig) { + break; + } + + params = targetIndex[i].getParameters(); + + if (params.length) { + if (!targetStringSig && params[0].getType() === this.semanticInfoChain.stringTypeSymbol) { + targetStringSig = targetIndex[i]; + continue; + } else if (!targetNumberSig && params[0].getType() === this.semanticInfoChain.numberTypeSymbol) { + targetNumberSig = targetIndex[i]; + continue; + } + } + } + + for (var i = 0; i < sourceIndex.length; i++) { + if (sourceStringSig && sourceNumberSig) { + break; + } + + params = sourceIndex[i].getParameters(); + + if (params.length) { + if (!sourceStringSig && params[0].getType() === this.semanticInfoChain.stringTypeSymbol) { + sourceStringSig = sourceIndex[i]; + continue; + } else if (!sourceNumberSig && params[0].getType() === this.semanticInfoChain.numberTypeSymbol) { + sourceNumberSig = sourceIndex[i]; + continue; + } + } + } + + var comparable = true; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeScript.TypeComparisonInfo(comparisonInfo); + } + + if (targetStringSig) { + if (sourceStringSig) { + comparable = this.signatureIsAssignableToTarget(sourceStringSig, targetStringSig, context, comparisonInfoSignatuesTypeCheck); + } else { + comparable = false; + } + } + + if (comparable && targetNumberSig) { + if (sourceNumberSig) { + comparable = this.signatureIsAssignableToTarget(sourceNumberSig, targetNumberSig, context, comparisonInfoSignatuesTypeCheck); + } else if (sourceStringSig) { + comparable = this.sourceIsAssignableToTarget(sourceStringSig.getReturnType(), targetNumberSig.getReturnType(), context, comparisonInfoSignatuesTypeCheck); + } else { + comparable = false; + } + } + + if (!comparable) { + if (comparisonInfo) { + var message; + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(253 /* Index_signatures_of_types__0__and__1__are_incompatible__NL__2 */, [source.toString(), target.toString(), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(252 /* Index_signatures_of_types__0__and__1__are_incompatible */, [source.toString(), target.toString()]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + if (targetStringSig && !source.isNamedTypeSymbol() && source.hasMembers()) { + var targetReturnType = targetStringSig.getReturnType(); + var sourceMembers = source.getMembers(); + + for (var i = 0; i < sourceMembers.length; i++) { + if (!this.sourceIsRelatableToTarget(sourceMembers[i].getType(), targetReturnType, assignableTo, comparisonCache, context, comparisonInfo)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, context, comparisonInfo) { + if (sourceSG === targetSG) { + return true; + } + + if (!(sourceSG.length && targetSG.length)) { + return false; + } + + var mSig = null; + var nSig = null; + var foundMatch = false; + + for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { + mSig = targetSG[iMSig]; + + if (mSig.isStringConstantOverloadSignature()) { + continue; + } + + for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { + nSig = sourceSG[iNSig]; + + if (nSig.isStringConstantOverloadSignature()) { + continue; + } + + if (this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, context, comparisonInfo)) { + foundMatch = true; + break; + } + } + + if (foundMatch) { + foundMatch = false; + continue; + } + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, context, comparisonInfo) { + var sourceParameters = sourceSig.getParameters(); + var targetParameters = targetSig.getParameters(); + + if (!sourceParameters || !targetParameters) { + return false; + } + + var targetVarArgCount = targetSig.getNonOptionalParameterCount(); + var sourceVarArgCount = sourceSig.getNonOptionalParameterCount(); + + if (sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableParamList()) { + if (comparisonInfo) { + comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(254 /* Call_signature_expects__0__or_fewer_parameters */, [targetVarArgCount])); + } + return false; + } + + var sourceReturnType = sourceSig.getReturnType(); + var targetReturnType = targetSig.getReturnType(); + + var prevSpecializingToObject = context.specializingToObject; + context.specializingToObject = true; + + if (targetReturnType != this.semanticInfoChain.voidTypeSymbol) { + if (!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, context, comparisonInfo)) { + if (comparisonInfo) { + comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; + } + context.specializingToObject = prevSpecializingToObject; + return false; + } + } + + var len = (sourceVarArgCount < targetVarArgCount && (sourceSig.hasVariableParamList() || (sourceParameters.length > sourceVarArgCount))) ? targetVarArgCount : sourceVarArgCount; + var sourceParamType = null; + var targetParamType = null; + var sourceParamName = ""; + var targetParamName = ""; + + for (var iSource = 0, iTarget = 0; iSource < len; iSource++, iTarget++) { + if (iSource < sourceParameters.length && (!sourceSig.hasVariableParamList() || iSource < sourceVarArgCount)) { + sourceParamType = sourceParameters[iSource].getType(); + sourceParamName = sourceParameters[iSource].getName(); + } else if (iSource === sourceVarArgCount) { + sourceParamType = sourceParameters[iSource].getType(); + if (sourceParamType.isArray()) { + sourceParamType = sourceParamType.getElementType(); + } + sourceParamName = sourceParameters[iSource].getName(); + } + + if (iTarget < targetParameters.length && iTarget < targetVarArgCount) { + targetParamType = targetParameters[iTarget].getType(); + targetParamName = targetParameters[iTarget].getName(); + } else if (targetSig.hasVariableParamList() && iTarget === targetVarArgCount) { + targetParamType = targetParameters[iTarget].getType(); + + if (targetParamType.isArray()) { + targetParamType = targetParamType.getElementType(); + } + targetParamName = targetParameters[iTarget].getName(); + } + + if (sourceParamType && sourceParamType.isTypeParameter() && this.cachedObjectInterfaceType()) { + sourceParamType = this.cachedObjectInterfaceType(); + } + if (targetParamType && targetParamType.isTypeParameter() && this.cachedObjectInterfaceType()) { + targetParamType = this.cachedObjectInterfaceType(); + } + + if (!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, context, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, context, comparisonInfo))) { + if (comparisonInfo) { + comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; + } + context.specializingToObject = prevSpecializingToObject; + return false; + } + } + context.specializingToObject = prevSpecializingToObject; + return true; + }; + + PullTypeResolver.prototype.resolveOverloads = function (application, group, enclosingDecl, haveTypeArgumentsAtCallSite, context, diagnostics) { + var rd = this.resolutionDataCache.getResolutionData(); + var actuals = rd.actuals; + var exactCandidates = rd.exactCandidates; + var conversionCandidates = rd.conversionCandidates; + var candidate = null; + var hasOverloads = group.length > 1; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var args = null; + var target = null; + + if (application.nodeType === 36 /* InvocationExpression */ || application.nodeType === 37 /* ObjectCreationExpression */) { + var callEx = application; + + args = callEx.arguments; + target = this.getLastIdentifierInTarget(callEx); + + if (callEx.arguments) { + var len = callEx.arguments.members.length; + + for (var i = 0; i < len; i++) { + var argSym = this.resolveAST(callEx.arguments.members[i], false, enclosingDecl, context).symbol; + actuals[i] = argSym.getType(); + } + } + } else if (application.nodeType === 35 /* ElementAccessExpression */) { + var binExp = application; + target = binExp.operand1; + args = new TypeScript.ASTList(); + args.members[0] = binExp.operand2; + var argSym = this.resolveAST(args.members[0], false, enclosingDecl, context).symbol; + actuals[0] = argSym.getType(); + } + + var signature; + var returnType; + var candidateInfo; + + for (var j = 0, groupLen = group.length; j < groupLen; j++) { + signature = group[j]; + if ((hasOverloads && signature.isDefinition()) || (haveTypeArgumentsAtCallSite && !signature.isGeneric())) { + continue; + } + + returnType = signature.getReturnType(); + + this.getCandidateSignatures(signature, actuals, args, exactCandidates, conversionCandidates, enclosingDecl, context, comparisonInfo); + } + if (exactCandidates.length === 0) { + var applicableCandidates = this.getApplicableSignaturesFromCandidates(conversionCandidates, args, comparisonInfo, enclosingDecl, context); + if (applicableCandidates.length > 0) { + candidateInfo = this.findMostApplicableSignature(applicableCandidates, args, enclosingDecl, context); + + candidate = candidateInfo.sig; + } else { + if (comparisonInfo.message) { + diagnostics.push(context.postError(this.unitPath, target.minChar, target.getLength(), 151 /* Supplied_parameters_do_not_match_any_signature_of_call_target__NL__0 */, [comparisonInfo.message])); + } else { + diagnostics.push(context.postError(this.unitPath, target.minChar, target.getLength(), 150 /* Supplied_parameters_do_not_match_any_signature_of_call_target */, null)); + } + } + } else { + if (exactCandidates.length > 1) { + var applicableSigs = []; + for (var i = 0; i < exactCandidates.length; i++) { + applicableSigs[i] = { signature: exactCandidates[i], hadProvisionalErrors: false }; + } + candidateInfo = this.findMostApplicableSignature(applicableSigs, args, enclosingDecl, context); + + candidate = candidateInfo.sig; + } else { + candidate = exactCandidates[0]; + } + } + + this.resolutionDataCache.returnResolutionData(rd); + return candidate; + }; + + PullTypeResolver.prototype.getLastIdentifierInTarget = function (callEx) { + return (callEx.target.nodeType === 32 /* MemberAccessExpression */) ? (callEx.target).operand2 : callEx.target; + }; + + PullTypeResolver.prototype.getCandidateSignatures = function (signature, actuals, args, exactCandidates, conversionCandidates, enclosingDecl, context, comparisonInfo) { + var parameters = signature.getParameters(); + var lowerBound = signature.getNonOptionalParameterCount(); + var upperBound = parameters.length; + var formalLen = lowerBound; + var acceptable = false; + + if ((actuals.length >= lowerBound) && (signature.hasVariableParamList() || actuals.length <= upperBound)) { + formalLen = (signature.hasVariableParamList() ? parameters.length : actuals.length); + acceptable = true; + } + + var repeatType = null; + + if (acceptable) { + if (signature.hasVariableParamList()) { + formalLen -= 1; + repeatType = parameters[formalLen].getType(); + repeatType = repeatType.getElementType(); + acceptable = actuals.length >= (formalLen < lowerBound ? formalLen : lowerBound); + } + var len = actuals.length; + + var exact = acceptable; + var convert = acceptable; + + var typeA; + var typeB; + + for (var i = 0; i < len; i++) { + if (i < formalLen) { + typeA = parameters[i].getType(); + } else { + typeA = repeatType; + } + + typeB = actuals[i]; + + if (typeA && !typeA.isResolved()) { + this.resolveDeclaredSymbol(typeA, enclosingDecl, context); + } + + if (typeB && !typeB.isResolved()) { + this.resolveDeclaredSymbol(typeB, enclosingDecl, context); + } + + if (!typeA || !typeB || !(this.typesAreIdentical(typeA, typeB, args.members[i]))) { + exact = false; + } + + comparisonInfo.stringConstantVal = args.members[i]; + + if (!this.sourceIsAssignableToTarget(typeB, typeA, context, comparisonInfo)) { + convert = false; + } + + comparisonInfo.stringConstantVal = null; + + if (!(exact || convert)) { + break; + } + } + if (exact) { + exactCandidates[exactCandidates.length] = signature; + } else if (convert && (exactCandidates.length === 0)) { + conversionCandidates[conversionCandidates.length] = signature; + } + } + }; + + PullTypeResolver.prototype.getApplicableSignaturesFromCandidates = function (candidateSignatures, args, comparisonInfo, enclosingDecl, context) { + var applicableSigs = []; + var memberType = null; + var miss = false; + var cxt = null; + var hadProvisionalErrors = false; + + var parameters; + var signature; + var argSym; + + for (var i = 0; i < candidateSignatures.length; i++) { + miss = false; + + signature = candidateSignatures[i]; + parameters = signature.getParameters(); + + for (var j = 0; j < args.members.length; j++) { + if (j >= parameters.length) { + continue; + } + + if (!parameters[j].isResolved()) { + this.resolveDeclaredSymbol(parameters[j], enclosingDecl, context); + } + + memberType = parameters[j].getType(); + + if (signature.hasVariableParamList() && (j >= signature.getNonOptionalParameterCount()) && memberType.isArray()) { + memberType = memberType.getElementType(); + } + + if (this.isAnyOrEquivalent(memberType)) { + continue; + } else if (args.members[j].nodeType === 12 /* FunctionDeclaration */) { + if (this.cachedFunctionInterfaceType() && memberType === this.cachedFunctionInterfaceType()) { + continue; + } + + argSym = this.resolveFunctionExpression(args.members[j], false, enclosingDecl, context); + + if (!this.canApplyContextualTypeToFunction(memberType, args.members[j], true)) { + if (this.canApplyContextualTypeToFunction(memberType, args.members[j], false)) { + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + break; + } + } else { + break; + } + } else { + argSym.invalidate(); + context.pushContextualType(memberType, true, null); + + argSym = this.resolveFunctionExpression(args.members[j], true, enclosingDecl, context); + + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + if (comparisonInfo) { + comparisonInfo.setMessage(TypeScript.getDiagnosticMessage(255 /* Could_not_apply_type__0__to_argument__1__which_is_of_type__2_ */, [memberType.toString(), (j + 1), argSym.getTypeName()])); + } + miss = true; + } + argSym.invalidate(); + cxt = context.popContextualType(); + hadProvisionalErrors = cxt.hadProvisionalErrors(); + + if (miss) { + break; + } + } + } else if (args.members[j].nodeType === 22 /* ObjectLiteralExpression */) { + if (this.cachedObjectInterfaceType() && memberType === this.cachedObjectInterfaceType()) { + continue; + } + + context.pushContextualType(memberType, true, null); + argSym = this.resolveObjectLiteralExpression(args.members[j], true, enclosingDecl, context).symbol; + + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + if (comparisonInfo) { + comparisonInfo.setMessage(TypeScript.getDiagnosticMessage(255 /* Could_not_apply_type__0__to_argument__1__which_is_of_type__2_ */, [memberType.toString(), (j + 1), argSym.getTypeName()])); + } + + miss = true; + } + + argSym.invalidate(); + cxt = context.popContextualType(); + hadProvisionalErrors = cxt.hadProvisionalErrors(); + + if (miss) { + break; + } + } else if (args.members[j].nodeType === 21 /* ArrayLiteralExpression */) { + if (memberType === this.cachedArrayInterfaceType()) { + continue; + } + + context.pushContextualType(memberType, true, null); + var argSym = this.resolveArrayLiteralExpression(args.members[j], true, enclosingDecl, context).symbol; + + if (!this.sourceIsAssignableToTarget(argSym.getType(), memberType, context, comparisonInfo, true)) { + if (comparisonInfo) { + comparisonInfo.setMessage(TypeScript.getDiagnosticMessage(255 /* Could_not_apply_type__0__to_argument__1__which_is_of_type__2_ */, [memberType.toString(), (j + 1), argSym.getTypeName()])); + } + break; + } + + argSym.invalidate(); + cxt = context.popContextualType(); + + hadProvisionalErrors = cxt.hadProvisionalErrors(); + + if (miss) { + break; + } + } + } + + if (j === args.members.length) { + applicableSigs[applicableSigs.length] = { signature: candidateSignatures[i], hadProvisionalErrors: hadProvisionalErrors }; + } + + hadProvisionalErrors = false; + } + + return applicableSigs; + }; + + PullTypeResolver.prototype.findMostApplicableSignature = function (signatures, args, enclosingDecl, context) { + if (signatures.length === 1) { + return { sig: signatures[0].signature, ambiguous: false }; + } + + var best = signatures[0]; + var Q = null; + + var AType = null; + var PType = null; + var QType = null; + + var ambiguous = false; + + var bestParams; + var qParams; + + for (var qSig = 1; qSig < signatures.length; qSig++) { + Q = signatures[qSig]; + + for (var i = 0; args && i < args.members.length; i++) { + var argSym = this.resolveAST(args.members[i], false, enclosingDecl, context).symbol; + + AType = argSym.getType(); + + argSym.invalidate(); + + bestParams = best.signature.getParameters(); + qParams = Q.signature.getParameters(); + + PType = i < bestParams.length ? bestParams[i].getType() : bestParams[bestParams.length - 1].getType().getElementType(); + QType = i < qParams.length ? qParams[i].getType() : qParams[qParams.length - 1].getType().getElementType(); + + if (this.typesAreIdentical(PType, QType) && !(QType.isPrimitive() && (QType).isStringConstant())) { + continue; + } else if (PType.isPrimitive() && (PType).isStringConstant() && args.members[i].nodeType === 5 /* StringLiteral */ && TypeScript.stripQuotes((args.members[i]).actualText) === TypeScript.stripQuotes((PType).getName())) { + break; + } else if (QType.isPrimitive() && (QType).isStringConstant() && args.members[i].nodeType === 5 /* StringLiteral */ && TypeScript.stripQuotes((args.members[i]).actualText) === TypeScript.stripQuotes((QType).getName())) { + best = Q; + } else if (this.typesAreIdentical(AType, PType)) { + break; + } else if (this.typesAreIdentical(AType, QType)) { + best = Q; + break; + } else if (this.sourceIsSubtypeOfTarget(PType, QType, context)) { + break; + } else if (this.sourceIsSubtypeOfTarget(QType, PType, context)) { + best = Q; + break; + } else if (Q.hadProvisionalErrors) { + break; + } else if (best.hadProvisionalErrors) { + best = Q; + break; + } + } + + if (!args || i === args.members.length) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return index ? Q.signature.getReturnType() : best.signature.getReturnType(); + } + }; + var bct = this.findBestCommonType(best.signature.getReturnType(), null, collection, context); + ambiguous = !bct; + } else { + ambiguous = false; + } + } + + return { sig: best.signature, ambiguous: ambiguous }; + }; + + PullTypeResolver.prototype.canApplyContextualTypeToFunction = function (candidateType, funcDecl, beStringent) { + if (funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation) { + return false; + } + + beStringent = beStringent || (this.cachedFunctionInterfaceType() === candidateType); + + if (!beStringent) { + return true; + } + var functionSymbol = this.getDeclForAST(funcDecl).getSymbol(); + var signature = functionSymbol.getType().getCallSignatures()[0]; + var parameters = signature.getParameters(); + var paramLen = parameters.length; + + for (var i = 0; i < paramLen; i++) { + var param = parameters[i]; + var argDecl = this.getASTForDecl(param.getDeclarations()[0]); + + if (beStringent && argDecl.typeExpr) { + return false; + } + } + + if (candidateType.getConstructSignatures().length && candidateType.getCallSignatures().length) { + return false; + } + + var candidateSigs = candidateType.getConstructSignatures().length ? candidateType.getConstructSignatures() : candidateType.getCallSignatures(); + + if (!candidateSigs || candidateSigs.length > 1) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (signature, args, comparisonInfo, enclosingDecl, context) { + var cxt = null; + var hadProvisionalErrors = false; + + var parameters = signature.getParameters(); + var typeParameters = signature.getTypeParameters(); + var argContext = new TypeScript.ArgumentInferenceContext(); + + var parameterType = null; + + for (var i = 0; i < typeParameters.length; i++) { + argContext.addInferenceRoot(typeParameters[i]); + } + + var substitutions; + var inferenceCandidates; + var inferenceCandidate; + + for (var i = 0; i < args.members.length; i++) { + if (i >= parameters.length) { + break; + } + + parameterType = parameters[i].getType(); + + if (signature.hasVariableParamList() && (i >= signature.getNonOptionalParameterCount() - 1) && parameterType.isArray()) { + parameterType = parameterType.getElementType(); + } + + inferenceCandidates = argContext.getInferenceCandidates(); + substitutions = {}; + + if (inferenceCandidates.length) { + for (var j = 0; j < inferenceCandidates.length; j++) { + argContext.resetRelationshipCache(); + + inferenceCandidate = inferenceCandidates[j]; + + substitutions = inferenceCandidates[j]; + + context.pushContextualType(parameterType, true, substitutions); + + var argSym = this.resolveAST(args.members[i], true, enclosingDecl, context).symbol; + + this.relateTypeToTypeParameters(argSym.getType(), parameterType, false, argContext, enclosingDecl, context); + + cxt = context.popContextualType(); + + argSym.invalidate(); + + hadProvisionalErrors = cxt.hadProvisionalErrors(); + } + } else { + context.pushContextualType(parameterType, true, {}); + var argSym = this.resolveAST(args.members[i], true, enclosingDecl, context).symbol; + + this.relateTypeToTypeParameters(argSym.getType(), parameterType, false, argContext, enclosingDecl, context); + + cxt = context.popContextualType(); + + argSym.invalidate(); + + hadProvisionalErrors = cxt.hadProvisionalErrors(); + } + } + + hadProvisionalErrors = false; + + var inferenceResults = argContext.inferArgumentTypes(this, context); + + if (inferenceResults.unfit) { + return null; + } + + var resultTypes = []; + + for (var i = 0; i < typeParameters.length; i++) { + for (var j = 0; j < inferenceResults.results.length; j++) { + if (inferenceResults.results[j].param == typeParameters[i]) { + resultTypes[resultTypes.length] = inferenceResults.results[j].type; + break; + } + } + } + + if (!args.members.length && !resultTypes.length && typeParameters.length) { + for (var i = 0; i < typeParameters.length; i++) { + resultTypes[resultTypes.length] = this.semanticInfoChain.anyTypeSymbol; + } + } else if (resultTypes.length && resultTypes.length < typeParameters.length) { + for (var i = resultTypes.length; i < typeParameters.length; i++) { + resultTypes[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + + return resultTypes; + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, enclosingDecl, context) { + if (!expressionType || !parameterType) { + return; + } + + if (expressionType.isError()) { + expressionType = this.semanticInfoChain.anyTypeSymbol; + } + + if (parameterType === expressionType) { + return; + } + + if (parameterType.isTypeParameter()) { + if (expressionType.isGeneric() && !expressionType.isFixed()) { + expressionType = this.specializeTypeToAny(expressionType, enclosingDecl, context); + } + argContext.addCandidateForInference(parameterType, expressionType, shouldFix); + return; + } + var parameterDeclarations = parameterType.getDeclarations(); + var expressionDeclarations = expressionType.getDeclarations(); + if (!parameterType.isArray() && parameterDeclarations.length && expressionDeclarations.length && (parameterDeclarations[0].isEqual(expressionDeclarations[0]) || (expressionType.isGeneric() && parameterType.isGeneric() && this.sourceIsSubtypeOfTarget(expressionType, parameterType, context, null))) && expressionType.isGeneric()) { + var typeParameters = parameterType.getIsSpecialized() ? parameterType.getTypeArguments() : parameterType.getTypeParameters(); + var typeArguments = expressionType.getTypeArguments(); + + if (!typeArguments) { + typeParameters = parameterType.getTypeArguments(); + typeArguments = expressionType.getIsSpecialized() ? expressionType.getTypeArguments() : expressionType.getTypeParameters(); + } + + if (typeParameters && typeArguments && typeParameters.length === typeArguments.length) { + for (var i = 0; i < typeParameters.length; i++) { + if (typeArguments[i] != typeParameters[i]) { + this.relateTypeToTypeParameters(typeArguments[i], typeParameters[i], true, argContext, enclosingDecl, context); + } + } + } + } + + var prevSpecializingToAny = context.specializingToAny; + context.specializingToAny = true; + + if (!this.sourceIsAssignableToTarget(expressionType, parameterType, context)) { + context.specializingToAny = prevSpecializingToAny; + return; + } + context.specializingToAny = prevSpecializingToAny; + + if (expressionType.isArray() && parameterType.isArray()) { + this.relateArrayTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, enclosingDecl, context); + + return; + } + + this.relateObjectTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, enclosingDecl, context); + }; + + PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, enclosingDecl, context) { + var expressionParams = expressionSignature.getParameters(); + var expressionReturnType = expressionSignature.getReturnType(); + + var parameterParams = parameterSignature.getParameters(); + var parameterReturnType = parameterSignature.getReturnType(); + + var len = parameterParams.length < expressionParams.length ? parameterParams.length : expressionParams.length; + + for (var i = 0; i < len; i++) { + this.relateTypeToTypeParameters(expressionParams[i].getType(), parameterParams[i].getType(), true, argContext, enclosingDecl, context); + } + + this.relateTypeToTypeParameters(expressionReturnType, parameterReturnType, false, argContext, enclosingDecl, context); + }; + + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, shouldFix, argContext, enclosingDecl, context) { + var parameterTypeMembers = parameterType.getMembers(); + var parameterSignatures; + var parameterSignature; + + var objectMember; + var objectSignatures; + + if (argContext.alreadyRelatingTypes(objectType, parameterType)) { + return; + } + + var objectTypeArguments = objectType.getTypeArguments(); + var parameterTypeParameters = parameterType.getTypeParameters(); + + if (objectTypeArguments && (objectTypeArguments.length === parameterTypeParameters.length)) { + for (var i = 0; i < objectTypeArguments.length; i++) { + argContext.addCandidateForInference(parameterTypeParameters[i], objectTypeArguments[i], shouldFix); + } + } + + for (var i = 0; i < parameterTypeMembers.length; i++) { + objectMember = this.getMemberSymbol(parameterTypeMembers[i].getName(), TypeScript.PullElementKind.SomeValue, objectType); + + if (objectMember) { + this.relateTypeToTypeParameters(objectMember.getType(), parameterTypeMembers[i].getType(), shouldFix, argContext, enclosingDecl, context); + } + } + + parameterSignatures = parameterType.getCallSignatures(); + objectSignatures = objectType.getCallSignatures(); + + for (var i = 0; i < parameterSignatures.length; i++) { + parameterSignature = parameterSignatures[i]; + + for (var j = 0; j < objectSignatures.length; j++) { + this.relateFunctionSignatureToTypeParameters(objectSignatures[j], parameterSignature, argContext, enclosingDecl, context); + } + } + + parameterSignatures = parameterType.getConstructSignatures(); + objectSignatures = objectType.getConstructSignatures(); + + for (var i = 0; i < parameterSignatures.length; i++) { + parameterSignature = parameterSignatures[i]; + + for (var j = 0; j < objectSignatures.length; j++) { + this.relateFunctionSignatureToTypeParameters(objectSignatures[j], parameterSignature, argContext, enclosingDecl, context); + } + } + + parameterSignatures = parameterType.getIndexSignatures(); + objectSignatures = objectType.getIndexSignatures(); + + for (var i = 0; i < parameterSignatures.length; i++) { + parameterSignature = parameterSignatures[i]; + + for (var j = 0; j < objectSignatures.length; j++) { + this.relateFunctionSignatureToTypeParameters(objectSignatures[j], parameterSignature, argContext, enclosingDecl, context); + } + } + }; + + PullTypeResolver.prototype.relateArrayTypeToTypeParameters = function (argArrayType, parameterArrayType, shouldFix, argContext, enclosingDecl, context) { + var argElement = argArrayType.getElementType(); + var paramElement = parameterArrayType.getElementType(); + + this.relateTypeToTypeParameters(argElement, paramElement, shouldFix, argContext, enclosingDecl, context); + }; + + PullTypeResolver.prototype.specializeTypeToAny = function (typeToSpecialize, enclosingDecl, context) { + var prevSpecialize = context.specializingToAny; + + context.specializingToAny = true; + + var rootType = TypeScript.getRootType(typeToSpecialize); + + var type = TypeScript.specializeType(rootType, [], this, enclosingDecl, context); + + context.specializingToAny = prevSpecialize; + + return type; + }; + + PullTypeResolver.prototype.specializeSignatureToAny = function (signatureToSpecialize, enclosingDecl, context) { + var typeParameters = signatureToSpecialize.getTypeParameters(); + var typeReplacementMap = {}; + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[i] = this.semanticInfoChain.anyTypeSymbol; + typeReplacementMap[typeParameters[i].getSymbolID().toString()] = typeArguments[i]; + } + if (!typeArguments.length) { + typeArguments[0] = this.semanticInfoChain.anyTypeSymbol; + } + + var prevSpecialize = context.specializingToAny; + + context.specializingToAny = true; + + var sig = TypeScript.specializeSignature(signatureToSpecialize, false, typeReplacementMap, typeArguments, this, enclosingDecl, context); + context.specializingToAny = prevSpecialize; + + return sig; + }; + return PullTypeResolver; + })(); + TypeScript.PullTypeResolver = PullTypeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullTypeResolver2 = (function () { + function PullTypeResolver2() { + } + return PullTypeResolver2; + })(); + TypeScript.PullTypeResolver2 = PullTypeResolver2; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TypeComparisonInfo = (function () { + function TypeComparisonInfo(sourceComparisonInfo) { + this.onlyCaptureFirstError = false; + this.flags = 0 /* SuccessfulComparison */; + this.message = ""; + this.stringConstantVal = null; + this.indent = 1; + if (sourceComparisonInfo) { + this.flags = sourceComparisonInfo.flags; + this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; + this.stringConstantVal = sourceComparisonInfo.stringConstantVal; + this.indent = sourceComparisonInfo.indent + 1; + } + } + TypeComparisonInfo.prototype.addMessage = function (message) { + if (!this.onlyCaptureFirstError && this.message) { + this.message = TypeScript.getDiagnosticMessage(2 /* _0__NL__1_TB__2 */, [this.message, this.indent, message]); + } else { + this.message = TypeScript.getDiagnosticMessage(3 /* _0_TB__1 */, [this.indent, message]); + } + }; + + TypeComparisonInfo.prototype.setMessage = function (message) { + this.message = TypeScript.getDiagnosticMessage(3 /* _0_TB__1 */, [this.indent, message]); + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + + var PullTypeCheckContext = (function () { + function PullTypeCheckContext(compiler, script, scriptName) { + this.compiler = compiler; + this.script = script; + this.scriptName = scriptName; + this.enclosingDeclStack = []; + this.enclosingDeclReturnStack = []; + this.semanticInfo = null; + this.inSuperConstructorCall = false; + this.inSuperConstructorTarget = false; + this.seenSuperConstructorCall = false; + this.inConstructorArguments = false; + this.inImportDeclaration = false; + } + PullTypeCheckContext.prototype.pushEnclosingDecl = function (decl) { + this.enclosingDeclStack[this.enclosingDeclStack.length] = decl; + this.enclosingDeclReturnStack[this.enclosingDeclReturnStack.length] = false; + }; + + PullTypeCheckContext.prototype.popEnclosingDecl = function () { + this.enclosingDeclStack.length--; + this.enclosingDeclReturnStack.length--; + }; + + PullTypeCheckContext.prototype.getEnclosingDecl = function (kind) { + if (typeof kind === "undefined") { kind = TypeScript.PullElementKind.All; } + for (var i = this.enclosingDeclStack.length - 1; i >= 0; i--) { + var decl = this.enclosingDeclStack[i]; + if (decl.getKind() & kind) { + return decl; + } + } + + return null; + }; + + PullTypeCheckContext.prototype.getEnclosingNonLambdaDecl = function () { + for (var i = this.enclosingDeclStack.length - 1; i >= 0; i--) { + var decl = this.enclosingDeclStack[i]; + if (!(decl.getKind() === 131072 /* FunctionExpression */ && (decl.getFlags() & 8192 /* FatArrow */))) { + return decl; + } + } + + return null; + }; + + PullTypeCheckContext.prototype.getEnclosingClassDecl = function () { + return this.getEnclosingDecl(8 /* Class */); + }; + + PullTypeCheckContext.prototype.getEnclosingDeclHasReturn = function () { + return this.enclosingDeclReturnStack[this.enclosingDeclReturnStack.length - 1]; + }; + + PullTypeCheckContext.prototype.setEnclosingDeclHasReturn = function () { + return this.enclosingDeclReturnStack[this.enclosingDeclReturnStack.length - 1] = true; + }; + return PullTypeCheckContext; + })(); + TypeScript.PullTypeCheckContext = PullTypeCheckContext; + + var PullTypeChecker = (function () { + function PullTypeChecker(compilationSettings, semanticInfoChain) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this.resolver = null; + this.context = new TypeScript.PullTypeResolutionContext(); + } + PullTypeChecker.prototype.setUnit = function (unitPath) { + this.resolver = new TypeScript.PullTypeResolver(this.compilationSettings, this.semanticInfoChain, unitPath); + }; + + PullTypeChecker.prototype.getScriptDecl = function (fileName) { + return this.semanticInfoChain.getUnit(fileName).getTopLevelDecls()[0]; + }; + + PullTypeChecker.prototype.checkForResolutionError = function (typeSymbol, decl) { + if (typeSymbol && typeSymbol.isError()) { + decl.addDiagnostic((typeSymbol).getDiagnostic()); + } + }; + + PullTypeChecker.prototype.postError = function (offset, length, fileName, diagnosticCode, arguments, enclosingDecl) { + enclosingDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(fileName, offset, length, diagnosticCode, arguments)); + }; + + PullTypeChecker.prototype.validateVariableDeclarationGroups = function (enclosingDecl, typeCheckContext) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + var decl; + var firstSymbol; + var symbol; + var boundDeclAST; + + for (var i = 0; i < declGroups.length; i++) { + for (var j = 0; j < declGroups[i].length; j++) { + decl = declGroups[i][j]; + symbol = decl.getSymbol(); + boundDeclAST = this.semanticInfoChain.getASTForDecl(decl); + this.resolver.resolveAST(boundDeclAST, false, enclosingDecl, this.context); + if (!j) { + firstSymbol = decl.getSymbol(); + + if (this.resolver.isAnyOrEquivalent(this.resolver.widenType(firstSymbol.getType()))) { + return; + } + continue; + } + + if (!this.resolver.typesAreIdentical(symbol.getType(), firstSymbol.getType())) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 199 /* Subsequent_variable_declarations_must_have_the_same_type___Variable__0__must_be_of_type__1___but_here_has_type___2_ */, [symbol.getDisplayName(), firstSymbol.getType().toString(), symbol.getType().toString()], enclosingDecl); + } + } + } + }; + + PullTypeChecker.prototype.typeCheckAST = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + if (!ast) { + return null; + } + + if (ast.typeCheckPhase >= PullTypeChecker.globalPullTypeCheckPhase) { + return null; + } else { + ast.typeCheckPhase = PullTypeChecker.globalPullTypeCheckPhase; + } + + switch (ast.nodeType) { + case 1 /* List */: + return this.typeCheckList(ast, typeCheckContext); + + case 17 /* VariableDeclarator */: + case 19 /* Parameter */: + return this.typeCheckBoundDecl(ast, typeCheckContext); + + case 12 /* FunctionDeclaration */: + return this.typeCheckFunction(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 13 /* ClassDeclaration */: + return this.typeCheckClass(ast, typeCheckContext); + + case 14 /* InterfaceDeclaration */: + return this.typeCheckInterface(ast, typeCheckContext); + + case 15 /* ModuleDeclaration */: + return this.typeCheckModule(ast, typeCheckContext); + + case 9 /* TypeParameter */: + return this.typeCheckTypeParameter(ast, typeCheckContext); + + case 16 /* ImportDeclaration */: + return this.typeCheckImportDeclaration(ast, typeCheckContext); + + case 38 /* AssignmentExpression */: + return this.typeCheckAssignment(ast, typeCheckContext); + + case 10 /* GenericType */: + return this.typeCheckGenericType(ast, typeCheckContext); + + case 22 /* ObjectLiteralExpression */: + return this.typeCheckObjectLiteral(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 21 /* ArrayLiteralExpression */: + return this.typeCheckArrayLiteral(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 29 /* ThisExpression */: + return this.typeCheckThisExpression(ast, typeCheckContext); + + case 30 /* SuperExpression */: + return this.typeCheckSuperExpression(ast, typeCheckContext); + + case 36 /* InvocationExpression */: + return this.typeCheckCallExpression(ast, typeCheckContext); + + case 37 /* ObjectCreationExpression */: + return this.typeCheckObjectCreationExpression(ast, typeCheckContext); + + case 78 /* CastExpression */: + return this.typeCheckTypeAssertion(ast, typeCheckContext); + + case 11 /* TypeRef */: + return this.typeCheckTypeReference(ast, typeCheckContext); + + case 87 /* ExportAssignment */: + return this.typeCheckExportAssignment(ast, typeCheckContext); + + case 57 /* NotEqualsWithTypeConversionExpression */: + case 56 /* EqualsWithTypeConversionExpression */: + case 58 /* EqualsExpression */: + case 59 /* NotEqualsExpression */: + case 60 /* LessThanExpression */: + case 61 /* LessThanOrEqualExpression */: + case 63 /* GreaterThanOrEqualExpression */: + case 62 /* GreaterThanExpression */: + return this.typeCheckLogicalOperation(ast, typeCheckContext); + + case 25 /* CommaExpression */: + return this.typeCheckCommaExpression(ast, typeCheckContext); + + case 64 /* AddExpression */: + case 39 /* AddAssignmentExpression */: + return this.typeCheckBinaryAdditionOperation(ast, typeCheckContext); + + case 65 /* SubtractExpression */: + case 66 /* MultiplyExpression */: + case 67 /* DivideExpression */: + case 68 /* ModuloExpression */: + case 53 /* BitwiseOrExpression */: + case 55 /* BitwiseAndExpression */: + case 69 /* LeftShiftExpression */: + case 70 /* SignedRightShiftExpression */: + case 71 /* UnsignedRightShiftExpression */: + case 54 /* BitwiseExclusiveOrExpression */: + case 45 /* ExclusiveOrAssignmentExpression */: + case 47 /* LeftShiftAssignmentExpression */: + case 48 /* SignedRightShiftAssignmentExpression */: + case 49 /* UnsignedRightShiftAssignmentExpression */: + case 40 /* SubtractAssignmentExpression */: + case 42 /* MultiplyAssignmentExpression */: + case 41 /* DivideAssignmentExpression */: + case 43 /* ModuloAssignmentExpression */: + case 46 /* OrAssignmentExpression */: + case 44 /* AndAssignmentExpression */: + return this.typeCheckBinaryArithmeticOperation(ast, typeCheckContext); + + case 26 /* PlusExpression */: + case 27 /* NegateExpression */: + case 72 /* BitwiseNotExpression */: + case 76 /* PostIncrementExpression */: + case 74 /* PreIncrementExpression */: + case 77 /* PostDecrementExpression */: + case 75 /* PreDecrementExpression */: + return this.typeCheckUnaryArithmeticOperation(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 35 /* ElementAccessExpression */: + return this.typeCheckElementAccessExpression(ast, typeCheckContext); + + case 73 /* LogicalNotExpression */: + return this.typeCheckLogicalNotExpression(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 51 /* LogicalOrExpression */: + case 52 /* LogicalAndExpression */: + return this.typeCheckLogicalAndOrExpression(ast, typeCheckContext); + + case 34 /* TypeOfExpression */: + return this.typeCheckTypeOf(ast, typeCheckContext); + + case 50 /* ConditionalExpression */: + return this.typeCheckConditionalExpression(ast, typeCheckContext); + + case 24 /* VoidExpression */: + return this.typeCheckVoidExpression(ast, typeCheckContext); + + case 95 /* ThrowStatement */: + return this.typeCheckThrowStatement(ast, typeCheckContext); + + case 28 /* DeleteExpression */: + return this.typeCheckDeleteExpression(ast, typeCheckContext); + + case 6 /* RegularExpressionLiteral */: + return this.typeCheckRegExpExpression(ast, typeCheckContext); + + case 31 /* InExpression */: + return this.typeCheckInExpression(ast, typeCheckContext); + + case 33 /* InstanceOfExpression */: + return this.typeCheckInstanceOfExpression(ast, typeCheckContext); + + case 79 /* ParenthesizedExpression */: + return this.typeCheckParenthesizedExpression(ast, typeCheckContext); + + case 90 /* ForStatement */: + return this.typeCheckForStatement(ast, typeCheckContext); + + case 89 /* ForInStatement */: + return this.typeCheckForInStatement(ast, typeCheckContext); + + case 98 /* WhileStatement */: + return this.typeCheckWhileStatement(ast, typeCheckContext); + + case 85 /* DoStatement */: + return this.typeCheckDoStatement(ast, typeCheckContext); + + case 91 /* IfStatement */: + return this.typeCheckIfStatement(ast, typeCheckContext); + + case 81 /* Block */: + return this.typeCheckBlock(ast, typeCheckContext); + + case 18 /* VariableDeclaration */: + return this.typeCheckVariableDeclaration(ast, typeCheckContext); + + case 97 /* VariableStatement */: + return this.typeCheckVariableStatement(ast, typeCheckContext); + + case 99 /* WithStatement */: + return this.typeCheckWithStatement(ast, typeCheckContext); + + case 96 /* TryStatement */: + return this.typeCheckTryStatement(ast, typeCheckContext); + + case 101 /* CatchClause */: + return this.typeCheckCatchClause(ast, typeCheckContext); + + case 93 /* ReturnStatement */: + return this.typeCheckReturnStatement(ast, typeCheckContext); + + case 20 /* Name */: + return this.typeCheckNameExpression(ast, typeCheckContext); + + case 32 /* MemberAccessExpression */: + return this.typeCheckMemberAccessExpression(ast, typeCheckContext); + + case 94 /* SwitchStatement */: + return this.typeCheckSwitchStatement(ast, typeCheckContext); + + case 88 /* ExpressionStatement */: + return this.typeCheckExpressionStatement(ast, typeCheckContext, inContextuallyTypedAssignment); + + case 100 /* CaseClause */: + return this.typeCheckCaseClause(ast, typeCheckContext); + + case 92 /* LabeledStatement */: + return this.typeCheckLabeledStatement(ast, typeCheckContext); + + case 7 /* NumericLiteral */: + return this.semanticInfoChain.numberTypeSymbol; + + case 5 /* StringLiteral */: + return this.semanticInfoChain.stringTypeSymbol; + + case 8 /* NullLiteral */: + return this.semanticInfoChain.nullTypeSymbol; + + case 3 /* TrueLiteral */: + case 4 /* FalseLiteral */: + return this.semanticInfoChain.booleanTypeSymbol; + + case 9 /* TypeParameter */: + return this.typeCheckTypeParameter(ast, typeCheckContext); + + default: + break; + } + + return null; + }; + + PullTypeChecker.prototype.typeCheckScript = function (script, scriptName, compiler) { + var unit = this.semanticInfoChain.getUnit(scriptName); + + if (unit.getTypeChecked()) { + return; + } + + var typeCheckContext = new PullTypeCheckContext(compiler, script, scriptName); + + this.setUnit(scriptName); + + typeCheckContext.semanticInfo = typeCheckContext.compiler.semanticInfoChain.getUnit(typeCheckContext.scriptName); + var scriptDecl = typeCheckContext.semanticInfo.getTopLevelDecls()[0]; + typeCheckContext.pushEnclosingDecl(scriptDecl); + + PullTypeChecker.globalPullTypeCheckPhase++; + + this.typeCheckAST(script.moduleElements, typeCheckContext, false); + + this.validateVariableDeclarationGroups(scriptDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + unit.setTypeChecked(); + }; + + PullTypeChecker.prototype.typeCheckList = function (list, typeCheckContext) { + if (!list) { + return null; + } + + for (var i = 0; i < list.members.length; i++) { + this.typeCheckAST(list.members[i], typeCheckContext, false); + } + }; + + PullTypeChecker.prototype.reportDiagnostics = function (symbolAndDiagnostics, enclosingDecl) { + if (symbolAndDiagnostics && symbolAndDiagnostics.diagnostics) { + for (var i = 0, n = symbolAndDiagnostics.diagnostics.length; i < n; i++) { + this.context.postDiagnostic(symbolAndDiagnostics.diagnostics[i], enclosingDecl, true); + } + } + }; + + PullTypeChecker.prototype.resolveSymbolAndReportDiagnostics = function (ast, inContextuallyTypedAssignment, enclosingDecl) { + var symbolAndDiagnostics = this.resolver.resolveAST(ast, inContextuallyTypedAssignment, enclosingDecl, this.context); + + this.reportDiagnostics(symbolAndDiagnostics, enclosingDecl); + return symbolAndDiagnostics && symbolAndDiagnostics.symbol; + }; + + PullTypeChecker.prototype.typeCheckBoundDecl = function (ast, typeCheckContext) { + var _this = this; + var boundDeclAST = ast; + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var typeExprSymbol = null; + + if (boundDeclAST.typeExpr) { + typeExprSymbol = this.typeCheckAST(boundDeclAST.typeExpr, typeCheckContext, false); + + if (typeExprSymbol.isNamedTypeSymbol() && typeExprSymbol.isGeneric() && !typeExprSymbol.isTypeParameter() && !this.resolver.isArrayOrEquivalent(typeExprSymbol) && typeExprSymbol.isResolved() && typeExprSymbol.getTypeParameters().length && typeExprSymbol.getTypeArguments() == null && !typeExprSymbol.getIsSpecialized() && this.resolver.isTypeRefWithoutTypeArgs(boundDeclAST.typeExpr)) { + this.postError(boundDeclAST.typeExpr.minChar, boundDeclAST.typeExpr.getLength(), typeCheckContext.scriptName, 239 /* Generic_type_references_must_include_all_type_arguments */, null, enclosingDecl); + typeExprSymbol = this.resolver.specializeTypeToAny(typeExprSymbol, enclosingDecl, this.context); + } + } + + if (boundDeclAST.init) { + if (typeExprSymbol) { + this.context.pushContextualType(typeExprSymbol, this.context.inProvisionalResolution(), null); + } + + var initTypeSymbol = this.typeCheckAST(boundDeclAST.init, typeCheckContext, !!typeExprSymbol); + + if (typeExprSymbol) { + this.context.popContextualType(); + } + + if (typeExprSymbol && typeExprSymbol.isContainer()) { + var exportedTypeSymbol = (typeExprSymbol).getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceTypeSymbol = (typeExprSymbol.getType()).getInstanceSymbol().getType(); + + if (!instanceTypeSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceTypeSymbol)) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 190 /* Tried_to_set_variable_type_to_module_type__0__ */, [typeExprSymbol.toString()], enclosingDecl); + typeExprSymbol = null; + } else { + typeExprSymbol = instanceTypeSymbol.getType(); + } + } + } + + if (initTypeSymbol && initTypeSymbol.isContainer()) { + instanceTypeSymbol = (initTypeSymbol.getType()).getInstanceSymbol().getType(); + + if (!instanceTypeSymbol) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 191 /* Tried_to_set_variable_type_to_uninitialized_module_type__0__ */, [initTypeSymbol.toString()], enclosingDecl); + initTypeSymbol = null; + } else { + initTypeSymbol = instanceTypeSymbol.getType(); + } + } + + if (initTypeSymbol && typeExprSymbol) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.resolver.sourceIsAssignableToTarget(initTypeSymbol, typeExprSymbol, this.context, comparisonInfo); + + if (!isAssignable) { + if (comparisonInfo.message) { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [initTypeSymbol.toString(), typeExprSymbol.toString(), comparisonInfo.message], enclosingDecl); + } else { + this.postError(boundDeclAST.minChar, boundDeclAST.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [initTypeSymbol.toString(), typeExprSymbol.toString()], enclosingDecl); + } + } + } + } + + var prevSupressErrors = this.context.suppressErrors; + this.context.suppressErrors = true; + var decl = this.resolver.getDeclForAST(boundDeclAST); + + var varTypeSymbol = this.resolveSymbolAndReportDiagnostics(boundDeclAST, false, enclosingDecl).getType(); + + if (typeExprSymbol && typeExprSymbol.isContainer() && varTypeSymbol.isError()) { + this.checkForResolutionError(varTypeSymbol, decl); + } + + this.context.suppressErrors = prevSupressErrors; + + var declSymbol = decl.getSymbol(); + + if (declSymbol.getKind() != 2048 /* Parameter */ && (declSymbol.getKind() != 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + this.checkTypePrivacy(declSymbol, varTypeSymbol, typeCheckContext, function (typeSymbol) { + return _this.variablePrivacyErrorReporter(declSymbol, typeSymbol, typeCheckContext); + }); + } + + return varTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckImportDeclaration = function (importDeclaration, typeCheckContext) { + var result = this.resolveSymbolAndReportDiagnostics(importDeclaration, false, typeCheckContext.getEnclosingDecl()); + + var savedInImportDeclaration = typeCheckContext.inImportDeclaration; + typeCheckContext.inImportDeclaration = true; + this.typeCheckAST(importDeclaration.alias, typeCheckContext, false); + typeCheckContext.inImportDeclaration = savedInImportDeclaration; + + return result; + }; + + PullTypeChecker.prototype.typeCheckFunction = function (funcDeclAST, typeCheckContext, inContextuallyTypedAssignment) { + if (funcDeclAST.isConstructor || TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 1024 /* ConstructMember */)) { + return this.typeCheckConstructor(funcDeclAST, typeCheckContext, inContextuallyTypedAssignment); + } else if (TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 4096 /* IndexerMember */)) { + return this.typeCheckIndexer(funcDeclAST, typeCheckContext, inContextuallyTypedAssignment); + } else if (funcDeclAST.isAccessor()) { + return this.typeCheckAccessor(funcDeclAST, typeCheckContext, inContextuallyTypedAssignment); + } + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var functionSymbol = this.resolveSymbolAndReportDiagnostics(funcDeclAST, inContextuallyTypedAssignment, enclosingDecl); + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.typeArguments, typeCheckContext, inContextuallyTypedAssignment); + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, inContextuallyTypedAssignment); + this.typeCheckAST(funcDeclAST.returnTypeAnnotation, typeCheckContext, false); + this.typeCheckAST(funcDeclAST.block, typeCheckContext, false); + + var hasReturn = typeCheckContext.getEnclosingDeclHasReturn(); + + this.validateVariableDeclarationGroups(functionDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + var functionSignature = functionDecl.getSignatureSymbol(); + + var parameters = functionSignature.getParameters(); + + if (parameters.length) { + for (var i = 0; i < parameters.length; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + } + + var returnType = functionSignature.getReturnType(); + + this.checkForResolutionError(returnType, enclosingDecl); + + if (funcDeclAST.block && funcDeclAST.returnTypeAnnotation != null && !hasReturn) { + var isVoidOrAny = this.resolver.isAnyOrEquivalent(returnType) || returnType === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !(funcDeclAST.block.statements.members.length > 0 && funcDeclAST.block.statements.members[0].nodeType === 95 /* ThrowStatement */)) { + var funcName = functionDecl.getDisplayName(); + funcName = funcName ? "'" + funcName + "'" : "expression"; + + this.postError(funcDeclAST.returnTypeAnnotation.minChar, funcDeclAST.returnTypeAnnotation.getLength(), typeCheckContext.scriptName, 192 /* Function__0__declared_a_non_void_return_type__but_has_no_return_expression */, [funcName], typeCheckContext.getEnclosingDecl()); + } + } + + this.typeCheckFunctionOverloads(funcDeclAST, typeCheckContext); + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + + return functionSymbol ? functionSymbol.getType() : null; + }; + + PullTypeChecker.prototype.typeCheckFunctionOverloads = function (funcDecl, typeCheckContext, signature, allSignatures) { + if (!signature) { + var functionSignatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(funcDecl, typeCheckContext.semanticInfo); + signature = functionSignatureInfo.signature; + allSignatures = functionSignatureInfo.allSignatures; + } + var functionDeclaration = typeCheckContext.semanticInfo.getDeclForAST(funcDecl); + var funcSymbol = functionDeclaration.getSymbol(); + + var definitionSignature = null; + for (var i = allSignatures.length - 1; i >= 0; i--) { + if (allSignatures[i].isDefinition()) { + definitionSignature = allSignatures[i]; + break; + } + } + + if (!signature.isDefinition()) { + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i] === signature) { + break; + } + + if (this.resolver.signaturesAreIdentical(allSignatures[i], signature)) { + if (funcDecl.isConstructor) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 210 /* Duplicate_constructor_overload_signature */, null, typeCheckContext.getEnclosingDecl()); + } else if (funcDecl.isConstructMember()) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 212 /* Duplicate_overload_construct_signature */, null, typeCheckContext.getEnclosingDecl()); + } else if (funcDecl.isCallMember()) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 211 /* Duplicate_overload_call_signature */, null, typeCheckContext.getEnclosingDecl()); + } else { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 209 /* Duplicate_overload_signature_for__0_ */, [funcSymbol.getScopedNameEx().toString()], typeCheckContext.getEnclosingDecl()); + } + + break; + } + } + } + + var isConstantOverloadSignature = signature.isStringConstantOverloadSignature(); + if (isConstantOverloadSignature) { + if (signature.isDefinition()) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 229 /* Overload_signature_implementation_cannot_use_specialized_type */, null, typeCheckContext.getEnclosingDecl()); + } else { + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var foundSubtypeSignature = false; + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i].isDefinition() || allSignatures[i] === signature) { + continue; + } + + if (!allSignatures[i].isResolved()) { + this.resolver.resolveDeclaredSymbol(allSignatures[i], typeCheckContext.getEnclosingDecl(), resolutionContext); + } + + if (allSignatures[i].isStringConstantOverloadSignature()) { + continue; + } + + if (this.resolver.signatureIsSubtypeOfTarget(signature, allSignatures[i], resolutionContext)) { + foundSubtypeSignature = true; + break; + } + } + + if (!foundSubtypeSignature) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 219 /* Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature */, null, typeCheckContext.getEnclosingDecl()); + } + } + } else if (definitionSignature && definitionSignature != signature) { + var comparisonInfo = new TypeComparisonInfo(); + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + if (!definitionSignature.isResolved()) { + this.resolver.resolveDeclaredSymbol(definitionSignature, typeCheckContext.getEnclosingDecl(), resolutionContext); + } + + if (!this.resolver.signatureIsAssignableToTarget(definitionSignature, signature, resolutionContext, comparisonInfo)) { + if (comparisonInfo.message) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 214 /* Overload_signature_is_not_compatible_with_function_definition__NL__0 */, [comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, 213 /* Overload_signature_is_not_compatible_with_function_definition */, null, typeCheckContext.getEnclosingDecl()); + } + } + } + + var signatureForVisibilityCheck = definitionSignature; + if (!definitionSignature) { + if (allSignatures[0] === signature) { + return; + } + signatureForVisibilityCheck = allSignatures[0]; + } + + if (!funcDecl.isConstructor && !funcDecl.isConstructMember() && signature != signatureForVisibilityCheck) { + var errorCode; + + if (signatureForVisibilityCheck.hasFlag(2 /* Private */) != signature.hasFlag(2 /* Private */)) { + errorCode = 215 /* Overload_signatures_must_all_be_public_or_private */; + } else if (signatureForVisibilityCheck.hasFlag(1 /* Exported */) != signature.hasFlag(1 /* Exported */)) { + errorCode = 216 /* Overload_signatures_must_all_be_exported_or_local */; + } else if (signatureForVisibilityCheck.hasFlag(8 /* Ambient */) != signature.hasFlag(8 /* Ambient */)) { + errorCode = 217 /* Overload_signatures_must_all_be_ambient_or_non_ambient */; + } else if (signatureForVisibilityCheck.hasFlag(128 /* Optional */) != signature.hasFlag(128 /* Optional */)) { + errorCode = 218 /* Overload_signatures_must_all_be_optional_or_required */; + } + + if (errorCode) { + this.postError(funcDecl.minChar, funcDecl.getLength(), typeCheckContext.scriptName, errorCode, null, typeCheckContext.getEnclosingDecl()); + } + } + }; + + PullTypeChecker.prototype.typeCheckTypeParameter = function (typeParameter, typeCheckContext) { + if (typeParameter.constraint) { + var constraintType = this.typeCheckAST(typeParameter.constraint, typeCheckContext, false); + + if (constraintType && !constraintType.isError() && constraintType.isPrimitive()) { + this.postError(typeParameter.constraint.minChar, typeParameter.constraint.getLength(), typeCheckContext.scriptName, 149 /* Type_parameter_constraint_cannot_be_a_primitive_type */, null, typeCheckContext.getEnclosingDecl()); + } + } + + return this.resolveSymbolAndReportDiagnostics(typeParameter, false, typeCheckContext.getEnclosingDecl()); + }; + + PullTypeChecker.prototype.typeCheckAccessor = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var funcDeclAST = ast; + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var accessorSymbol = this.resolveSymbolAndReportDiagnostics(ast, inContextuallyTypedAssignment, enclosingDecl); + this.checkForResolutionError(accessorSymbol.getType(), enclosingDecl); + + var isGetter = TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 32 /* GetAccessor */); + var isSetter = !isGetter; + + var getter = accessorSymbol.getGetter(); + var setter = accessorSymbol.getSetter(); + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, inContextuallyTypedAssignment); + + this.typeCheckAST(funcDeclAST.block, typeCheckContext, false); + + var hasReturn = typeCheckContext.getEnclosingDeclHasReturn(); + + this.validateVariableDeclarationGroups(functionDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + var functionSignature = functionDecl.getSignatureSymbol(); + + var parameters = functionSignature.getParameters(); + + var returnType = functionSignature.getReturnType(); + + this.checkForResolutionError(returnType, enclosingDecl); + + var funcNameAST = funcDeclAST.name; + + if (isGetter && !hasReturn) { + if (!(funcDeclAST.block.statements.members.length > 0 && funcDeclAST.block.statements.members[0].nodeType === 95 /* ThrowStatement */)) { + this.postError(funcNameAST.minChar, funcNameAST.getLength(), typeCheckContext.scriptName, 193 /* Getters_must_return_a_value */, null, typeCheckContext.getEnclosingDecl()); + } + } + + if (getter && setter) { + var getterDecl = getter.getDeclarations()[0]; + var setterDecl = setter.getDeclarations()[0]; + + var getterIsPrivate = getterDecl.getFlags() & 2 /* Private */; + var setterIsPrivate = setterDecl.getFlags() & 2 /* Private */; + + if (getterIsPrivate != setterIsPrivate) { + this.postError(funcNameAST.minChar, funcNameAST.getLength(), typeCheckContext.scriptName, 194 /* Getter_and_setter_accessors_do_not_agree_in_visibility */, null, typeCheckContext.getEnclosingDecl()); + } + } + + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + + return null; + }; + + PullTypeChecker.prototype.typeCheckConstructor = function (funcDeclAST, typeCheckContext, inContextuallyTypedAssignment) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var functionSymbol = this.resolveSymbolAndReportDiagnostics(funcDeclAST, inContextuallyTypedAssignment, enclosingDecl); + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.typeArguments, typeCheckContext, inContextuallyTypedAssignment); + + typeCheckContext.inConstructorArguments = true; + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, inContextuallyTypedAssignment); + typeCheckContext.inConstructorArguments = false; + + typeCheckContext.seenSuperConstructorCall = false; + + this.typeCheckAST(funcDeclAST.returnTypeAnnotation, typeCheckContext, false); + + this.typeCheckAST(funcDeclAST.block, typeCheckContext, false); + + this.validateVariableDeclarationGroups(functionDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + var constructorSignature = functionDecl.getSignatureSymbol(); + + var parameters = constructorSignature.getParameters(); + + if (parameters.length) { + for (var i = 0, n = parameters.length; i < n; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + } + + this.checkForResolutionError(constructorSignature.getReturnType(), enclosingDecl); + + if (functionDecl.getSignatureSymbol() && functionDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(typeCheckContext)) { + if (!typeCheckContext.seenSuperConstructorCall) { + this.postError(funcDeclAST.minChar, 11, typeCheckContext.scriptName, 173 /* Constructors_for_derived_classes_must_contain_a__super__call */, null, enclosingDecl); + } else if (this.superCallMustBeFirstStatementInConstructor(functionDecl, enclosingDecl)) { + var firstStatement = this.getFirstStatementFromFunctionDeclAST(funcDeclAST); + if (!firstStatement || !this.isSuperCallNode(firstStatement)) { + this.postError(funcDeclAST.minChar, 11, typeCheckContext.scriptName, 172 /* A__super__call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_intialized_properties_or_has_parameter_properties */, null, enclosingDecl); + } + } + } + + this.typeCheckFunctionOverloads(funcDeclAST, typeCheckContext); + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + return functionSymbol ? functionSymbol.getType() : null; + }; + + PullTypeChecker.prototype.typeCheckIndexer = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.resolver.resolveAST(ast, inContextuallyTypedAssignment, enclosingDecl, this.context); + + var funcDeclAST = ast; + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + typeCheckContext.pushEnclosingDecl(functionDecl); + + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, false); + + this.typeCheckAST(funcDeclAST.returnTypeAnnotation, typeCheckContext, false); + + typeCheckContext.popEnclosingDecl(); + + var indexSignature = functionDecl.getSignatureSymbol(); + var parameters = indexSignature.getParameters(); + + if (parameters.length) { + var parameterType = null; + + for (var i = 0; i < parameters.length; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + } + + this.checkForResolutionError(indexSignature.getReturnType(), enclosingDecl); + this.checkFunctionTypePrivacy(funcDeclAST, inContextuallyTypedAssignment, typeCheckContext); + + var isNumericIndexer = parameters[0].getType() === this.semanticInfoChain.numberTypeSymbol; + + var allIndexSignatures = enclosingDecl.getSymbol().getType().getIndexSignatures(); + for (var i = 0; i < allIndexSignatures.length; i++) { + if (!allIndexSignatures[i].isResolved()) { + this.resolver.resolveDeclaredSymbol(allIndexSignatures[i], allIndexSignatures[i].getDeclarations()[0].getParentDecl(), this.context); + } + if (allIndexSignatures[i].getParameters()[0].getType() !== parameters[0].getType()) { + var stringIndexSignature; + var numberIndexSignature; + if (isNumericIndexer) { + numberIndexSignature = indexSignature; + stringIndexSignature = allIndexSignatures[i]; + } else { + numberIndexSignature = allIndexSignatures[i]; + stringIndexSignature = indexSignature; + + if (enclosingDecl.getSymbol() === numberIndexSignature.getDeclarations()[0].getParentDecl().getSymbol()) { + break; + } + } + var comparisonInfo = new TypeComparisonInfo(); + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + if (!this.resolver.sourceIsSubtypeOfTarget(numberIndexSignature.getReturnType(), stringIndexSignature.getReturnType(), resolutionContext, comparisonInfo)) { + if (comparisonInfo.message) { + this.postError(funcDeclAST.minChar, funcDeclAST.getLength(), typeCheckContext.scriptName, 234 /* Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1____NL__2 */, [numberIndexSignature.getReturnType().toString(), stringIndexSignature.getReturnType().toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(funcDeclAST.minChar, funcDeclAST.getLength(), typeCheckContext.scriptName, 233 /* Numeric_indexer_type___0___must_be_a_subtype_of_string_indexer_type___1__ */, [numberIndexSignature.getReturnType().toString(), stringIndexSignature.getReturnType().toString()], typeCheckContext.getEnclosingDecl()); + } + } + break; + } + } + + var allMembers = enclosingDecl.getSymbol().getType().getAllMembers(TypeScript.PullElementKind.All, true); + for (var i = 0; i < allMembers.length; i++) { + var name = allMembers[i].getName(); + if (name) { + if (!allMembers[i].isResolved()) { + this.resolver.resolveDeclaredSymbol(allMembers[i], allMembers[i].getDeclarations()[0].getParentDecl(), this.context); + } + + if (enclosingDecl.getSymbol() !== allMembers[i].getContainer()) { + var isMemberNumeric = isFinite(+name); + if (isNumericIndexer === isMemberNumeric) { + this.checkThatMemberIsSubtypeOfIndexer(allMembers[i], indexSignature, funcDeclAST, typeCheckContext, isNumericIndexer); + } + } + } + } + + return null; + }; + + PullTypeChecker.prototype.typeCheckMembersAgainstIndexer = function (containerType, typeCheckContext) { + var indexSignatures = containerType.getIndexSignatures(); + if (indexSignatures.length > 0) { + var members = typeCheckContext.getEnclosingDecl().getChildDecls(); + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if (!member.getName() || member.getKind() & TypeScript.PullElementKind.SomeSignature) { + continue; + } + + var isMemberNumeric = isFinite(+member.getName()); + for (var j = 0; j < indexSignatures.length; j++) { + if (!indexSignatures[j].isResolved()) { + this.resolver.resolveDeclaredSymbol(indexSignatures[j], indexSignatures[j].getDeclarations()[0].getParentDecl(), this.context); + } + if ((indexSignatures[j].getParameters()[0].getType() === this.semanticInfoChain.numberTypeSymbol) === isMemberNumeric) { + this.checkThatMemberIsSubtypeOfIndexer(member.getSymbol(), indexSignatures[j], this.semanticInfoChain.getASTForDecl(member), typeCheckContext, isMemberNumeric); + break; + } + } + } + } + }; + + PullTypeChecker.prototype.checkThatMemberIsSubtypeOfIndexer = function (member, indexSignature, astForError, typeCheckContext, isNumeric) { + var comparisonInfo = new TypeComparisonInfo(); + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + if (!this.resolver.sourceIsSubtypeOfTarget(member.getType(), indexSignature.getReturnType(), resolutionContext, comparisonInfo)) { + if (isNumeric) { + if (comparisonInfo.message) { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 236 /* All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0____NL__1 */, [indexSignature.getReturnType().toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 235 /* All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type___0__ */, [indexSignature.getReturnType().toString()], typeCheckContext.getEnclosingDecl()); + } + } else { + if (comparisonInfo.message) { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 238 /* All_named_properties_must_be_subtypes_of_string_indexer_type___0____NL__1 */, [indexSignature.getReturnType().toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(astForError.minChar, astForError.getLength(), typeCheckContext.scriptName, 237 /* All_named_properties_must_be_subtypes_of_string_indexer_type___0__ */, [indexSignature.getReturnType().toString()], typeCheckContext.getEnclosingDecl()); + } + } + } + }; + + PullTypeChecker.prototype.typeCheckIfTypeMemberPropertyOkToOverride = function (typeSymbol, extendedType, typeMember, extendedTypeMember, comparisonInfo) { + if (!typeSymbol.isClass()) { + return true; + } + + var typeMemberKind = typeMember.getKind(); + var extendedMemberKind = extendedTypeMember.getKind(); + + if (typeMemberKind === extendedMemberKind) { + return true; + } + + var errorCode; + if (typeMemberKind === 4096 /* Property */) { + if (typeMember.isAccessor()) { + errorCode = 256 /* Class__0__defines_instance_member_accessor__1___but_extended_class__2__defines_it_as_instance_member_function */; + } else { + errorCode = 257 /* Class__0__defines_instance_member_property__1___but_extended_class__2__defines_it_as_instance_member_function */; + } + } else if (typeMemberKind === 65536 /* Method */) { + if (extendedTypeMember.isAccessor()) { + errorCode = 258 /* Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_accessor */; + } else { + errorCode = 259 /* Class__0__defines_instance_member_function__1___but_extended_class__2__defines_it_as_instance_member_property */; + } + } + + var message = TypeScript.getDiagnosticMessage(errorCode, [typeSymbol.toString(), typeMember.getScopedNameEx().toString(), extendedType.toString()]); + comparisonInfo.addMessage(message); + return false; + }; + + PullTypeChecker.prototype.typeCheckIfTypeExtendsType = function (typeDecl, typeSymbol, extendedType, typeCheckContext) { + var typeMembers = typeSymbol.getMembers(); + + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var comparisonInfo = new TypeComparisonInfo(); + var foundError = false; + + for (var i = 0; i < typeMembers.length; i++) { + var propName = typeMembers[i].getName(); + var extendedTypeProp = extendedType.findMember(propName); + if (extendedTypeProp) { + foundError = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, comparisonInfo); + + if (!foundError) { + foundError = !this.resolver.sourcePropertyIsSubtypeOfTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, resolutionContext, comparisonInfo); + } + + if (foundError) { + break; + } + } + } + + if (!foundError && typeSymbol.hasOwnCallSignatures()) { + foundError = !this.resolver.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(typeSymbol, extendedType, resolutionContext, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnConstructSignatures()) { + foundError = !this.resolver.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(typeSymbol, extendedType, resolutionContext, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnIndexSignatures()) { + foundError = !this.resolver.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(typeSymbol, extendedType, resolutionContext, comparisonInfo); + } + + if (!foundError && typeSymbol.isClass()) { + var typeConstructorType = (typeSymbol).getConstructorMethod().getType(); + var typeConstructorTypeMembers = typeConstructorType.getMembers(); + if (typeConstructorTypeMembers.length) { + var extendedConstructorType = (extendedType).getConstructorMethod().getType(); + var comparisonInfoForPropTypeCheck = new TypeComparisonInfo(comparisonInfo); + + for (var i = 0; i < typeConstructorTypeMembers.length; i++) { + var propName = typeConstructorTypeMembers[i].getName(); + var extendedConstructorTypeProp = extendedConstructorType.findMember(propName); + if (extendedConstructorTypeProp) { + if (!extendedConstructorTypeProp.isResolved()) { + var extendedClassAst = typeCheckContext.semanticInfo.getASTForSymbol(extendedType); + var extendedClassDecl = typeCheckContext.semanticInfo.getDeclForAST(extendedClassAst); + this.resolver.resolveDeclaredSymbol(extendedConstructorTypeProp, extendedClassDecl, resolutionContext); + } + + var typeConstructorTypePropType = typeConstructorTypeMembers[i].getType(); + var extendedConstructorTypePropType = extendedConstructorTypeProp.getType(); + if (!this.resolver.sourceIsSubtypeOfTarget(typeConstructorTypePropType, extendedConstructorTypePropType, resolutionContext, comparisonInfoForPropTypeCheck)) { + var propMessage; + if (comparisonInfoForPropTypeCheck.message) { + propMessage = TypeScript.getDiagnosticMessage(261 /* Types_of_static_property__0__of_class__1__and_class__2__are_incompatible__NL__3 */, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(), extendedType.toString(), comparisonInfoForPropTypeCheck.message]); + } else { + propMessage = TypeScript.getDiagnosticMessage(260 /* Types_of_static_property__0__of_class__1__and_class__2__are_incompatible */, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(), extendedType.toString()]); + } + comparisonInfo.addMessage(propMessage); + foundError = true; + break; + } + } + } + } + } + + if (foundError) { + var errorCode; + if (typeSymbol.isClass()) { + errorCode = 206 /* Class__0__cannot_extend_class__1__NL__2 */; + } else { + if (extendedType.isClass()) { + errorCode = 207 /* Interface__0__cannot_extend_class__1__NL__2 */; + } else { + errorCode = 208 /* Interface__0__cannot_extend_interface__1__NL__2 */; + } + } + + this.postError(typeDecl.name.minChar, typeDecl.name.getLength(), typeCheckContext.scriptName, errorCode, [typeSymbol.getScopedName(), extendedType.getScopedName(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } + }; + + PullTypeChecker.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, typeCheckContext) { + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var comparisonInfo = new TypeComparisonInfo(); + var foundError = !this.resolver.sourceMembersAreSubtypeOfTargetMembers(classSymbol, implementedType, resolutionContext, comparisonInfo); + if (!foundError) { + foundError = !this.resolver.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(classSymbol, implementedType, resolutionContext, comparisonInfo); + if (!foundError) { + foundError = !this.resolver.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(classSymbol, implementedType, resolutionContext, comparisonInfo); + if (!foundError) { + foundError = !this.resolver.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(classSymbol, implementedType, resolutionContext, comparisonInfo); + } + } + } + + if (foundError) { + var errorCode = implementedType.isClass() ? 203 /* Class__0__declares_class__1__but_does_not_implement_it__NL__2 */ : 202 /* Class__0__declares_interface__1__but_does_not_implement_it__NL__2 */; + + this.postError(classDecl.name.minChar, classDecl.name.getLength(), typeCheckContext.scriptName, errorCode, [classSymbol.getScopedName(), implementedType.getScopedName(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } + }; + + PullTypeChecker.prototype.typeCheckBase = function (typeDeclAst, typeSymbol, baseDeclAST, isExtendedType, typeCheckContext) { + var _this = this; + var typeDecl = typeCheckContext.semanticInfo.getDeclForAST(typeDeclAst); + var contextForBaseTypeResolution = new TypeScript.PullTypeResolutionContext(); + contextForBaseTypeResolution.isResolvingClassExtendedType = true; + + var baseType = this.typeCheckAST(new TypeScript.TypeReference(baseDeclAST, 0), typeCheckContext, false); + contextForBaseTypeResolution.isResolvingClassExtendedType = false; + + var typeDeclIsClass = typeSymbol.isClass(); + + if (!typeSymbol.isValidBaseKind(baseType, isExtendedType)) { + if (baseType.isError()) { + var error = (baseType).getDiagnostic(); + if (error) { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, error.diagnosticCode(), error.arguments(), typeCheckContext.getEnclosingDecl()); + } + } else if (isExtendedType) { + if (typeDeclIsClass) { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, 142 /* A_class_may_only_extend_another_class */, null, typeCheckContext.getEnclosingDecl()); + } else { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, 144 /* An_interface_may_only_extend_another_class_or_interface */, null, typeCheckContext.getEnclosingDecl()); + } + } else { + this.postError(baseDeclAST.minChar, baseDeclAST.getLength(), typeCheckContext.scriptName, 143 /* A_class_may_only_implement_another_class_or_interface */, null, typeCheckContext.getEnclosingDecl()); + } + return; + } + + if ((baseType.getRootSymbol()).hasBase(typeSymbol.getRootSymbol())) { + typeSymbol.setHasBaseTypeConflict(); + baseType.setHasBaseTypeConflict(); + + this.postError(typeDeclAst.name.minChar, typeDeclAst.name.getLength(), typeCheckContext.scriptName, typeDeclIsClass ? 168 /* Class__0__is_recursively_referenced_as_a_base_type_of_itself */ : 169 /* Interface__0__is_recursively_referenced_as_a_base_type_of_itself */, [typeSymbol.getScopedName()], typeCheckContext.getEnclosingDecl()); + return; + } + + if (isExtendedType) { + this.typeCheckIfTypeExtendsType(typeDeclAst, typeSymbol, baseType, typeCheckContext); + } else { + this.typeCheckIfClassImplementsType(typeDeclAst, typeSymbol, baseType, typeCheckContext); + } + + this.checkTypePrivacy(typeSymbol, baseType, typeCheckContext, function (errorTypeSymbol) { + return _this.baseListPrivacyErrorReporter(typeDeclAst, typeSymbol, baseDeclAST, isExtendedType, errorTypeSymbol, typeCheckContext); + }); + }; + + PullTypeChecker.prototype.typeCheckBases = function (typeDeclAst, typeSymbol, typeCheckContext) { + if (!typeDeclAst.extendsList && !typeDeclAst.implementsList) { + return; + } + + for (var i = 0; i < typeDeclAst.extendsList.members.length; i++) { + this.typeCheckBase(typeDeclAst, typeSymbol, typeDeclAst.extendsList.members[i], true, typeCheckContext); + } + + if (typeSymbol.isClass()) { + for (var i = 0; i < typeDeclAst.implementsList.members.length; i++) { + this.typeCheckBase(typeDeclAst, typeSymbol, typeDeclAst.implementsList.members[i], false, typeCheckContext); + } + } else if (typeDeclAst.implementsList) { + this.postError(typeDeclAst.implementsList.minChar, typeDeclAst.implementsList.getLength(), typeCheckContext.scriptName, 145 /* An_interface_cannot_implement_another_type */, null, typeCheckContext.getEnclosingDecl()); + } + }; + + PullTypeChecker.prototype.typeCheckClass = function (ast, typeCheckContext) { + var classAST = ast; + + var classSymbol = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(classSymbol, typeCheckContext.getEnclosingDecl()); + + this.typeCheckAST(classAST.typeParameters, typeCheckContext, false); + + var classDecl = typeCheckContext.semanticInfo.getDeclForAST(classAST); + typeCheckContext.pushEnclosingDecl(classDecl); + + this.typeCheckAST(classAST.typeParameters, typeCheckContext, false); + + this.typeCheckBases(classAST, classSymbol, typeCheckContext); + + this.typeCheckAST(classAST.members, typeCheckContext, false); + + if (!classSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(classSymbol, typeCheckContext); + } + + typeCheckContext.popEnclosingDecl(); + + return classSymbol; + }; + + PullTypeChecker.prototype.typeCheckInterface = function (ast, typeCheckContext) { + var interfaceAST = ast; + + var interfaceType = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(interfaceType, typeCheckContext.getEnclosingDecl()); + + var interfaceDecl = typeCheckContext.semanticInfo.getDeclForAST(interfaceAST); + typeCheckContext.pushEnclosingDecl(interfaceDecl); + + this.typeCheckAST(interfaceAST.typeParameters, typeCheckContext, false); + + this.typeCheckBases(ast, interfaceType, typeCheckContext); + + this.typeCheckAST(interfaceAST.members, typeCheckContext, false); + + if (!interfaceType.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(interfaceType, typeCheckContext); + } + + typeCheckContext.popEnclosingDecl(); + + return interfaceType; + }; + + PullTypeChecker.prototype.typeCheckModule = function (ast, typeCheckContext) { + var moduleDeclAST = ast; + var moduleType = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()); + + this.checkForResolutionError(moduleType, typeCheckContext.getEnclosingDecl()); + + var moduleDecl = typeCheckContext.semanticInfo.getDeclForAST(moduleDeclAST); + typeCheckContext.pushEnclosingDecl(moduleDecl); + + var modName = (moduleDeclAST.name).text; + var isDynamic = TypeScript.isQuoted(modName) || TypeScript.hasFlag(moduleDeclAST.getModuleFlags(), 512 /* IsDynamic */); + + if (isDynamic && moduleDeclAST.members && moduleDeclAST.members.members) { + for (var i = moduleDeclAST.members.members.length - 1; i >= 0; i--) { + if (moduleDeclAST.members.members[i] && moduleDeclAST.members.members[i].nodeType == 87 /* ExportAssignment */) { + this.typeCheckAST(moduleDeclAST.members.members[i], typeCheckContext, false); + break; + } + } + } + this.typeCheckAST(moduleDeclAST.members, typeCheckContext, false); + + this.validateVariableDeclarationGroups(moduleDecl, typeCheckContext); + + typeCheckContext.popEnclosingDecl(); + + return moduleType; + }; + + PullTypeChecker.prototype.checkAssignability = function (ast, source, target, typeCheckContext) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.resolver.sourceIsAssignableToTarget(source, target, this.context, comparisonInfo); + + if (!isAssignable) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + if (comparisonInfo.message) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [source.toString(), target.toString(), comparisonInfo.message], enclosingDecl); + } else { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [source.toString(), target.toString()], enclosingDecl); + } + } + }; + + PullTypeChecker.prototype.isValidLHS = function (ast, expressionSymbol) { + var expressionTypeSymbol = expressionSymbol.getType(); + + if (ast.nodeType === 35 /* ElementAccessExpression */ || this.resolver.isAnyOrEquivalent(expressionTypeSymbol)) { + return true; + } else if (!expressionSymbol.isType() || expressionTypeSymbol.isArray()) { + return ((expressionSymbol.getKind() & TypeScript.PullElementKind.SomeLHS) != 0) && !expressionSymbol.hasFlag(4096 /* Enum */); + } + + return false; + }; + + PullTypeChecker.prototype.typeCheckAssignment = function (binaryExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + + var leftExpr = this.resolveSymbolAndReportDiagnostics(binaryExpression.operand1, false, typeCheckContext.getEnclosingDecl()); + var leftType = leftExpr.getType(); + this.checkForResolutionError(leftType, enclosingDecl); + leftType = this.resolver.widenType(leftExpr.getType()); + + this.context.pushContextualType(leftType, this.context.inProvisionalResolution(), null); + var rightType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand2, typeCheckContext, true)); + this.context.popContextualType(); + + if (!this.isValidLHS(binaryExpression.operand1, leftExpr)) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 195 /* Invalid_left_hand_side_of_assignment_expression */, null, enclosingDecl); + } + + this.checkAssignability(binaryExpression.operand1, rightType, leftType, typeCheckContext); + return rightType; + }; + + PullTypeChecker.prototype.typeCheckGenericType = function (genericType, typeCheckContext) { + var savedResolvingTypeReference = this.context.resolvingTypeReference; + this.context.resolvingTypeReference = true; + this.typeCheckAST(genericType.name, typeCheckContext, false); + this.context.resolvingTypeReference = savedResolvingTypeReference; + + this.typeCheckAST(genericType.typeArguments, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(genericType, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckObjectLiteral = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var objectLitAST = ast; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var objectLitType = this.resolveSymbolAndReportDiagnostics(ast, inContextuallyTypedAssignment, enclosingDecl).getType(); + var memberDecls = objectLitAST.operand; + + var contextualType = this.context.getContextualType(); + var memberType; + + if (memberDecls) { + var member = null; + + for (var i = 0; i < memberDecls.members.length; i++) { + var binex = memberDecls.members[i]; + + if (contextualType) { + var text; + if (binex.operand1.nodeType === 20 /* Name */) { + text = (binex.operand1).text; + } else if (binex.operand1.nodeType === 5 /* StringLiteral */) { + text = (binex.operand1).text; + } + + member = contextualType.findMember(text); + + if (member) { + this.context.pushContextualType(member.getType(), this.context.inProvisionalResolution(), null); + } + } + + this.typeCheckAST(binex.operand2, typeCheckContext, member != null); + + if (member) { + this.context.popContextualType(); + member = null; + } + } + } + + this.checkForResolutionError(objectLitType, enclosingDecl); + + return objectLitType; + }; + + PullTypeChecker.prototype.typeCheckArrayLiteral = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + var arrayLiteralAST = ast; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var type = this.resolveSymbolAndReportDiagnostics(ast, inContextuallyTypedAssignment, enclosingDecl).getType(); + var memberASTs = arrayLiteralAST.operand; + + var contextualType = this.context.getContextualType(); + var contextualMemberType = null; + if (contextualType && contextualType.isArray()) { + contextualMemberType = contextualType.getElementType(); + } + + if (memberASTs && memberASTs.members && memberASTs.members.length) { + var elementTypes = []; + + if (contextualMemberType) { + this.context.pushContextualType(contextualMemberType, this.context.inProvisionalResolution(), null); + } + + for (var i = 0; i < memberASTs.members.length; i++) { + elementTypes[elementTypes.length] = this.typeCheckAST(memberASTs.members[i], typeCheckContext, false); + } + + if (contextualMemberType) { + this.context.popContextualType(); + } + } + + this.checkForResolutionError(type, enclosingDecl); + + return type; + }; + + PullTypeChecker.prototype.enclosingClassIsDerived = function (typeCheckContext) { + var enclosingClass = typeCheckContext.getEnclosingDecl(8 /* Class */); + + if (enclosingClass) { + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length > 0) { + return true; + } + } + + return false; + }; + + PullTypeChecker.prototype.isSuperCallNode = function (node) { + if (node && node.nodeType === 88 /* ExpressionStatement */) { + var expressionStatement = node; + if (expressionStatement.expression && expressionStatement.expression.nodeType === 36 /* InvocationExpression */) { + var callExpression = expressionStatement.expression; + if (callExpression.target && callExpression.target.nodeType === 30 /* SuperExpression */) { + return true; + } + } + } + return false; + }; + + PullTypeChecker.prototype.getFirstStatementFromFunctionDeclAST = function (funcDeclAST) { + if (funcDeclAST.block && funcDeclAST.block.statements && funcDeclAST.block.statements.members) { + return funcDeclAST.block.statements.members[0]; + } + + return null; + }; + + PullTypeChecker.prototype.superCallMustBeFirstStatementInConstructor = function (enclosingConstructor, enclosingClass) { + if (enclosingConstructor && enclosingClass) { + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length === 0) { + return false; + } + + var classMembers = classSymbol.getMembers(); + for (var i = 0, n1 = classMembers.length; i < n1; i++) { + var member = classMembers[i]; + + if (member.getKind() === 4096 /* Property */) { + var declarations = member.getDeclarations(); + for (var j = 0, n2 = declarations.length; j < n2; j++) { + var declaration = declarations[j]; + var ast = this.semanticInfoChain.getASTForDecl(declaration); + if (ast.nodeType === 19 /* Parameter */) { + return true; + } + + if (ast.nodeType === 17 /* VariableDeclarator */) { + var variableDeclarator = ast; + if (variableDeclarator.init) { + return true; + } + } + } + } + } + } + + return false; + }; + + PullTypeChecker.prototype.checkForThisOrSuperCaptureInArrowFunction = function (expression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var declPath = typeCheckContext.enclosingDeclStack; + + if (declPath.length) { + var inFatArrow = false; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.getKind(); + var declFlags = decl.getFlags(); + + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(declFlags, 8192 /* FatArrow */)) { + inFatArrow = true; + continue; + } + + if (inFatArrow) { + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + decl.setFlags(decl.getFlags() | 262144 /* MustCaptureThis */); + + if (declKind === 8 /* Class */) { + decl.getChildDecls().filter(function (d) { + return d.getKind() === 32768 /* ConstructorMethod */; + }).map(function (d) { + return d.setFlags(d.getFlags() | 262144 /* MustCaptureThis */); + }); + } + break; + } + } + } + } + }; + + PullTypeChecker.prototype.typeCheckThisExpression = function (thisExpressionAST, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var enclosingNonLambdaDecl = typeCheckContext.getEnclosingNonLambdaDecl(); + + if (typeCheckContext.inSuperConstructorCall && this.superCallMustBeFirstStatementInConstructor(typeCheckContext.getEnclosingDecl(32768 /* ConstructorMethod */), typeCheckContext.getEnclosingDecl(8 /* Class */))) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 166 /* _this__cannot_be_referenced_in_current_location */, null, enclosingDecl); + } else if (enclosingNonLambdaDecl) { + if (enclosingNonLambdaDecl.getKind() === 8 /* Class */) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 205 /* _this__cannot_be_referenced_in_initializers_in_a_class_body */, null, enclosingDecl); + } else if (enclosingNonLambdaDecl.getKind() === 4 /* Container */ || enclosingNonLambdaDecl.getKind() === 32 /* DynamicModule */) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 176 /* _this__cannot_be_referenced_within_module_bodies */, null, enclosingDecl); + } else if (typeCheckContext.inConstructorArguments) { + this.postError(thisExpressionAST.minChar, thisExpressionAST.getLength(), typeCheckContext.scriptName, 220 /* _this__cannot_be_referenced_in_constructor_arguments */, null, enclosingDecl); + } + } + + this.checkForThisOrSuperCaptureInArrowFunction(thisExpressionAST, typeCheckContext); + + return this.resolveSymbolAndReportDiagnostics(thisExpressionAST, false, enclosingDecl).getType(); + }; + + PullTypeChecker.prototype.typeCheckSuperExpression = function (ast, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var nonLambdaEnclosingDecl = typeCheckContext.getEnclosingNonLambdaDecl(); + var nonLambdaEnclosingDeclKind = nonLambdaEnclosingDecl.getKind(); + var inSuperConstructorTarget = typeCheckContext.inSuperConstructorTarget; + + if (inSuperConstructorTarget && enclosingDecl.getKind() !== 32768 /* ConstructorMethod */) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 174 /* Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors */, null, enclosingDecl); + } else if ((nonLambdaEnclosingDeclKind !== 65536 /* Method */ && nonLambdaEnclosingDeclKind !== 262144 /* GetAccessor */ && nonLambdaEnclosingDeclKind !== 524288 /* SetAccessor */ && nonLambdaEnclosingDeclKind !== 32768 /* ConstructorMethod */) || ((nonLambdaEnclosingDecl.getFlags() & 16 /* Static */) !== 0)) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 170 /* _super__property_access_is_permitted_only_in_a_constructor__instance_member_function__or_instance_member_accessor_of_a_derived_class */, null, enclosingDecl); + } else if (!this.enclosingClassIsDerived(typeCheckContext)) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 171 /* _super__cannot_be_referenced_in_non_derived_classes */, null, enclosingDecl); + } + + this.checkForThisOrSuperCaptureInArrowFunction(ast, typeCheckContext); + + return this.resolveSymbolAndReportDiagnostics(ast, false, enclosingDecl).getType(); + }; + + PullTypeChecker.prototype.typeCheckCallExpression = function (callExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var inSuperConstructorCall = (callExpression.target.nodeType === 30 /* SuperExpression */); + + var callResolutionData = new TypeScript.PullAdditionalCallResolutionData(); + var resultTypeAndDiagnostics = this.resolver.resolveCallExpression(callExpression, false, enclosingDecl, this.context, callResolutionData); + this.reportDiagnostics(resultTypeAndDiagnostics, enclosingDecl); + var resultType = resultTypeAndDiagnostics.symbol.getType(); + + this.typeCheckAST(callExpression.typeArguments, typeCheckContext, false); + + if (!resultType.isError()) { + var savedInSuperConstructorTarget = typeCheckContext.inSuperConstructorTarget; + if (inSuperConstructorCall) { + typeCheckContext.inSuperConstructorTarget = true; + } + + this.typeCheckAST(callExpression.target, typeCheckContext, false); + + typeCheckContext.inSuperConstructorTarget = savedInSuperConstructorTarget; + } + + if (inSuperConstructorCall && enclosingDecl.getKind() === 32768 /* ConstructorMethod */) { + typeCheckContext.seenSuperConstructorCall = true; + } + + var savedInSuperConstructorCall = typeCheckContext.inSuperConstructorCall; + if (inSuperConstructorCall) { + typeCheckContext.inSuperConstructorCall = true; + } + + var contextTypes = callResolutionData.actualParametersContextTypeSymbols; + if (callExpression.arguments) { + var argumentASTs = callExpression.arguments.members; + for (var i = 0, n = argumentASTs.length; i < n; i++) { + var argumentAST = argumentASTs[i]; + + if (contextTypes && contextTypes[i]) { + this.context.pushContextualType(contextTypes[i], this.context.inProvisionalResolution(), null); + } + + this.typeCheckAST(argumentAST, typeCheckContext, false); + + if (contextTypes && contextTypes[i]) { + this.context.popContextualType(); + } + } + } + + typeCheckContext.inSuperConstructorCall = savedInSuperConstructorCall; + + return resultType; + }; + + PullTypeChecker.prototype.typeCheckObjectCreationExpression = function (callExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var callResolutionData = new TypeScript.PullAdditionalCallResolutionData(); + var resultAndDiagnostics = this.resolver.resolveNewExpression(callExpression, false, enclosingDecl, this.context, callResolutionData); + this.reportDiagnostics(resultAndDiagnostics, typeCheckContext.getEnclosingDecl()); + + var result = resultAndDiagnostics.symbol.getType(); + + this.typeCheckAST(callExpression.target, typeCheckContext, false); + + this.typeCheckAST(callExpression.typeArguments, typeCheckContext, false); + + var contextTypes = callResolutionData.actualParametersContextTypeSymbols; + if (callExpression.arguments) { + var argumentASTs = callExpression.arguments.members; + for (var i = 0, n = argumentASTs.length; i < n; i++) { + var argumentAST = argumentASTs[i]; + + if (contextTypes && contextTypes[i]) { + this.context.pushContextualType(contextTypes[i], this.context.inProvisionalResolution(), null); + } + + this.typeCheckAST(argumentAST, typeCheckContext, false); + + if (contextTypes && contextTypes[i]) { + this.context.popContextualType(); + } + } + } + + return result; + }; + + PullTypeChecker.prototype.typeCheckTypeAssertion = function (ast, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var returnType = this.resolveSymbolAndReportDiagnostics(ast, false, enclosingDecl).getType(); + + if (returnType.isError()) { + var symbolName = (returnType).getData(); + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 164 /* Could_not_find_symbol__0_ */, [symbolName], typeCheckContext.getEnclosingDecl()); + } + + this.context.pushContextualType(returnType, this.context.inProvisionalResolution(), null); + var exprType = this.typeCheckAST(ast.operand, typeCheckContext, true); + this.context.popContextualType(); + + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.resolver.sourceIsAssignableToTarget(returnType, exprType, this.context, comparisonInfo) || this.resolver.sourceIsAssignableToTarget(exprType, returnType, this.context, comparisonInfo); + + if (!isAssignable) { + var message; + if (comparisonInfo.message) { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [exprType.toString(), returnType.toString(), comparisonInfo.message], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(ast.minChar, ast.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [exprType.toString(), returnType.toString()], typeCheckContext.getEnclosingDecl()); + } + } + + return returnType; + }; + + PullTypeChecker.prototype.typeCheckLogicalOperation = function (binex, typeCheckContext) { + var leftType = this.typeCheckAST(binex.operand1, typeCheckContext, false); + var rightType = this.typeCheckAST(binex.operand2, typeCheckContext, false); + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.resolver.sourceIsAssignableToTarget(leftType, rightType, this.context, comparisonInfo) && !this.resolver.sourceIsAssignableToTarget(rightType, leftType, this.context, comparisonInfo)) { + this.postError(binex.minChar, binex.getLength(), typeCheckContext.scriptName, 78 /* Operator__0__cannot_be_applied_to_types__1__and__2_ */, [TypeScript.BinaryExpression.getTextForBinaryToken(binex.nodeType), leftType.toString(), rightType.toString()], typeCheckContext.getEnclosingDecl()); + } + + return this.resolveSymbolAndReportDiagnostics(binex, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckLogicalAndOrExpression = function (binex, typeCheckContext) { + this.typeCheckAST(binex.operand1, typeCheckContext, false); + this.typeCheckAST(binex.operand2, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(binex, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckCommaExpression = function (binex, typeCheckContext) { + this.typeCheckAST(binex.operand1, typeCheckContext, false); + this.typeCheckAST(binex.operand2, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(binex, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckBinaryAdditionOperation = function (binaryExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.resolveSymbolAndReportDiagnostics(binaryExpression, false, enclosingDecl).getType(); + + var lhsType = this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + var rhsType = this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } else if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { + if (rhsType != this.semanticInfoChain.nullTypeSymbol && rhsType != this.semanticInfoChain.undefinedTypeSymbol) { + lhsType = rhsType; + } else { + lhsType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { + rhsType = this.semanticInfoChain.numberTypeSymbol; + } else if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { + if (lhsType != this.semanticInfoChain.nullTypeSymbol && lhsType != this.semanticInfoChain.undefinedTypeSymbol) { + rhsType = lhsType; + } else { + rhsType = this.semanticInfoChain.anyTypeSymbol; + } + } + + var exprType = null; + + if (lhsType === this.semanticInfoChain.stringTypeSymbol || rhsType === this.semanticInfoChain.stringTypeSymbol) { + exprType = this.semanticInfoChain.stringTypeSymbol; + } else if (this.resolver.isAnyOrEquivalent(lhsType) || this.resolver.isAnyOrEquivalent(rhsType)) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } else if (rhsType === this.semanticInfoChain.numberTypeSymbol && lhsType === this.semanticInfoChain.numberTypeSymbol) { + exprType = this.semanticInfoChain.numberTypeSymbol; + } + + if (exprType) { + if (binaryExpression.nodeType === 39 /* AddAssignmentExpression */) { + var lhsExpression = this.resolveSymbolAndReportDiagnostics(binaryExpression.operand1, false, typeCheckContext.getEnclosingDecl()); + if (!this.isValidLHS(binaryExpression.operand1, lhsExpression)) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 195 /* Invalid_left_hand_side_of_assignment_expression */, null, enclosingDecl); + } + + this.checkAssignability(binaryExpression.operand1, exprType, lhsType, typeCheckContext); + } + } else { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 178 /* Invalid__addition__expression___types_do_not_agree */, null, typeCheckContext.getEnclosingDecl()); + exprType = this.semanticInfoChain.anyTypeSymbol; + } + + return exprType; + }; + + PullTypeChecker.prototype.typeCheckBinaryArithmeticOperation = function (binaryExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + this.resolveSymbolAndReportDiagnostics(binaryExpression, false, enclosingDecl).getType(); + + var lhsType = this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + var rhsType = this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + var lhsIsFit = this.resolver.isAnyOrEquivalent(lhsType) || lhsType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(lhsType); + var rhsIsFit = this.resolver.isAnyOrEquivalent(rhsType) || rhsType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(rhsType); + + if (!rhsIsFit) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 179 /* The_right_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!lhsIsFit) { + this.postError(binaryExpression.operand2.minChar, binaryExpression.operand2.getLength(), typeCheckContext.scriptName, 180 /* The_left_hand_side_of_an_arithmetic_operation_must_be_of_type__any____number__or_an_enum_type */, null, typeCheckContext.getEnclosingDecl()); + } + + if (rhsIsFit && lhsIsFit) { + switch (binaryExpression.nodeType) { + case 47 /* LeftShiftAssignmentExpression */: + case 48 /* SignedRightShiftAssignmentExpression */: + case 49 /* UnsignedRightShiftAssignmentExpression */: + case 40 /* SubtractAssignmentExpression */: + case 42 /* MultiplyAssignmentExpression */: + case 41 /* DivideAssignmentExpression */: + case 43 /* ModuloAssignmentExpression */: + case 46 /* OrAssignmentExpression */: + case 44 /* AndAssignmentExpression */: + case 45 /* ExclusiveOrAssignmentExpression */: + var lhsExpression = this.resolveSymbolAndReportDiagnostics(binaryExpression.operand1, false, typeCheckContext.getEnclosingDecl()); + if (!this.isValidLHS(binaryExpression.operand1, lhsExpression)) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 195 /* Invalid_left_hand_side_of_assignment_expression */, null, enclosingDecl); + } + + this.checkAssignability(binaryExpression.operand1, rhsType, lhsType, typeCheckContext); + break; + } + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckLogicalNotExpression = function (unaryExpression, typeCheckContext, inContextuallyTypedAssignment) { + this.typeCheckAST(unaryExpression.operand, typeCheckContext, inContextuallyTypedAssignment); + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckUnaryArithmeticOperation = function (unaryExpression, typeCheckContext, inContextuallyTypedAssignment) { + var operandType = this.typeCheckAST(unaryExpression.operand, typeCheckContext, inContextuallyTypedAssignment); + + switch (unaryExpression.nodeType) { + case 26 /* PlusExpression */: + case 27 /* NegateExpression */: + case 72 /* BitwiseNotExpression */: + return this.semanticInfoChain.numberTypeSymbol; + } + + var operandIsFit = this.resolver.isAnyOrEquivalent(operandType) || operandType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(operandType); + + if (!operandIsFit) { + this.postError(unaryExpression.operand.minChar, unaryExpression.operand.getLength(), typeCheckContext.scriptName, 181 /* The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type__any____number__or_an_enum_type */, null, typeCheckContext.getEnclosingDecl()); + } + + switch (unaryExpression.nodeType) { + case 76 /* PostIncrementExpression */: + case 74 /* PreIncrementExpression */: + case 77 /* PostDecrementExpression */: + case 75 /* PreDecrementExpression */: + var expression = this.resolveSymbolAndReportDiagnostics(unaryExpression.operand, false, typeCheckContext.getEnclosingDecl()); + if (!this.isValidLHS(unaryExpression.operand, expression)) { + this.postError(unaryExpression.operand.minChar, unaryExpression.operand.getLength(), typeCheckContext.scriptName, 204 /* The_operand_of_an_increment_or_decrement_operator_must_be_a_variable__property_or_indexer */, null, typeCheckContext.getEnclosingDecl()); + } + + break; + } + + return operandType; + }; + + PullTypeChecker.prototype.typeCheckElementAccessExpression = function (binaryExpression, typeCheckContext) { + this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false); + this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(binaryExpression, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckTypeOf = function (ast, typeCheckContext) { + this.typeCheckAST((ast).operand, typeCheckContext, false); + + return this.semanticInfoChain.stringTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckTypeReference = function (typeRef, typeCheckContext) { + if (typeRef.term.nodeType === 12 /* FunctionDeclaration */) { + this.typeCheckFunctionTypeSignature(typeRef.term, typeCheckContext.getEnclosingDecl(), typeCheckContext); + } else if (typeRef.term.nodeType === 14 /* InterfaceDeclaration */) { + this.typeCheckInterfaceTypeReference(typeRef.term, typeCheckContext.getEnclosingDecl(), typeCheckContext); + } else { + var savedResolvingTypeReference = this.context.resolvingTypeReference; + this.context.resolvingTypeReference = true; + var type = this.typeCheckAST(typeRef.term, typeCheckContext, false); + + if (type && !type.isError() && !typeCheckContext.inImportDeclaration) { + if ((type.getKind() & TypeScript.PullElementKind.SomeType) === 0) { + if (type.getKind() & TypeScript.PullElementKind.SomeContainer) { + this.postError(typeRef.minChar, typeRef.getLength(), typeCheckContext.scriptName, 262 /* Type_reference_cannot_refer_to_container__0_ */, [type.toString()], typeCheckContext.getEnclosingDecl()); + } else { + this.postError(typeRef.minChar, typeRef.getLength(), typeCheckContext.scriptName, 263 /* Type_reference_must_refer_to_type */, null, typeCheckContext.getEnclosingDecl()); + } + } + } + + this.context.resolvingTypeReference = savedResolvingTypeReference; + } + + return this.resolveSymbolAndReportDiagnostics(typeRef, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckExportAssignment = function (ast, typeCheckContext) { + return this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckFunctionTypeSignature = function (funcDeclAST, enclosingDecl, typeCheckContext) { + var funcDeclSymbolAndDiagnostics = this.resolver.getSymbolAndDiagnosticsForAST(funcDeclAST); + var funcDeclSymbol = funcDeclSymbolAndDiagnostics && funcDeclSymbolAndDiagnostics.symbol; + if (!funcDeclSymbol) { + funcDeclSymbol = this.resolver.resolveFunctionTypeSignature(funcDeclAST, enclosingDecl, this.context); + } + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + + typeCheckContext.pushEnclosingDecl(functionDecl); + this.typeCheckAST(funcDeclAST.arguments, typeCheckContext, false); + typeCheckContext.popEnclosingDecl(); + + var functionSignature = funcDeclSymbol.getKind() === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + var parameters = functionSignature.getParameters(); + for (var i = 0; i < parameters.length; i++) { + this.checkForResolutionError(parameters[i].getType(), enclosingDecl); + } + + if (funcDeclAST.returnTypeAnnotation) { + var returnType = functionSignature.getReturnType(); + this.checkForResolutionError(returnType, enclosingDecl); + } + + this.typeCheckFunctionOverloads(funcDeclAST, typeCheckContext, functionSignature, [functionSignature]); + return funcDeclSymbol; + }; + + PullTypeChecker.prototype.typeCheckInterfaceTypeReference = function (interfaceAST, enclosingDecl, typeCheckContext) { + var interfaceSymbolAndDiagnostics = this.resolver.getSymbolAndDiagnosticsForAST(interfaceAST); + var interfaceSymbol = interfaceSymbolAndDiagnostics && interfaceSymbolAndDiagnostics.symbol; + if (!interfaceSymbol) { + interfaceSymbol = this.resolver.resolveInterfaceTypeReference(interfaceAST, enclosingDecl, this.context); + } + + var interfaceDecl = typeCheckContext.semanticInfo.getDeclForAST(interfaceAST); + typeCheckContext.pushEnclosingDecl(interfaceDecl); + this.typeCheckAST(interfaceAST.members, typeCheckContext, false); + this.typeCheckMembersAgainstIndexer(interfaceSymbol, typeCheckContext); + typeCheckContext.popEnclosingDecl(); + + return interfaceSymbol; + }; + + PullTypeChecker.prototype.typeCheckConditionalExpression = function (conditionalExpression, typeCheckContext) { + this.typeCheckAST(conditionalExpression.operand1, typeCheckContext, false); + this.typeCheckAST(conditionalExpression.operand2, typeCheckContext, false); + this.typeCheckAST(conditionalExpression.operand3, typeCheckContext, false); + + return this.resolveSymbolAndReportDiagnostics(conditionalExpression, false, typeCheckContext.getEnclosingDecl()).getType(); + }; + + PullTypeChecker.prototype.typeCheckThrowStatement = function (throwStatement, typeCheckContext) { + this.typeCheckAST(throwStatement.expression, typeCheckContext, false); + + var type = this.resolveSymbolAndReportDiagnostics(throwStatement.expression, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(type, typeCheckContext.getEnclosingDecl()); + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckDeleteExpression = function (unaryExpression, typeCheckContext) { + this.typeCheckAST(unaryExpression.operand, typeCheckContext, false); + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var type = this.resolveSymbolAndReportDiagnostics(unaryExpression, false, enclosingDecl).getType(); + this.checkForResolutionError(type, enclosingDecl); + + return type; + }; + + PullTypeChecker.prototype.typeCheckVoidExpression = function (unaryExpression, typeCheckContext) { + this.typeCheckAST(unaryExpression.operand, typeCheckContext, false); + + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var type = this.resolveSymbolAndReportDiagnostics(unaryExpression, false, enclosingDecl).getType(); + this.checkForResolutionError(type, enclosingDecl); + + return type; + }; + + PullTypeChecker.prototype.typeCheckRegExpExpression = function (ast, typeCheckContext) { + var type = this.resolveSymbolAndReportDiagnostics(ast, false, typeCheckContext.getEnclosingDecl()).getType(); + this.checkForResolutionError(type, typeCheckContext.getEnclosingDecl()); + return type; + }; + + PullTypeChecker.prototype.typeCheckForStatement = function (forStatement, typeCheckContext) { + this.typeCheckAST(forStatement.init, typeCheckContext, false); + this.typeCheckAST(forStatement.cond, typeCheckContext, false); + this.typeCheckAST(forStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckForInStatement = function (ast, typeCheckContext) { + var forInStatement = ast; + + var rhsType = this.resolver.widenType(this.typeCheckAST(forInStatement.obj, typeCheckContext, false)); + var lval = forInStatement.lval; + + if (lval.nodeType === 18 /* VariableDeclaration */) { + var declaration = forInStatement.lval; + var varDecl = declaration.declarators.members[0]; + + if (varDecl.typeExpr) { + this.postError(lval.minChar, lval.getLength(), typeCheckContext.scriptName, 182 /* Variable_declarations_for_for_in_expressions_cannot_contain_a_type_annotation */, null, typeCheckContext.getEnclosingDecl()); + } + } + + var varSym = this.resolveSymbolAndReportDiagnostics(forInStatement.lval, false, typeCheckContext.getEnclosingDecl()); + this.checkForResolutionError(varSym.getType(), typeCheckContext.getEnclosingDecl()); + + var isStringOrNumber = varSym.getType() === this.semanticInfoChain.stringTypeSymbol || this.resolver.isAnyOrEquivalent(varSym.getType()); + + var isValidRHS = rhsType && (this.resolver.isAnyOrEquivalent(rhsType) || !rhsType.isPrimitive()); + + if (!isStringOrNumber) { + this.postError(lval.minChar, lval.getLength(), typeCheckContext.scriptName, 183 /* Variable_declarations_for_for_in_expressions_must_be_of_types__string__or__any_ */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!isValidRHS) { + this.postError(forInStatement.obj.minChar, forInStatement.obj.getLength(), typeCheckContext.scriptName, 184 /* The_right_operand_of_a_for_in_expression_must_be_of_type__any____an_object_type_or_a_type_parameter */, null, typeCheckContext.getEnclosingDecl()); + } + + this.typeCheckAST(forInStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckInExpression = function (binaryExpression, typeCheckContext) { + var lhsType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false)); + var rhsType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false)); + + var isStringAnyOrNumber = lhsType.getType() === this.semanticInfoChain.stringTypeSymbol || this.resolver.isAnyOrEquivalent(lhsType.getType()) || this.resolver.isNumberOrEquivalent(lhsType.getType()); + var isValidRHS = rhsType && (this.resolver.isAnyOrEquivalent(rhsType) || !rhsType.isPrimitive()); + + if (!isStringAnyOrNumber) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 185 /* The_left_hand_side_of_an__in__expression_must_be_of_types__string__or__any_ */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!isValidRHS) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 186 /* The_right_hand_side_of_an__in__expression_must_be_of_type__any___an_object_type_or_a_type_parameter */, null, typeCheckContext.getEnclosingDecl()); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckInstanceOfExpression = function (binaryExpression, typeCheckContext) { + var lhsType = this.resolver.widenType(this.typeCheckAST(binaryExpression.operand1, typeCheckContext, false)); + var rhsType = this.typeCheckAST(binaryExpression.operand2, typeCheckContext, false); + + var isValidLHS = lhsType && (this.resolver.isAnyOrEquivalent(lhsType) || !lhsType.isPrimitive()); + var isValidRHS = rhsType && (this.resolver.isAnyOrEquivalent(rhsType) || rhsType.isClass() || this.resolver.typeIsSubtypeOfFunction(rhsType, this.context)); + + if (!isValidLHS) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 187 /* The_left_hand_side_of_an__instanceOf__expression_must_be_of_type__any___an_object_type_or_a_type_parameter */, null, typeCheckContext.getEnclosingDecl()); + } + + if (!isValidRHS) { + this.postError(binaryExpression.operand1.minChar, binaryExpression.operand1.getLength(), typeCheckContext.scriptName, 188 /* The_right_hand_side_of_an__instanceOf__expression_must_be_of_type__any__or_a_subtype_of_the__Function__interface_type */, null, typeCheckContext.getEnclosingDecl()); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckParenthesizedExpression = function (parenthesizedExpression, typeCheckContext) { + return this.typeCheckAST(parenthesizedExpression.expression, typeCheckContext, false); + }; + + PullTypeChecker.prototype.typeCheckWhileStatement = function (whileStatement, typeCheckContext) { + this.typeCheckAST(whileStatement.cond, typeCheckContext, false); + this.typeCheckAST(whileStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckDoStatement = function (doStatement, typeCheckContext) { + this.typeCheckAST(doStatement.cond, typeCheckContext, false); + this.typeCheckAST(doStatement.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckIfStatement = function (ifStatement, typeCheckContext) { + this.typeCheckAST(ifStatement.cond, typeCheckContext, false); + this.typeCheckAST(ifStatement.thenBod, typeCheckContext, false); + this.typeCheckAST(ifStatement.elseBod, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckBlock = function (block, typeCheckContext) { + this.typeCheckAST(block.statements, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckVariableDeclaration = function (variableDeclaration, typeCheckContext) { + this.typeCheckAST(variableDeclaration.declarators, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckVariableStatement = function (variableStatement, typeCheckContext) { + this.typeCheckAST(variableStatement.declaration, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckWithStatement = function (withStatement, typeCheckContext) { + this.postError(withStatement.expr.minChar, withStatement.expr.getLength(), typeCheckContext.scriptName, 200 /* All_symbols_within_a__with__block_will_be_resolved_to__any__ */, null, typeCheckContext.getEnclosingDecl()); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckTryStatement = function (tryStatement, typeCheckContext) { + this.typeCheckAST(tryStatement.tryBody, typeCheckContext, false); + this.typeCheckAST(tryStatement.catchClause, typeCheckContext, false); + this.typeCheckAST(tryStatement.finallyBody, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckCatchClause = function (catchClause, typeCheckContext) { + var catchDecl = this.resolver.getDeclForAST(catchClause); + + typeCheckContext.pushEnclosingDecl(catchDecl); + this.typeCheckAST(catchClause.body, typeCheckContext, false); + typeCheckContext.popEnclosingDecl(); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckReturnStatement = function (returnAST, typeCheckContext) { + typeCheckContext.setEnclosingDeclHasReturn(); + + var returnExpr = returnAST.returnExpression; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var inContextuallyTypedAssignment = false; + var enclosingDeclAST; + + if (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction) { + enclosingDeclAST = this.resolver.getASTForDecl(enclosingDecl); + if (enclosingDeclAST.returnTypeAnnotation) { + var returnTypeAnnotationSymbol = this.resolver.resolveTypeReference(enclosingDeclAST.returnTypeAnnotation, enclosingDecl, this.context).symbol; + if (returnTypeAnnotationSymbol) { + inContextuallyTypedAssignment = true; + this.context.pushContextualType(returnTypeAnnotationSymbol, this.context.inProvisionalResolution(), null); + } + } else { + var currentContextualType = this.context.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var currentContextualTypeSignatureSymbol = currentContextualType.getDeclarations()[0].getSignatureSymbol(); + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.getReturnType(); + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + this.context.pushContextualType(currentContextualTypeReturnTypeSymbol, this.context.inProvisionalResolution(), null); + } + } + } + } + + var returnType = this.typeCheckAST(returnExpr, typeCheckContext, inContextuallyTypedAssignment); + + if (inContextuallyTypedAssignment) { + this.context.popContextualType(); + } + + if (enclosingDecl.getKind() === 524288 /* SetAccessor */ && returnExpr) { + this.postError(returnExpr.minChar, returnExpr.getLength(), typeCheckContext.scriptName, 189 /* Setters_cannot_return_a_value */, null, typeCheckContext.getEnclosingDecl()); + } + + if (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction) { + enclosingDeclAST = this.resolver.getASTForDecl(enclosingDecl); + + if (enclosingDeclAST.returnTypeAnnotation) { + var signatureSymbol = enclosingDecl.getSignatureSymbol(); + var sigReturnType = signatureSymbol.getReturnType(); + + if (returnType && sigReturnType) { + var comparisonInfo = new TypeComparisonInfo(); + var upperBound = null; + + if (returnType.isTypeParameter()) { + upperBound = (returnType).getConstraint(); + + if (upperBound) { + returnType = upperBound; + } + } + + if (sigReturnType.isTypeParameter()) { + upperBound = (sigReturnType).getConstraint(); + + if (upperBound) { + sigReturnType = upperBound; + } + } + + if (!returnType.isResolved()) { + this.resolver.resolveDeclaredSymbol(returnType, enclosingDecl, this.context); + } + + if (!sigReturnType.isResolved()) { + this.resolver.resolveDeclaredSymbol(sigReturnType, enclosingDecl, this.context); + } + + var isAssignable = this.resolver.sourceIsAssignableToTarget(returnType, sigReturnType, this.context, comparisonInfo); + + if (!isAssignable) { + if (comparisonInfo.message) { + this.postError(returnExpr.minChar, returnExpr.getLength(), typeCheckContext.scriptName, 81 /* Cannot_convert__0__to__1__NL__2 */, [returnType.toString(), sigReturnType.toString(), comparisonInfo.message], enclosingDecl); + } else { + this.postError(returnExpr.minChar, returnExpr.getLength(), typeCheckContext.scriptName, 80 /* Cannot_convert__0__to__1_ */, [returnType.toString(), sigReturnType.toString()], enclosingDecl); + } + } + } + } + } + + return returnType; + }; + + PullTypeChecker.prototype.typeCheckNameExpression = function (ast, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var type = this.resolveSymbolAndReportDiagnostics(ast, false, enclosingDecl).getType(); + this.checkForResolutionError(type, enclosingDecl); + return type; + }; + + PullTypeChecker.prototype.checkForSuperMemberAccess = function (memberAccessExpression, typeCheckContext, resolvedName) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + if (resolvedName) { + if (memberAccessExpression.operand1.nodeType === 30 /* SuperExpression */ && !resolvedName.isError() && resolvedName.getKind() !== 65536 /* Method */) { + this.postError(memberAccessExpression.operand2.minChar, memberAccessExpression.operand2.getLength(), typeCheckContext.scriptName, 232 /* Only_public_instance_methods_of_the_base_class_are_accessible_via_the_super_keyword */, [], enclosingDecl); + return true; + } + } + + return false; + }; + + PullTypeChecker.prototype.checkForPrivateMemberAccess = function (memberAccessExpression, typeCheckContext, expressionType, resolvedName) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + if (resolvedName) { + if (resolvedName.hasFlag(2 /* Private */)) { + var memberContainer = resolvedName.getContainer(); + if (memberContainer && memberContainer.getKind() === 33554432 /* ConstructorType */) { + memberContainer = memberContainer.getAssociatedContainerType(); + } + + if (memberContainer && memberContainer.isClass()) { + var containingClass = typeCheckContext.getEnclosingClassDecl(); + if (!containingClass || containingClass.getSymbol() !== memberContainer) { + var name = memberAccessExpression.operand2; + this.postError(name.minChar, name.getLength(), typeCheckContext.scriptName, 175 /* _0_1__is_inaccessible */, [memberContainer.toString(false), name.actualText], enclosingDecl); + return true; + } + } + } + } + + return false; + }; + + PullTypeChecker.prototype.checkForStaticMemberAccess = function (memberAccessExpression, typeCheckContext, expressionType, resolvedName) { + if (expressionType && resolvedName && !resolvedName.isError()) { + if (expressionType.isClass() || expressionType.getKind() === 33554432 /* ConstructorType */) { + var name = memberAccessExpression.operand2; + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + if (resolvedName.hasFlag(16 /* Static */) || this.resolver.isPrototypeMember(memberAccessExpression, enclosingDecl, this.context)) { + if (expressionType.getKind() !== 33554432 /* ConstructorType */) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + this.postError(name.minChar, name.getLength(), typeCheckContext.scriptName, 221 /* Static_member_cannot_be_accessed_off_an_instance_variable */, null, enclosingDecl); + return true; + } + } + } + } + + return false; + }; + + PullTypeChecker.prototype.typeCheckMemberAccessExpression = function (memberAccessExpression, typeCheckContext) { + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var resolvedName = this.resolveSymbolAndReportDiagnostics(memberAccessExpression, false, enclosingDecl); + var type = resolvedName.getType(); + + this.checkForResolutionError(type, enclosingDecl); + var prevCanUseTypeSymbol = this.context.canUseTypeSymbol; + this.context.canUseTypeSymbol = true; + var expressionType = this.typeCheckAST(memberAccessExpression.operand1, typeCheckContext, false); + this.context.canUseTypeSymbol = prevCanUseTypeSymbol; + + this.checkForSuperMemberAccess(memberAccessExpression, typeCheckContext, resolvedName) || this.checkForPrivateMemberAccess(memberAccessExpression, typeCheckContext, expressionType, resolvedName) || this.checkForStaticMemberAccess(memberAccessExpression, typeCheckContext, expressionType, resolvedName); + + return type; + }; + + PullTypeChecker.prototype.typeCheckSwitchStatement = function (switchStatement, typeCheckContext) { + this.typeCheckAST(switchStatement.val, typeCheckContext, false); + this.typeCheckAST(switchStatement.caseList, typeCheckContext, false); + this.typeCheckAST(switchStatement.defaultCase, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckExpressionStatement = function (ast, typeCheckContext, inContextuallyTypedAssignment) { + return this.typeCheckAST(ast.expression, typeCheckContext, inContextuallyTypedAssignment); + }; + + PullTypeChecker.prototype.typeCheckCaseClause = function (caseClause, typeCheckContext) { + this.typeCheckAST(caseClause.expr, typeCheckContext, false); + this.typeCheckAST(caseClause.body, typeCheckContext, false); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeChecker.prototype.typeCheckLabeledStatement = function (labeledStatement, typeCheckContext) { + return this.typeCheckAST(labeledStatement.statement, typeCheckContext, false); + }; + + PullTypeChecker.prototype.checkTypePrivacy = function (declSymbol, typeSymbol, typeCheckContext, privacyErrorReporter) { + if (!typeSymbol || typeSymbol.getKind() === 2 /* Primitive */) { + return; + } + + if (typeSymbol.isArray()) { + this.checkTypePrivacy(declSymbol, (typeSymbol).getElementType(), typeCheckContext, privacyErrorReporter); + return; + } + + if (!typeSymbol.isNamedTypeSymbol()) { + var members = typeSymbol.getMembers(); + for (var i = 0; i < members.length; i++) { + this.checkTypePrivacy(declSymbol, members[i].getType(), typeCheckContext, privacyErrorReporter); + } + + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), typeCheckContext, privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), typeCheckContext, privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), typeCheckContext, privacyErrorReporter); + + return; + } + + if (declSymbol.isExternallyVisible()) { + var typeSymbolIsVisible = typeSymbol.isExternallyVisible(); + + if (typeSymbolIsVisible) { + var typeSymbolPath = typeSymbol.pathToRoot(); + if (typeSymbolPath.length && typeSymbolPath[typeSymbolPath.length - 1].getKind() === 32 /* DynamicModule */) { + var declSymbolPath = declSymbol.pathToRoot(); + if (declSymbolPath.length && declSymbolPath[declSymbolPath.length - 1] != typeSymbolPath[typeSymbolPath.length - 1]) { + typeSymbolIsVisible = false; + for (var i = typeSymbolPath.length - 1; i >= 0; i--) { + var aliasSymbol = typeSymbolPath[i].getAliasedSymbol(declSymbol); + if (aliasSymbol) { + TypeScript.CompilerDiagnostics.assert(aliasSymbol.getKind() === 256 /* TypeAlias */, "dynamic module need to be referenced by type alias"); + (aliasSymbol).setIsTypeUsedExternally(); + typeSymbolIsVisible = true; + break; + } + } + } + } + } + + if (!typeSymbolIsVisible) { + privacyErrorReporter(typeSymbol); + } + } + }; + + PullTypeChecker.prototype.checkTypePrivacyOfSignatures = function (declSymbol, signatures, typeCheckContext, privacyErrorReporter) { + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (signatures.length && signature.isDefinition()) { + continue; + } + + var typeParams = signature.getTypeParameters(); + for (var j = 0; j < typeParams.length; j++) { + this.checkTypePrivacy(declSymbol, typeParams[j], typeCheckContext, privacyErrorReporter); + } + + var params = signature.getParameters(); + for (var j = 0; j < params.length; j++) { + var paramType = params[j].getType(); + this.checkTypePrivacy(declSymbol, paramType, typeCheckContext, privacyErrorReporter); + } + + var returnType = signature.getReturnType(); + this.checkTypePrivacy(declSymbol, returnType, typeCheckContext, privacyErrorReporter); + } + }; + + PullTypeChecker.prototype.baseListPrivacyErrorReporter = function (declAST, declSymbol, baseAst, isExtendedType, typeSymbol, typeCheckContext) { + var decl = this.resolver.getDeclForAST(declAST); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + var messageCode; + var messageArguments; + + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (declAST.nodeType === 13 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = 90 /* Exported_class__0__extends_class_from_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 91 /* Exported_class__0__implements_interface_from_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 92 /* Exported_interface__0__extends_interface_from_inaccessible_module__1_ */; + messageArguments = [declSymbol.getDisplayName(), typeSymbolName]; + } + } else { + if (declAST.nodeType === 13 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = 87 /* Exported_class__0__extends_private_class__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 88 /* Exported_class__0__implements_private_interface__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 89 /* Exported_interface__0__extends_private_interface__1_ */; + messageArguments = [declSymbol.getDisplayName(), typeSymbolName]; + } + } + + this.context.postError(typeCheckContext.scriptName, baseAst.minChar, baseAst.getLength(), messageCode, messageArguments, enclosingDecl, true); + }; + + PullTypeChecker.prototype.variablePrivacyErrorReporter = function (declSymbol, typeSymbol, typeCheckContext) { + var declAST = this.resolver.getASTForSymbol(declSymbol); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var isProperty = declSymbol.getKind() === 4096 /* Property */; + var isPropertyOfClass = false; + var declParent = declSymbol.getContainer(); + if (declParent && (declParent.getKind() === 8 /* Class */ || declParent.getKind() === 32768 /* ConstructorMethod */)) { + isPropertyOfClass = true; + } + + var messageCode; + var messageArguments; + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declSymbol.hasFlag(16 /* Static */)) { + messageCode = 97 /* Public_static_property__0__of__exported_class_is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = 98 /* Public_property__0__of__exported_class_is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 99 /* Property__0__of__exported_interface_is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 100 /* Exported_variable__0__is_using_inaccessible_module__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + if (declSymbol.hasFlag(16 /* Static */)) { + messageCode = 93 /* Public_static_property__0__of__exported_class_has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = 94 /* Public_property__0__of__exported_class_has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } else { + messageCode = 95 /* Property__0__of__exported_interface_has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } else { + messageCode = 96 /* Exported_variable__0__has_or_is_using_private_type__1_ */; + messageArguments = [declSymbol.getScopedName(), typeSymbolName]; + } + } + + this.context.postError(typeCheckContext.scriptName, declAST.minChar, declAST.getLength(), messageCode, messageArguments, enclosingDecl, true); + }; + + PullTypeChecker.prototype.checkFunctionTypePrivacy = function (funcDeclAST, inContextuallyTypedAssignment, typeCheckContext) { + var _this = this; + if (inContextuallyTypedAssignment || (funcDeclAST.getFunctionFlags() & 8192 /* IsFunctionExpression */) || (funcDeclAST.getFunctionFlags() & 16384 /* IsFunctionProperty */)) { + return; + } + + var functionDecl = typeCheckContext.semanticInfo.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + ; + var functionSignature; + + var isGetter = funcDeclAST.isGetAccessor(); + var isSetter = funcDeclAST.isSetAccessor(); + + if (isGetter || isSetter) { + var accessorSymbol = functionSymbol; + functionSignature = (isGetter ? accessorSymbol.getGetter() : accessorSymbol.getSetter()).getType().getCallSignatures()[0]; + } else { + if (!functionSymbol) { + var parentDecl = functionDecl.getParentDecl(); + functionSymbol = parentDecl.getSymbol(); + if (functionSymbol && functionSymbol.isType() && !(functionSymbol).isNamedTypeSymbol()) { + return; + } + } else if (functionSymbol.getKind() == 65536 /* Method */ && !functionSymbol.getContainer().isNamedTypeSymbol()) { + return; + } + functionSignature = functionDecl.getSignatureSymbol(); + } + + if (!isGetter) { + var funcParams = functionSignature.getParameters(); + for (var i = 0; i < funcParams.length; i++) { + this.checkTypePrivacy(functionSymbol, funcParams[i].getType(), typeCheckContext, function (typeSymbol) { + return _this.functionArgumentTypePrivacyErrorReporter(funcDeclAST, i, funcParams[i], typeSymbol, typeCheckContext); + }); + } + } + + if (!isSetter) { + this.checkTypePrivacy(functionSymbol, functionSignature.getReturnType(), typeCheckContext, function (typeSymbol) { + return _this.functionReturnTypePrivacyErrorReporter(funcDeclAST, functionSignature.getReturnType(), typeSymbol, typeCheckContext); + }); + } + }; + + PullTypeChecker.prototype.functionArgumentTypePrivacyErrorReporter = function (declAST, argIndex, paramSymbol, typeSymbol, typeCheckContext) { + var decl = this.resolver.getDeclForAST(declAST); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var isGetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 32 /* GetAccessor */); + var isSetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 64 /* SetAccessor */); + var isStatic = (decl.getFlags() & 16 /* Static */) === 16 /* Static */; + var isMethod = decl.getKind() === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.getKind() === 8 /* Class */ || declParent.getKind() === 32768 /* ConstructorMethod */)) { + isMethodOfClass = true; + } + + var start = declAST.arguments.members[argIndex].minChar; + var length = declAST.arguments.members[argIndex].getLength(); + + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declAST.isConstructor) { + this.context.postError(typeCheckContext.scriptName, start, length, 110 /* Parameter__0__of_constructor_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isSetter) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 111 /* Parameter__0__of_public_static_property_setter_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 112 /* Parameter__0__of_public_property_setter_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (declAST.isConstructMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 113 /* Parameter__0__of_constructor_signature_from_exported_interface_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (declAST.isCallMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 114 /* Parameter__0__of_call_signature_from_exported_interface_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethod) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 115 /* Parameter__0__of_public_static_method_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethodOfClass) { + this.context.postError(typeCheckContext.scriptName, start, length, 116 /* Parameter__0__of_public_method_from_exported_class_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 117 /* Parameter__0__of_method_from_exported_interface_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (!isGetter) { + this.context.postError(typeCheckContext.scriptName, start, length, 118 /* Parameter__0__of_exported_function_is_using_inaccessible_module__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else { + if (declAST.isConstructor) { + this.context.postError(typeCheckContext.scriptName, start, length, 101 /* Parameter__0__of_constructor_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isSetter) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 102 /* Parameter__0__of_public_static_property_setter_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 103 /* Parameter__0__of_public_property_setter_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (declAST.isConstructMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 104 /* Parameter__0__of_constructor_signature_from_exported_interface_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (declAST.isCallMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 105 /* Parameter__0__of_call_signature_from_exported_interface_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethod) { + if (isStatic) { + this.context.postError(typeCheckContext.scriptName, start, length, 106 /* Parameter__0__of_public_static_method_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else if (isMethodOfClass) { + this.context.postError(typeCheckContext.scriptName, start, length, 107 /* Parameter__0__of_public_method_from_exported_class_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } else { + this.context.postError(typeCheckContext.scriptName, start, length, 108 /* Parameter__0__of_method_from_exported_interface_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } else if (!isGetter && !declAST.isIndexerMember()) { + this.context.postError(typeCheckContext.scriptName, start, length, 109 /* Parameter__0__of_exported_function_has_or_is_using_private_type__1_ */, [paramSymbol.getScopedName(), typeSymbolName], enclosingDecl, true); + } + } + }; + + PullTypeChecker.prototype.functionReturnTypePrivacyErrorReporter = function (declAST, funcReturnType, typeSymbol, typeCheckContext) { + var _this = this; + var decl = this.resolver.getDeclForAST(declAST); + var enclosingDecl = typeCheckContext.getEnclosingDecl(); + + var isGetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 32 /* GetAccessor */); + var isSetter = declAST.isAccessor() && TypeScript.hasFlag(declAST.getFunctionFlags(), 64 /* SetAccessor */); + var isStatic = (decl.getFlags() & 16 /* Static */) === 16 /* Static */; + var isMethod = decl.getKind() === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.getKind() === 8 /* Class */ || declParent.getKind() === 32768 /* ConstructorMethod */)) { + isMethodOfClass = true; + } + + var messageCode = null; + var messageArguments; + var typeSymbolName = typeSymbol.getScopedName(); + if (typeSymbol.isContainer()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (isGetter) { + if (isStatic) { + messageCode = 128 /* Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 129 /* Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (declAST.isConstructMember()) { + messageCode = 130 /* Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isCallMember()) { + messageCode = 131 /* Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isIndexerMember()) { + messageCode = 132 /* Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethod) { + if (isStatic) { + messageCode = 133 /* Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethodOfClass) { + messageCode = 134 /* Return_type_of_public_method_from_exported_class_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 135 /* Return_type_of_method_from_exported_interface_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (!isSetter && !declAST.isConstructor) { + messageCode = 136 /* Return_type_of_exported_function_is_using_inaccessible_module__0_ */; + messageArguments = [typeSymbolName]; + } + } else { + if (isGetter) { + if (isStatic) { + messageCode = 119 /* Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 120 /* Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (declAST.isConstructMember()) { + messageCode = 121 /* Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isCallMember()) { + messageCode = 122 /* Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (declAST.isIndexerMember()) { + messageCode = 123 /* Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethod) { + if (isStatic) { + messageCode = 124 /* Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else if (isMethodOfClass) { + messageCode = 125 /* Return_type_of_public_method_from_exported_class_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } else { + messageCode = 126 /* Return_type_of_method_from_exported_interface_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } + } else if (!isSetter && !declAST.isConstructor) { + messageCode = 127 /* Return_type_of_exported_function_has_or_is_using_private_type__0_ */; + messageArguments = [typeSymbolName]; + } + } + + if (messageCode) { + var reportOnFuncDecl = false; + var contextForReturnTypeResolution = new TypeScript.PullTypeResolutionContext(); + if (declAST.returnTypeAnnotation) { + var returnExpressionSymbolAndDiagnostics = this.resolver.resolveTypeReference(declAST.returnTypeAnnotation, decl, contextForReturnTypeResolution); + var returnExpressionSymbol = returnExpressionSymbolAndDiagnostics && returnExpressionSymbolAndDiagnostics.symbol; + if (returnExpressionSymbol === funcReturnType) { + this.context.postError(typeCheckContext.scriptName, declAST.returnTypeAnnotation.minChar, declAST.returnTypeAnnotation.getLength(), messageCode, messageArguments, enclosingDecl, true); + } + } + + if (declAST.block) { + var reportErrorOnReturnExpressions = function (ast, parent, walker) { + var go = true; + switch (ast.nodeType) { + case 12 /* FunctionDeclaration */: + go = false; + break; + + case 93 /* ReturnStatement */: + var returnStatement = ast; + var returnExpressionSymbol = _this.resolver.resolveAST(returnStatement.returnExpression, false, decl, contextForReturnTypeResolution).symbol.getType(); + + if (returnExpressionSymbol === funcReturnType) { + _this.context.postError(typeCheckContext.scriptName, returnStatement.minChar, returnStatement.getLength(), messageCode, messageArguments, enclosingDecl, true); + } else { + reportOnFuncDecl = true; + } + go = false; + break; + + default: + break; + } + + walker.options.goChildren = go; + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(declAST.block, reportErrorOnReturnExpressions); + } + + if (reportOnFuncDecl) { + this.context.postError(typeCheckContext.scriptName, declAST.minChar, declAST.getLength(), messageCode, messageArguments, enclosingDecl, true); + } + } + }; + PullTypeChecker.globalPullTypeCheckPhase = 0; + return PullTypeChecker; + })(); + TypeScript.PullTypeChecker = PullTypeChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullDeclEdit) { + PullDeclEdit[PullDeclEdit["NoChanges"] = 0] = "NoChanges"; + PullDeclEdit[PullDeclEdit["DeclAdded"] = 1] = "DeclAdded"; + PullDeclEdit[PullDeclEdit["DeclRemoved"] = 2] = "DeclRemoved"; + PullDeclEdit[PullDeclEdit["DeclChanged"] = 3] = "DeclChanged"; + })(TypeScript.PullDeclEdit || (TypeScript.PullDeclEdit = {})); + var PullDeclEdit = TypeScript.PullDeclEdit; + + var PullDeclDiff = (function () { + function PullDeclDiff(oldDecl, newDecl, kind) { + this.oldDecl = oldDecl; + this.newDecl = newDecl; + this.kind = kind; + } + return PullDeclDiff; + })(); + TypeScript.PullDeclDiff = PullDeclDiff; + + var PullDeclDiffer = (function () { + function PullDeclDiffer(oldSemanticInfo, newSemanticInfo) { + this.oldSemanticInfo = oldSemanticInfo; + this.newSemanticInfo = newSemanticInfo; + this.differences = []; + } + PullDeclDiffer.diffDecls = function (oldDecl, oldSemanticInfo, newDecl, newSemanticInfo) { + var declDiffer = new PullDeclDiffer(oldSemanticInfo, newSemanticInfo); + declDiffer.diff(oldDecl, newDecl); + return declDiffer.differences; + }; + + PullDeclDiffer.prototype.diff = function (oldDecl, newDecl) { + TypeScript.Debug.assert(oldDecl.getName() === newDecl.getName()); + TypeScript.Debug.assert(oldDecl.getKind() === newDecl.getKind()); + + var oldAST = this.oldSemanticInfo.getASTForDecl(oldDecl); + var newAST = this.newSemanticInfo.getASTForDecl(newDecl); + TypeScript.Debug.assert(oldAST !== undefined); + TypeScript.Debug.assert(newAST !== undefined); + + if (oldAST === newAST) { + return; + } + + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclTypeCache, newDecl.childDeclTypeCache); + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclTypeParameterCache, newDecl.childDeclTypeParameterCache); + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclValueCache, newDecl.childDeclValueCache); + this.diff1(oldDecl, newDecl, oldAST, newAST, oldDecl.childDeclNamespaceCache, newDecl.childDeclNamespaceCache); + + if (!this.isEquivalent(oldAST, newAST)) { + this.differences.push(new PullDeclDiff(oldDecl, newDecl, 3 /* DeclChanged */)); + } + }; + + PullDeclDiffer.prototype.diff1 = function (oldDecl, newDecl, oldAST, newAST, oldNameToDecls, newNameToDecls) { + var oldChildrenOfName; + var newChildrenOfName; + var oldChild; + var newChild; + + for (var name in oldNameToDecls) { + oldChildrenOfName = oldNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + newChildrenOfName = newNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + + for (var i = 0, n = oldChildrenOfName.length; i < n; i++) { + oldChild = oldChildrenOfName[i]; + + switch (oldChild.getKind()) { + case 131072 /* FunctionExpression */: + case 512 /* ObjectLiteral */: + case 8388608 /* ObjectType */: + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + continue; + } + + if (i < newChildrenOfName.length) { + newChild = newChildrenOfName[i]; + + if (oldChild.getKind() === newChild.getKind()) { + this.diff(oldChild, newChildrenOfName[i]); + } else { + this.differences.push(new PullDeclDiff(oldChild, null, 2 /* DeclRemoved */)); + this.differences.push(new PullDeclDiff(oldDecl, newChild, 1 /* DeclAdded */)); + } + } else { + this.differences.push(new PullDeclDiff(oldChild, null, 2 /* DeclRemoved */)); + } + } + } + + for (var name in newNameToDecls) { + oldChildrenOfName = oldNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + newChildrenOfName = newNameToDecls[name] || PullDeclDiffer.emptyDeclArray; + + for (var i = oldChildrenOfName.length, n = newChildrenOfName.length; i < n; i++) { + newChild = newChildrenOfName[i]; + this.differences.push(new PullDeclDiff(oldDecl, newChild, 1 /* DeclAdded */)); + } + } + }; + + PullDeclDiffer.prototype.isEquivalent = function (oldAST, newAST) { + TypeScript.Debug.assert(oldAST !== null); + TypeScript.Debug.assert(newAST !== null); + TypeScript.Debug.assert(oldAST !== newAST); + + if (oldAST.nodeType !== newAST.nodeType || oldAST.getFlags() !== newAST.getFlags()) { + return false; + } + + switch (oldAST.nodeType) { + case 16 /* ImportDeclaration */: + return this.importDeclarationIsEquivalent(oldAST, newAST); + case 15 /* ModuleDeclaration */: + return this.moduleDeclarationIsEquivalent(oldAST, newAST); + case 13 /* ClassDeclaration */: + return this.classDeclarationIsEquivalent(oldAST, newAST); + case 14 /* InterfaceDeclaration */: + return this.interfaceDeclarationIsEquivalent(oldAST, newAST); + case 19 /* Parameter */: + return this.argumentDeclarationIsEquivalent(oldAST, newAST); + case 17 /* VariableDeclarator */: + return this.variableDeclarationIsEquivalent(oldAST, newAST); + case 9 /* TypeParameter */: + return this.typeParameterIsEquivalent(oldAST, newAST); + case 12 /* FunctionDeclaration */: + return this.functionDeclarationIsEquivalent(oldAST, newAST); + case 101 /* CatchClause */: + return this.catchClauseIsEquivalent(oldAST, newAST); + case 99 /* WithStatement */: + return this.withStatementIsEquivalent(oldAST, newAST); + case 2 /* Script */: + return this.scriptIsEquivalent(oldAST, newAST); + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PullDeclDiffer.prototype.importDeclarationIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.alias, decl2.alias); + }; + + PullDeclDiffer.prototype.typeDeclarationIsEquivalent = function (decl1, decl2) { + return decl1.getVarFlags() === decl2.getVarFlags() && TypeScript.structuralEqualsNotIncludingPosition(decl1.typeParameters, decl2.typeParameters) && TypeScript.structuralEqualsNotIncludingPosition(decl1.extendsList, decl2.extendsList) && TypeScript.structuralEqualsNotIncludingPosition(decl1.implementsList, decl2.implementsList); + }; + + PullDeclDiffer.prototype.classDeclarationIsEquivalent = function (decl1, decl2) { + return this.typeDeclarationIsEquivalent(decl1, decl2); + }; + + PullDeclDiffer.prototype.interfaceDeclarationIsEquivalent = function (decl1, decl2) { + return this.typeDeclarationIsEquivalent(decl1, decl2); + }; + + PullDeclDiffer.prototype.typeParameterIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.constraint, decl2.constraint); + }; + + PullDeclDiffer.prototype.boundDeclarationIsEquivalent = function (decl1, decl2) { + if (decl1.getVarFlags() === decl2.getVarFlags() && TypeScript.structuralEqualsNotIncludingPosition(decl1.typeExpr, decl2.typeExpr)) { + if (decl1.typeExpr === null) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.init, decl2.init); + } else { + return true; + } + } + + return false; + }; + + PullDeclDiffer.prototype.argumentDeclarationIsEquivalent = function (decl1, decl2) { + return this.boundDeclarationIsEquivalent(decl1, decl2) && decl1.isOptional === decl2.isOptional; + }; + + PullDeclDiffer.prototype.variableDeclarationIsEquivalent = function (decl1, decl2) { + return this.boundDeclarationIsEquivalent(decl1, decl2); + }; + + PullDeclDiffer.prototype.functionDeclarationIsEquivalent = function (decl1, decl2) { + if (decl1.hint === decl2.hint && decl1.getFunctionFlags() === decl2.getFunctionFlags() && decl1.variableArgList === decl2.variableArgList && decl1.isConstructor === decl2.isConstructor && TypeScript.structuralEqualsNotIncludingPosition(decl1.returnTypeAnnotation, decl2.returnTypeAnnotation) && TypeScript.structuralEqualsNotIncludingPosition(decl1.typeArguments, decl2.typeArguments) && TypeScript.structuralEqualsNotIncludingPosition(decl1.arguments, decl2.arguments)) { + if (decl1.returnTypeAnnotation === null) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.block, decl2.block); + } else { + return true; + } + } + + return false; + }; + + PullDeclDiffer.prototype.catchClauseIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.param, decl2.param) && TypeScript.structuralEqualsNotIncludingPosition(decl1.body, decl2.body); + }; + + PullDeclDiffer.prototype.withStatementIsEquivalent = function (decl1, decl2) { + return TypeScript.structuralEqualsNotIncludingPosition(decl1.expr, decl2.expr) && TypeScript.structuralEqualsNotIncludingPosition(decl1.body, decl2.body); + }; + + PullDeclDiffer.prototype.scriptIsEquivalent = function (decl1, decl2) { + return true; + }; + + PullDeclDiffer.prototype.moduleDeclarationIsEquivalent = function (decl1, decl2) { + return decl1.getModuleFlags() === decl2.getModuleFlags() && decl2.prettyName === decl2.prettyName && TypeScript.ArrayUtilities.sequenceEquals(decl1.amdDependencies, decl2.amdDependencies, TypeScript.StringUtilities.stringEquals); + }; + PullDeclDiffer.emptyDeclArray = []; + return PullDeclDiffer; + })(); + TypeScript.PullDeclDiffer = PullDeclDiffer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.declCacheHit = 0; + TypeScript.declCacheMiss = 0; + TypeScript.symbolCacheHit = 0; + TypeScript.symbolCacheMiss = 0; + + var SemanticInfo = (function () { + function SemanticInfo(compilationUnitPath) { + this.topLevelDecls = []; + this.topLevelSynthesizedDecls = []; + this.astDeclMap = new TypeScript.DataMap(); + this.declASTMap = new TypeScript.DataMap(); + this.syntaxElementDeclMap = new TypeScript.DataMap(); + this.declSyntaxElementMap = new TypeScript.DataMap(); + this.astSymbolMap = new TypeScript.DataMap(); + this.symbolASTMap = new TypeScript.DataMap(); + this.syntaxElementSymbolMap = new TypeScript.DataMap(); + this.symbolSyntaxElementMap = new TypeScript.DataMap(); + this.properties = new SemanticInfoProperties(); + this.hasBeenTypeChecked = false; + this.compilationUnitPath = compilationUnitPath; + } + SemanticInfo.prototype.addTopLevelDecl = function (decl) { + this.topLevelDecls[this.topLevelDecls.length] = decl; + }; + + SemanticInfo.prototype.setTypeChecked = function () { + this.hasBeenTypeChecked = true; + }; + SemanticInfo.prototype.getTypeChecked = function () { + return this.hasBeenTypeChecked; + }; + SemanticInfo.prototype.invalidate = function () { + this.astSymbolMap = new TypeScript.DataMap(); + this.symbolASTMap = new TypeScript.DataMap(); + }; + + SemanticInfo.prototype.getTopLevelDecls = function () { + return this.topLevelDecls; + }; + + SemanticInfo.prototype.getPath = function () { + return this.compilationUnitPath; + }; + + SemanticInfo.prototype.addSynthesizedDecl = function (decl) { + this.topLevelSynthesizedDecls[this.topLevelSynthesizedDecls.length] = decl; + }; + SemanticInfo.prototype.getSynthesizedDecls = function () { + return this.topLevelSynthesizedDecls; + }; + + SemanticInfo.prototype.getDeclForAST = function (ast) { + return this.astDeclMap.read(ast.getID().toString()); + }; + + SemanticInfo.prototype.setDeclForAST = function (ast, decl) { + this.astDeclMap.link(ast.getID().toString(), decl); + }; + + SemanticInfo.prototype.getDeclKey = function (decl) { + var decl1 = decl; + + if (!decl1.__declKey) { + decl1.__declKey = decl.getDeclID().toString() + "-" + decl.getKind().toString(); + } + + return decl1.__declKey; + }; + + SemanticInfo.prototype.getASTForDecl = function (decl) { + return this.declASTMap.read(this.getDeclKey(decl)); + }; + + SemanticInfo.prototype.setASTForDecl = function (decl, ast) { + this.declASTMap.link(this.getDeclKey(decl), ast); + }; + + SemanticInfo.prototype.setSymbolAndDiagnosticsForAST = function (ast, symbolAndDiagnostics) { + this.astSymbolMap.link(ast.getID().toString(), symbolAndDiagnostics); + this.symbolASTMap.link(symbolAndDiagnostics.symbol.getSymbolID().toString(), ast); + }; + + SemanticInfo.prototype.getSymbolAndDiagnosticsForAST = function (ast) { + return this.astSymbolMap.read(ast.getID().toString()); + }; + + SemanticInfo.prototype.getASTForSymbol = function (symbol) { + return this.symbolASTMap.read(symbol.getSymbolID().toString()); + }; + + SemanticInfo.prototype.getSyntaxElementForDecl = function (decl) { + return this.declSyntaxElementMap.read(this.getDeclKey(decl)); + }; + + SemanticInfo.prototype.setSyntaxElementForDecl = function (decl, syntaxElement) { + this.declSyntaxElementMap.link(this.getDeclKey(decl), syntaxElement); + }; + + SemanticInfo.prototype.getDeclForSyntaxElement = function (syntaxElement) { + return this.syntaxElementDeclMap.read(TypeScript.Collections.identityHashCode(syntaxElement).toString()); + }; + + SemanticInfo.prototype.setDeclForSyntaxElement = function (syntaxElement, decl) { + this.syntaxElementDeclMap.link(TypeScript.Collections.identityHashCode(syntaxElement).toString(), decl); + }; + + SemanticInfo.prototype.getSyntaxElementForSymbol = function (symbol) { + return this.symbolSyntaxElementMap.read(symbol.getSymbolID().toString()); + }; + + SemanticInfo.prototype.getSymbolForSyntaxElement = function (syntaxElement) { + return this.syntaxElementSymbolMap.read(TypeScript.Collections.identityHashCode(syntaxElement).toString()); + }; + + SemanticInfo.prototype.setSymbolForSyntaxElement = function (syntaxElement, symbol) { + this.syntaxElementSymbolMap.link(TypeScript.Collections.identityHashCode(syntaxElement).toString(), symbol); + this.symbolSyntaxElementMap.link(symbol.getSymbolID().toString(), syntaxElement); + }; + + SemanticInfo.prototype.getDiagnostics = function (semanticErrors) { + for (var i = 0; i < this.topLevelDecls.length; i++) { + TypeScript.getDiagnosticsFromEnclosingDecl(this.topLevelDecls[i], semanticErrors); + } + }; + + SemanticInfo.prototype.getProperties = function () { + return this.properties; + }; + return SemanticInfo; + })(); + TypeScript.SemanticInfo = SemanticInfo; + + var SemanticInfoProperties = (function () { + function SemanticInfoProperties() { + this.unitContainsBool = false; + } + return SemanticInfoProperties; + })(); + TypeScript.SemanticInfoProperties = SemanticInfoProperties; + + var SemanticInfoChain = (function () { + function SemanticInfoChain() { + this.units = [new SemanticInfo("")]; + this.declCache = new TypeScript.BlockIntrinsics(); + this.symbolCache = new TypeScript.BlockIntrinsics(); + this.unitCache = new TypeScript.BlockIntrinsics(); + this.declSymbolMap = new TypeScript.DataMap(); + this.anyTypeSymbol = null; + this.booleanTypeSymbol = null; + this.numberTypeSymbol = null; + this.stringTypeSymbol = null; + this.nullTypeSymbol = null; + this.undefinedTypeSymbol = null; + this.elementTypeSymbol = null; + this.voidTypeSymbol = null; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this; + } + + var globalDecl = this.getGlobalDecl(); + var globalInfo = this.units[0]; + globalInfo.addTopLevelDecl(globalDecl); + } + SemanticInfoChain.prototype.addPrimitiveType = function (name, globalDecl) { + var span = new TypeScript.TextSpan(0, 0); + var decl = new TypeScript.PullDecl(name, name, 2 /* Primitive */, 0 /* None */, span, ""); + var symbol = new TypeScript.PullPrimitiveTypeSymbol(name); + + symbol.addDeclaration(decl); + decl.setSymbol(symbol); + + symbol.setResolved(); + + if (globalDecl) { + globalDecl.addChildDecl(decl); + } + + return symbol; + }; + + SemanticInfoChain.prototype.addPrimitiveValue = function (name, type, globalDecl) { + var span = new TypeScript.TextSpan(0, 0); + var decl = new TypeScript.PullDecl(name, name, 1024 /* Variable */, 8 /* Ambient */, span, ""); + var symbol = new TypeScript.PullSymbol(name, 1024 /* Variable */); + + symbol.addDeclaration(decl); + decl.setSymbol(symbol); + symbol.setType(type); + symbol.setResolved(); + + globalDecl.addChildDecl(decl); + }; + + SemanticInfoChain.prototype.getGlobalDecl = function () { + var span = new TypeScript.TextSpan(0, 0); + var globalDecl = new TypeScript.PullDecl("", "", 0 /* Global */, 0 /* None */, span, ""); + + this.anyTypeSymbol = this.addPrimitiveType("any", globalDecl); + this.booleanTypeSymbol = this.addPrimitiveType("boolean", globalDecl); + this.numberTypeSymbol = this.addPrimitiveType("number", globalDecl); + this.stringTypeSymbol = this.addPrimitiveType("string", globalDecl); + this.voidTypeSymbol = this.addPrimitiveType("void", globalDecl); + this.elementTypeSymbol = this.addPrimitiveType("_element", globalDecl); + + this.nullTypeSymbol = this.addPrimitiveType("null", null); + this.undefinedTypeSymbol = this.addPrimitiveType("undefined", null); + this.addPrimitiveValue("undefined", this.undefinedTypeSymbol, globalDecl); + this.addPrimitiveValue("null", this.nullTypeSymbol, globalDecl); + + return globalDecl; + }; + + SemanticInfoChain.prototype.addUnit = function (unit) { + this.units[this.units.length] = unit; + this.unitCache[unit.getPath()] = unit; + }; + + SemanticInfoChain.prototype.getUnit = function (compilationUnitPath) { + for (var i = 0; i < this.units.length; i++) { + if (this.units[i].getPath() === compilationUnitPath) { + return this.units[i]; + } + } + + return null; + }; + + SemanticInfoChain.prototype.updateUnit = function (oldUnit, newUnit) { + for (var i = 0; i < this.units.length; i++) { + if (this.units[i].getPath() === oldUnit.getPath()) { + this.units[i] = newUnit; + this.unitCache[oldUnit.getPath()] = newUnit; + return; + } + } + }; + + SemanticInfoChain.prototype.collectAllTopLevelDecls = function () { + var decls = []; + var unitDecls; + + for (var i = 0; i < this.units.length; i++) { + unitDecls = this.units[i].getTopLevelDecls(); + for (var j = 0; j < unitDecls.length; j++) { + decls[decls.length] = unitDecls[j]; + } + } + + return decls; + }; + + SemanticInfoChain.prototype.collectAllSynthesizedDecls = function () { + var decls = []; + var synthDecls; + + for (var i = 0; i < this.units.length; i++) { + synthDecls = this.units[i].getSynthesizedDecls(); + for (var j = 0; j < synthDecls.length; j++) { + decls[decls.length] = synthDecls[j]; + } + } + + return decls; + }; + + SemanticInfoChain.prototype.getDeclPathCacheID = function (declPath, declKind) { + var cacheID = ""; + + for (var i = 0; i < declPath.length; i++) { + cacheID += "#" + declPath[i]; + } + + return cacheID + "#" + declKind.toString(); + }; + + SemanticInfoChain.prototype.findDecls = function (declPath, declKind) { + var cacheID = this.getDeclPathCacheID(declPath, declKind); + + if (declPath.length) { + var cachedDecls = this.declCache[cacheID]; + + if (cachedDecls && cachedDecls.length) { + TypeScript.declCacheHit++; + return cachedDecls; + } + } + + TypeScript.declCacheMiss++; + + var declsToSearch = this.collectAllTopLevelDecls(); + + var decls = []; + var path; + var foundDecls = []; + var keepSearching = (declKind & 4 /* Container */) || (declKind & 16 /* Interface */); + + for (var i = 0; i < declPath.length; i++) { + path = declPath[i]; + decls = []; + + for (var j = 0; j < declsToSearch.length; j++) { + foundDecls = declsToSearch[j].searchChildDecls(path, declKind); + + for (var k = 0; k < foundDecls.length; k++) { + decls[decls.length] = foundDecls[k]; + } + + if (foundDecls.length && !keepSearching) { + break; + } + } + + declsToSearch = decls; + + if (!declsToSearch) { + break; + } + } + + if (decls.length) { + this.declCache[cacheID] = decls; + } + + return decls; + }; + + SemanticInfoChain.prototype.findSymbol = function (declPath, declType) { + var cacheID = this.getDeclPathCacheID(declPath, declType); + + if (declPath.length) { + var cachedSymbol = this.symbolCache[cacheID]; + + if (cachedSymbol) { + TypeScript.symbolCacheHit++; + return cachedSymbol; + } + } + + TypeScript.symbolCacheMiss++; + + var decls = this.findDecls(declPath, declType); + var symbol = null; + + if (decls.length) { + symbol = decls[0].getSymbol(); + + if (symbol) { + this.symbolCache[cacheID] = symbol; + + symbol.addCacheID(cacheID); + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.cacheGlobalSymbol = function (symbol, kind) { + var cacheID1 = this.getDeclPathCacheID([symbol.getName()], kind); + var cacheID2 = this.getDeclPathCacheID([symbol.getName()], symbol.getKind()); + + if (!this.symbolCache[cacheID1]) { + this.symbolCache[cacheID1] = symbol; + symbol.addCacheID(cacheID1); + } + + if (!this.symbolCache[cacheID2]) { + this.symbolCache[cacheID2] = symbol; + symbol.addCacheID(cacheID2); + } + }; + + SemanticInfoChain.prototype.cleanDecl = function (decl) { + decl.setSymbol(null); + decl.setSignatureSymbol(null); + decl.setSpecializingSignatureSymbol(null); + decl.setIsBound(false); + + var children = decl.getChildDecls(); + + for (var i = 0; i < children.length; i++) { + this.cleanDecl(children[i]); + } + + var typeParameters = decl.getTypeParameters(); + + for (var i = 0; i < typeParameters.length; i++) { + this.cleanDecl(typeParameters[i]); + } + + var valueDecl = decl.getValueDecl(); + + if (valueDecl) { + this.cleanDecl(valueDecl); + } + }; + + SemanticInfoChain.prototype.cleanAllDecls = function () { + var topLevelDecls = this.collectAllTopLevelDecls(); + + for (var i = 1; i < topLevelDecls.length; i++) { + this.cleanDecl(topLevelDecls[i]); + } + + var synthesizedDecls = this.collectAllSynthesizedDecls(); + + for (var i = 0; i < synthesizedDecls.length; i++) { + this.cleanDecl(synthesizedDecls[i]); + } + }; + + SemanticInfoChain.prototype.update = function () { + this.declCache = new TypeScript.BlockIntrinsics(); + this.symbolCache = new TypeScript.BlockIntrinsics(); + this.units[0] = new SemanticInfo(""); + this.units[0].addTopLevelDecl(this.getGlobalDecl()); + this.cleanAllDecls(); + + for (var unit in this.unitCache) { + if (this.unitCache[unit]) { + this.unitCache[unit].invalidate(); + } + } + }; + + SemanticInfoChain.prototype.invalidateUnit = function (compilationUnitPath) { + var unit = this.unitCache[compilationUnitPath]; + if (unit) { + unit.invalidate(); + } + }; + + SemanticInfoChain.prototype.getDeclForAST = function (ast, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + return unit.getDeclForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getASTForDecl = function (decl) { + var unit = this.unitCache[decl.getScriptName()]; + + if (unit) { + return unit.getASTForDecl(decl); + } + + return null; + }; + + SemanticInfoChain.prototype.getSymbolAndDiagnosticsForAST = function (ast, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + return unit.getSymbolAndDiagnosticsForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getASTForSymbol = function (symbol, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + return unit.getASTForSymbol(symbol); + } + + return null; + }; + + SemanticInfoChain.prototype.setSymbolAndDiagnosticsForAST = function (ast, symbolAndDiagnostics, unitPath) { + var unit = this.unitCache[unitPath]; + + if (unit) { + unit.setSymbolAndDiagnosticsForAST(ast, symbolAndDiagnostics); + } + }; + + SemanticInfoChain.prototype.setSymbolForDecl = function (decl, symbol) { + this.declSymbolMap.link(decl.getDeclID().toString(), symbol); + }; + SemanticInfoChain.prototype.getSymbolForDecl = function (decl) { + return this.declSymbolMap.read(decl.getDeclID().toString()); + }; + + SemanticInfoChain.prototype.removeSymbolFromCache = function (symbol) { + var path = [symbol.getName()]; + var kind = (symbol.getKind() & TypeScript.PullElementKind.SomeType) !== 0 ? TypeScript.PullElementKind.SomeType : TypeScript.PullElementKind.SomeValue; + + var kindID = this.getDeclPathCacheID(path, kind); + var symID = this.getDeclPathCacheID(path, symbol.getKind()); + + symbol.addCacheID(kindID); + symbol.addCacheID(symID); + + symbol.invalidateCachedIDs(this.symbolCache); + }; + + SemanticInfoChain.prototype.postDiagnostics = function () { + var errors = []; + + for (var i = 1; i < this.units.length; i++) { + this.units[i].getDiagnostics(errors); + } + + return errors; + }; + return SemanticInfoChain; + })(); + TypeScript.SemanticInfoChain = SemanticInfoChain; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclCollectionContext = (function () { + function DeclCollectionContext(semanticInfo, scriptName) { + if (typeof scriptName === "undefined") { scriptName = ""; } + this.semanticInfo = semanticInfo; + this.scriptName = scriptName; + this.parentChain = []; + this.foundValueDecl = false; + } + DeclCollectionContext.prototype.getParent = function () { + return this.parentChain ? this.parentChain[this.parentChain.length - 1] : null; + }; + + DeclCollectionContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + } + }; + + DeclCollectionContext.prototype.popParent = function () { + this.parentChain.length--; + }; + return DeclCollectionContext; + })(); + TypeScript.DeclCollectionContext = DeclCollectionContext; + + function preCollectImportDecls(ast, parentAST, context) { + var importDecl = ast; + var declFlags = 0 /* None */; + var span = TypeScript.TextSpan.fromBounds(importDecl.minChar, importDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(importDecl.id.text, importDecl.id.actualText, 256 /* TypeAlias */, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + return false; + } + TypeScript.preCollectImportDecls = preCollectImportDecls; + + function preCollectModuleDecls(ast, parentAST, context) { + var moduleDecl = ast; + var declFlags = 0 /* None */; + var modName = (moduleDecl.name).text; + var isDynamic = TypeScript.isQuoted(modName) || TypeScript.hasFlag(moduleDecl.getModuleFlags(), 512 /* IsDynamic */); + var kind = 4 /* Container */; + + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasFlag(moduleDecl.getModuleFlags(), 128 /* IsEnum */)) { + declFlags |= (4096 /* Enum */ | 131072 /* InitializedEnum */); + kind = 64 /* Enum */; + } else { + kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; + } + + var span = TypeScript.TextSpan.fromBounds(moduleDecl.minChar, moduleDecl.limChar); + + var decl = new TypeScript.PullDecl(modName, (moduleDecl.name).actualText, kind, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + var parent = context.getParent(); + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectModuleDecls = preCollectModuleDecls; + + function preCollectClassDecls(classDecl, parentAST, context) { + var declFlags = 0 /* None */; + var constructorDeclKind = 1024 /* Variable */; + + if (TypeScript.hasFlag(classDecl.getVarFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(classDecl.getVarFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + var span = TypeScript.TextSpan.fromBounds(classDecl.minChar, classDecl.limChar); + + var decl = new TypeScript.PullDecl(classDecl.name.text, classDecl.name.actualText, 8 /* Class */, declFlags, span, context.scriptName); + + var constructorDecl = new TypeScript.PullDecl(classDecl.name.text, classDecl.name.actualText, constructorDeclKind, declFlags | 16384 /* ClassConstructorVariable */, span, context.scriptName); + + decl.setValueDecl(constructorDecl); + + var parent = context.getParent(); + parent.addChildDecl(decl); + parent.addChildDecl(constructorDecl); + decl.setParentDecl(parent); + constructorDecl.setParentDecl(parent); + + context.pushParent(decl); + + context.semanticInfo.setDeclForAST(classDecl, decl); + context.semanticInfo.setASTForDecl(decl, classDecl); + context.semanticInfo.setASTForDecl(constructorDecl, classDecl); + + return true; + } + TypeScript.preCollectClassDecls = preCollectClassDecls; + + function createObjectTypeDeclaration(interfaceDecl, context) { + var declFlags = 0 /* None */; + + var span = TypeScript.TextSpan.fromBounds(interfaceDecl.minChar, interfaceDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("", "", 8388608 /* ObjectType */, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(interfaceDecl, decl); + context.semanticInfo.setASTForDecl(decl, interfaceDecl); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.createObjectTypeDeclaration = createObjectTypeDeclaration; + + function preCollectInterfaceDecls(interfaceDecl, parentAST, context) { + var declFlags = 0 /* None */; + + if (interfaceDecl.getFlags() & 8 /* TypeReference */) { + return createObjectTypeDeclaration(interfaceDecl, context); + } + + if (TypeScript.hasFlag(interfaceDecl.getVarFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + var span = TypeScript.TextSpan.fromBounds(interfaceDecl.minChar, interfaceDecl.limChar); + + var decl = new TypeScript.PullDecl(interfaceDecl.name.text, interfaceDecl.name.actualText, 16 /* Interface */, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(interfaceDecl, decl); + context.semanticInfo.setASTForDecl(decl, interfaceDecl); + + var parent = context.getParent(); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectInterfaceDecls = preCollectInterfaceDecls; + + function preCollectParameterDecl(argDecl, parentAST, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasFlag(argDecl.getVarFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasFlag(argDecl.getFlags(), 4 /* OptionalName */) || TypeScript.hasFlag(argDecl.id.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var span = TypeScript.TextSpan.fromBounds(argDecl.minChar, argDecl.limChar); + + var decl = new TypeScript.PullDecl(argDecl.id.text, argDecl.id.actualText, 2048 /* Parameter */, declFlags, span, context.scriptName); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (TypeScript.hasFlag(argDecl.getVarFlags(), 256 /* Property */)) { + var propDecl = new TypeScript.PullDecl(argDecl.id.text, argDecl.id.actualText, 4096 /* Property */, declFlags, span, context.scriptName); + propDecl.setValueDecl(decl); + context.parentChain[context.parentChain.length - 2].addChildDecl(propDecl); + propDecl.setParentDecl(context.parentChain[context.parentChain.length - 2]); + context.semanticInfo.setASTForDecl(decl, argDecl); + context.semanticInfo.setASTForDecl(propDecl, argDecl); + context.semanticInfo.setDeclForAST(argDecl, propDecl); + } else { + context.semanticInfo.setASTForDecl(decl, argDecl); + context.semanticInfo.setDeclForAST(argDecl, decl); + } + + if (argDecl.typeExpr && ((argDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (argDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((argDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.preCollectParameterDecl = preCollectParameterDecl; + + function preCollectTypeParameterDecl(typeParameterDecl, parentAST, context) { + var declFlags = 0 /* None */; + + var span = TypeScript.TextSpan.fromBounds(typeParameterDecl.minChar, typeParameterDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(typeParameterDecl.name.text, typeParameterDecl.name.actualText, 8192 /* TypeParameter */, declFlags, span, context.scriptName); + context.semanticInfo.setASTForDecl(decl, typeParameterDecl); + context.semanticInfo.setDeclForAST(typeParameterDecl, decl); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (typeParameterDecl.constraint && ((typeParameterDecl.constraint).term.nodeType === 14 /* InterfaceDeclaration */ || (typeParameterDecl.constraint).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((typeParameterDecl.constraint).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.preCollectTypeParameterDecl = preCollectTypeParameterDecl; + + function createPropertySignature(propertyDecl, context) { + var declFlags = 4 /* Public */; + var parent = context.getParent(); + var declType = parent.getKind() === 64 /* Enum */ ? 67108864 /* EnumMember */ : 4096 /* Property */; + + if (TypeScript.hasFlag(propertyDecl.id.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + if (TypeScript.hasFlag(propertyDecl.getVarFlags(), 4096 /* Constant */)) { + declFlags |= 524288 /* Constant */; + } + + var span = TypeScript.TextSpan.fromBounds(propertyDecl.minChar, propertyDecl.limChar); + + var decl = new TypeScript.PullDecl(propertyDecl.id.text, propertyDecl.id.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(propertyDecl, decl); + context.semanticInfo.setASTForDecl(decl, propertyDecl); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (propertyDecl.typeExpr && ((propertyDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (propertyDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((propertyDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.createPropertySignature = createPropertySignature; + + function createMemberVariableDeclaration(memberDecl, context) { + var declFlags = 0 /* None */; + var declType = 4096 /* Property */; + + if (TypeScript.hasFlag(memberDecl.getVarFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasFlag(memberDecl.getVarFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + var span = TypeScript.TextSpan.fromBounds(memberDecl.minChar, memberDecl.limChar); + + var decl = new TypeScript.PullDecl(memberDecl.id.text, memberDecl.id.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(memberDecl, decl); + context.semanticInfo.setASTForDecl(decl, memberDecl); + + var parent = context.getParent(); + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (memberDecl.typeExpr && ((memberDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (memberDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((memberDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.createMemberVariableDeclaration = createMemberVariableDeclaration; + + function createVariableDeclaration(varDecl, context) { + var declFlags = 0 /* None */; + var declType = 1024 /* Variable */; + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + var span = TypeScript.TextSpan.fromBounds(varDecl.minChar, varDecl.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(varDecl.id.text, varDecl.id.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(varDecl, decl); + context.semanticInfo.setASTForDecl(decl, varDecl); + + parent.addChildDecl(decl); + decl.setParentDecl(parent); + + if (varDecl.typeExpr && ((varDecl.typeExpr).term.nodeType === 14 /* InterfaceDeclaration */ || (varDecl.typeExpr).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((varDecl.typeExpr).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return false; + } + TypeScript.createVariableDeclaration = createVariableDeclaration; + + function preCollectVarDecls(ast, parentAST, context) { + var varDecl = ast; + var declFlags = 0 /* None */; + var declType = 1024 /* Variable */; + var isProperty = false; + var isStatic = false; + + if (TypeScript.hasFlag(varDecl.getVarFlags(), 2048 /* ClassProperty */)) { + return createMemberVariableDeclaration(varDecl, context); + } else if (TypeScript.hasFlag(varDecl.getVarFlags(), 256 /* Property */)) { + return createPropertySignature(varDecl, context); + } + + return createVariableDeclaration(varDecl, context); + } + TypeScript.preCollectVarDecls = preCollectVarDecls; + + function createFunctionTypeDeclaration(functionTypeDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 16777216 /* FunctionType */; + + var span = TypeScript.TextSpan.fromBounds(functionTypeDeclAST.minChar, functionTypeDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("", "", declType, declFlags, span, context.semanticInfo.getPath()); + context.semanticInfo.setDeclForAST(functionTypeDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, functionTypeDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (functionTypeDeclAST.returnTypeAnnotation && ((functionTypeDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (functionTypeDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((functionTypeDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createFunctionTypeDeclaration = createFunctionTypeDeclaration; + + function createConstructorTypeDeclaration(constructorTypeDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 33554432 /* ConstructorType */; + + var span = TypeScript.TextSpan.fromBounds(constructorTypeDeclAST.minChar, constructorTypeDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("{new}", "{new}", declType, declFlags, span, context.semanticInfo.getPath()); + context.semanticInfo.setDeclForAST(constructorTypeDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, constructorTypeDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (constructorTypeDeclAST.returnTypeAnnotation && ((constructorTypeDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (constructorTypeDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((constructorTypeDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createConstructorTypeDeclaration = createConstructorTypeDeclaration; + + function createFunctionDeclaration(funcDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 16384 /* Function */; + + if (TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 8 /* Ambient */)) { + declFlags |= 8 /* Ambient */; + } + + if (TypeScript.hasFlag(funcDeclAST.getFunctionFlags(), 1 /* Exported */)) { + declFlags |= 1 /* Exported */; + } + + if (!funcDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var span = TypeScript.TextSpan.fromBounds(funcDeclAST.minChar, funcDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(funcDeclAST.name.text, funcDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(funcDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, funcDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (funcDeclAST.returnTypeAnnotation && ((funcDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (funcDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((funcDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createFunctionDeclaration = createFunctionDeclaration; + + function createFunctionExpressionDeclaration(functionExpressionDeclAST, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasFlag(functionExpressionDeclAST.getFunctionFlags(), 2048 /* IsFatArrowFunction */)) { + declFlags |= 8192 /* FatArrow */; + } + + var span = TypeScript.TextSpan.fromBounds(functionExpressionDeclAST.minChar, functionExpressionDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var name = functionExpressionDeclAST.name ? functionExpressionDeclAST.name.actualText : ""; + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(functionExpressionDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, functionExpressionDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (functionExpressionDeclAST.returnTypeAnnotation && ((functionExpressionDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (functionExpressionDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((functionExpressionDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createFunctionExpressionDeclaration = createFunctionExpressionDeclaration; + + function createMemberFunctionDeclaration(memberFunctionDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + if (TypeScript.hasFlag(memberFunctionDeclAST.getFunctionFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasFlag(memberFunctionDeclAST.getFunctionFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (!memberFunctionDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + if (TypeScript.hasFlag(memberFunctionDeclAST.name.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + var span = TypeScript.TextSpan.fromBounds(memberFunctionDeclAST.minChar, memberFunctionDeclAST.limChar); + + var decl = new TypeScript.PullDecl(memberFunctionDeclAST.name.text, memberFunctionDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(memberFunctionDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, memberFunctionDeclAST); + + var parent = context.getParent(); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (memberFunctionDeclAST.returnTypeAnnotation && ((memberFunctionDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (memberFunctionDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((memberFunctionDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createMemberFunctionDeclaration = createMemberFunctionDeclaration; + + function createIndexSignatureDeclaration(indexSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */ | 1024 /* Index */; + var declType = 4194304 /* IndexSignature */; + + var span = TypeScript.TextSpan.fromBounds(indexSignatureDeclAST.minChar, indexSignatureDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("[]", "[]", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(indexSignatureDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, indexSignatureDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (indexSignatureDeclAST.returnTypeAnnotation && ((indexSignatureDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (indexSignatureDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + if (parent) { + declCollectionContext.pushParent(parent); + } + + declCollectionContext.scriptName = context.scriptName; + + TypeScript.getAstWalkerFactory().walk((indexSignatureDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createIndexSignatureDeclaration = createIndexSignatureDeclaration; + + function createCallSignatureDeclaration(callSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */ | 256 /* Call */; + var declType = 1048576 /* CallSignature */; + + var span = TypeScript.TextSpan.fromBounds(callSignatureDeclAST.minChar, callSignatureDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("()", "()", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(callSignatureDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, callSignatureDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (callSignatureDeclAST.returnTypeAnnotation && ((callSignatureDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (callSignatureDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((callSignatureDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createCallSignatureDeclaration = createCallSignatureDeclaration; + + function createConstructSignatureDeclaration(constructSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */ | 256 /* Call */; + var declType = 2097152 /* ConstructSignature */; + + var span = TypeScript.TextSpan.fromBounds(constructSignatureDeclAST.minChar, constructSignatureDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("new", "new", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(constructSignatureDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, constructSignatureDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (constructSignatureDeclAST.returnTypeAnnotation && ((constructSignatureDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (constructSignatureDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((constructSignatureDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createConstructSignatureDeclaration = createConstructSignatureDeclaration; + + function createClassConstructorDeclaration(constructorDeclAST, context) { + var declFlags = 512 /* Constructor */; + var declType = 32768 /* ConstructorMethod */; + + if (!constructorDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var span = TypeScript.TextSpan.fromBounds(constructorDeclAST.minChar, constructorDeclAST.limChar); + + var parent = context.getParent(); + + if (parent) { + var parentFlags = parent.getFlags(); + + if (parentFlags & 1 /* Exported */) { + declFlags |= 1 /* Exported */; + } + } + + var decl = new TypeScript.PullDecl(parent.getName(), parent.getDisplayName(), declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(constructorDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, constructorDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (constructorDeclAST.returnTypeAnnotation && ((constructorDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (constructorDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((constructorDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createClassConstructorDeclaration = createClassConstructorDeclaration; + + function createGetAccessorDeclaration(getAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 262144 /* GetAccessor */; + + if (TypeScript.hasFlag(getAccessorDeclAST.getFunctionFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasFlag(getAccessorDeclAST.name.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + if (TypeScript.hasFlag(getAccessorDeclAST.getFunctionFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var span = TypeScript.TextSpan.fromBounds(getAccessorDeclAST.minChar, getAccessorDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(getAccessorDeclAST.name.text, getAccessorDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(getAccessorDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, getAccessorDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + if (getAccessorDeclAST.returnTypeAnnotation && ((getAccessorDeclAST.returnTypeAnnotation).term.nodeType === 14 /* InterfaceDeclaration */ || (getAccessorDeclAST.returnTypeAnnotation).term.nodeType === 12 /* FunctionDeclaration */)) { + var declCollectionContext = new DeclCollectionContext(context.semanticInfo); + + declCollectionContext.scriptName = context.scriptName; + + if (parent) { + declCollectionContext.pushParent(parent); + } + + TypeScript.getAstWalkerFactory().walk((getAccessorDeclAST.returnTypeAnnotation).term, preCollectDecls, postCollectDecls, null, declCollectionContext); + } + + return true; + } + TypeScript.createGetAccessorDeclaration = createGetAccessorDeclaration; + + function createSetAccessorDeclaration(setAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 524288 /* SetAccessor */; + + if (TypeScript.hasFlag(setAccessorDeclAST.getFunctionFlags(), 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasFlag(setAccessorDeclAST.name.getFlags(), 4 /* OptionalName */)) { + declFlags |= 128 /* Optional */; + } + + if (TypeScript.hasFlag(setAccessorDeclAST.getFunctionFlags(), 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var span = TypeScript.TextSpan.fromBounds(setAccessorDeclAST.minChar, setAccessorDeclAST.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl(setAccessorDeclAST.name.actualText, setAccessorDeclAST.name.actualText, declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(setAccessorDeclAST, decl); + context.semanticInfo.setASTForDecl(decl, setAccessorDeclAST); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.createSetAccessorDeclaration = createSetAccessorDeclaration; + + function preCollectCatchDecls(ast, parentAST, context) { + var declFlags = 0 /* None */; + var declType = 1073741824 /* CatchBlock */; + + var span = TypeScript.TextSpan.fromBounds(ast.minChar, ast.limChar); + + var parent = context.getParent(); + + if (parent && (parent.getKind() === 536870912 /* WithBlock */ || (parent.getFlags() & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.PullDecl("", "", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectCatchDecls = preCollectCatchDecls; + + function preCollectWithDecls(ast, parentAST, context) { + var declFlags = 0 /* None */; + var declType = 536870912 /* WithBlock */; + + var span = TypeScript.TextSpan.fromBounds(ast.minChar, ast.limChar); + + var parent = context.getParent(); + + var decl = new TypeScript.PullDecl("", "", declType, declFlags, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + if (parent) { + parent.addChildDecl(decl); + decl.setParentDecl(parent); + } + + context.pushParent(decl); + + return true; + } + TypeScript.preCollectWithDecls = preCollectWithDecls; + + function preCollectFuncDecls(ast, parentAST, context) { + var funcDecl = ast; + + if (funcDecl.isConstructor) { + return createClassConstructorDeclaration(funcDecl, context); + } else if (funcDecl.isGetAccessor()) { + return createGetAccessorDeclaration(funcDecl, context); + } else if (funcDecl.isSetAccessor()) { + return createSetAccessorDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 1024 /* ConstructMember */)) { + return TypeScript.hasFlag(funcDecl.getFlags(), 8 /* TypeReference */) ? createConstructorTypeDeclaration(funcDecl, context) : createConstructSignatureDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 512 /* CallMember */)) { + return createCallSignatureDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 4096 /* IndexerMember */)) { + return createIndexSignatureDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFlags(), 8 /* TypeReference */)) { + return createFunctionTypeDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), 256 /* Method */)) { + return createMemberFunctionDeclaration(funcDecl, context); + } else if (TypeScript.hasFlag(funcDecl.getFunctionFlags(), (8192 /* IsFunctionExpression */ | 2048 /* IsFatArrowFunction */ | 16384 /* IsFunctionProperty */))) { + return createFunctionExpressionDeclaration(funcDecl, context); + } + + return createFunctionDeclaration(funcDecl, context); + } + TypeScript.preCollectFuncDecls = preCollectFuncDecls; + + function preCollectDecls(ast, parentAST, walker) { + var context = walker.state; + var go = false; + + if (ast.nodeType === 2 /* Script */) { + var script = ast; + var span = TypeScript.TextSpan.fromBounds(script.minChar, script.limChar); + + var decl = new TypeScript.PullDecl(context.scriptName, context.scriptName, 1 /* Script */, 0 /* None */, span, context.scriptName); + context.semanticInfo.setDeclForAST(ast, decl); + context.semanticInfo.setASTForDecl(decl, ast); + + context.pushParent(decl); + + go = true; + } else if (ast.nodeType === 1 /* List */) { + go = true; + } else if (ast.nodeType === 81 /* Block */) { + go = true; + } else if (ast.nodeType === 18 /* VariableDeclaration */) { + go = true; + } else if (ast.nodeType === 97 /* VariableStatement */) { + go = true; + } else if (ast.nodeType === 15 /* ModuleDeclaration */) { + go = preCollectModuleDecls(ast, parentAST, context); + } else if (ast.nodeType === 13 /* ClassDeclaration */) { + go = preCollectClassDecls(ast, parentAST, context); + } else if (ast.nodeType === 14 /* InterfaceDeclaration */) { + go = preCollectInterfaceDecls(ast, parentAST, context); + } else if (ast.nodeType === 19 /* Parameter */) { + go = preCollectParameterDecl(ast, parentAST, context); + } else if (ast.nodeType === 17 /* VariableDeclarator */) { + go = preCollectVarDecls(ast, parentAST, context); + } else if (ast.nodeType === 12 /* FunctionDeclaration */) { + go = preCollectFuncDecls(ast, parentAST, context); + } else if (ast.nodeType === 16 /* ImportDeclaration */) { + go = preCollectImportDecls(ast, parentAST, context); + } else if (ast.nodeType === 9 /* TypeParameter */) { + go = preCollectTypeParameterDecl(ast, parentAST, context); + } else if (ast.nodeType === 91 /* IfStatement */) { + go = true; + } else if (ast.nodeType === 90 /* ForStatement */) { + go = true; + } else if (ast.nodeType === 89 /* ForInStatement */) { + go = true; + } else if (ast.nodeType === 98 /* WhileStatement */) { + go = true; + } else if (ast.nodeType === 85 /* DoStatement */) { + go = true; + } else if (ast.nodeType === 25 /* CommaExpression */) { + go = true; + } else if (ast.nodeType === 93 /* ReturnStatement */) { + go = true; + } else if (ast.nodeType === 94 /* SwitchStatement */ || ast.nodeType === 100 /* CaseClause */) { + go = true; + } else if (ast.nodeType === 36 /* InvocationExpression */) { + go = true; + } else if (ast.nodeType === 37 /* ObjectCreationExpression */) { + go = true; + } else if (ast.nodeType === 96 /* TryStatement */) { + go = true; + } else if (ast.nodeType === 92 /* LabeledStatement */) { + go = true; + } else if (ast.nodeType === 101 /* CatchClause */) { + go = preCollectCatchDecls(ast, parentAST, context); + } else if (ast.nodeType === 99 /* WithStatement */) { + go = preCollectWithDecls(ast, parentAST, context); + } + + walker.options.goChildren = go; + + return ast; + } + TypeScript.preCollectDecls = preCollectDecls; + + function isContainer(decl) { + return decl.getKind() === 4 /* Container */ || decl.getKind() === 32 /* DynamicModule */ || decl.getKind() === 64 /* Enum */; + } + + function getInitializationFlag(decl) { + if (decl.getKind() & 4 /* Container */) { + return 32768 /* InitializedModule */; + } else if (decl.getKind() & 64 /* Enum */) { + return 131072 /* InitializedEnum */; + } else if (decl.getKind() & 32 /* DynamicModule */) { + return 65536 /* InitializedDynamicModule */; + } + + return 0 /* None */; + } + + function hasInitializationFlag(decl) { + var kind = decl.getKind(); + + if (kind & 4 /* Container */) { + return (decl.getFlags() & 32768 /* InitializedModule */) !== 0; + } else if (kind & 64 /* Enum */) { + return (decl.getFlags() & 131072 /* InitializedEnum */) != 0; + } else if (kind & 32 /* DynamicModule */) { + return (decl.getFlags() & 65536 /* InitializedDynamicModule */) !== 0; + } + + return false; + } + + function postCollectDecls(ast, parentAST, walker) { + var context = walker.state; + var parentDecl; + var initFlag = 0 /* None */; + + if (ast.nodeType === 15 /* ModuleDeclaration */) { + var thisModule = context.getParent(); + context.popParent(); + parentDecl = context.getParent(); + + if (hasInitializationFlag(thisModule)) { + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + + var valueDecl = new TypeScript.PullDecl(thisModule.getName(), thisModule.getDisplayName(), 1024 /* Variable */, thisModule.getFlags(), thisModule.getSpan(), context.scriptName); + + thisModule.setValueDecl(valueDecl); + + context.semanticInfo.setASTForDecl(valueDecl, ast); + + if (parentDecl) { + parentDecl.addChildDecl(valueDecl); + valueDecl.setParentDecl(parentDecl); + } + } + } else if (ast.nodeType === 13 /* ClassDeclaration */) { + context.popParent(); + + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + } else if (ast.nodeType === 14 /* InterfaceDeclaration */) { + context.popParent(); + } else if (ast.nodeType === 12 /* FunctionDeclaration */) { + context.popParent(); + + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + } else if (ast.nodeType === 17 /* VariableDeclarator */) { + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + } else if (ast.nodeType === 101 /* CatchClause */) { + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + + context.popParent(); + } else if (ast.nodeType === 99 /* WithStatement */) { + parentDecl = context.getParent(); + + if (parentDecl && isContainer(parentDecl)) { + initFlag = getInitializationFlag(parentDecl); + parentDecl.setFlags(parentDecl.getFlags() | initFlag); + } + + context.popParent(); + } + + return ast; + } + TypeScript.postCollectDecls = postCollectDecls; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.globalBindingPhase = 0; + + function getPathToDecl(decl) { + if (!decl) { + return []; + } + + var decls = decl.getParentPath(); + + if (decls) { + return decls; + } else { + decls = [decl]; + } + + var parentDecl = decl.getParentDecl(); + + while (parentDecl) { + if (parentDecl && decls[decls.length - 1] != parentDecl && !(parentDecl.getKind() & 512 /* ObjectLiteral */)) { + decls[decls.length] = parentDecl; + } + parentDecl = parentDecl.getParentDecl(); + } + + decls = decls.reverse(); + + decl.setParentPath(decls); + + return decls; + } + TypeScript.getPathToDecl = getPathToDecl; + + function findSymbolInContext(name, declKind, startingDecl) { + var startTime = new Date().getTime(); + var contextSymbolPath = getPathToDecl(startingDecl); + var copyOfContextSymbolPath = []; + var symbol = null; + + var endTime = 0; + + if (contextSymbolPath.length) { + for (var i = 0; i < contextSymbolPath.length; i++) { + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].getName(); + } + + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = name; + + while (copyOfContextSymbolPath.length >= 2) { + symbol = TypeScript.globalSemanticInfoChain.findSymbol(copyOfContextSymbolPath, declKind); + + if (symbol) { + endTime = new Date().getTime(); + TypeScript.time_in_findSymbol += endTime - startTime; + + return symbol; + } + copyOfContextSymbolPath.length -= 2; + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = name; + } + } + + symbol = TypeScript.globalSemanticInfoChain.findSymbol([name], declKind); + + endTime = new Date().getTime(); + TypeScript.time_in_findSymbol += endTime - startTime; + + return symbol; + } + TypeScript.findSymbolInContext = findSymbolInContext; + + var PullSymbolBinder = (function () { + function PullSymbolBinder(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + this.bindingPhase = TypeScript.globalBindingPhase++; + this.functionTypeParameterCache = new TypeScript.BlockIntrinsics(); + this.reBindingAfterChange = false; + this.startingDeclForRebind = TypeScript.pullDeclID; + this.startingSymbolForRebind = TypeScript.pullSymbolID; + } + PullSymbolBinder.prototype.findTypeParameterInCache = function (name) { + return this.functionTypeParameterCache[name]; + }; + + PullSymbolBinder.prototype.addTypeParameterToCache = function (typeParameter) { + this.functionTypeParameterCache[typeParameter.getName()] = typeParameter; + }; + + PullSymbolBinder.prototype.resetTypeParameterCache = function () { + this.functionTypeParameterCache = new TypeScript.BlockIntrinsics(); + }; + + PullSymbolBinder.prototype.setUnit = function (fileName) { + this.semanticInfo = this.semanticInfoChain.getUnit(fileName); + }; + + PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { + if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } + var parentDecl = decl.getParentDecl(); + + if (parentDecl.getKind() == 1 /* Script */) { + return null; + } + + var parent = parentDecl.getSymbol(); + + if (!parent && parentDecl && !parentDecl.isBound()) { + this.bindDeclToPullSymbol(parentDecl); + } + + parent = parentDecl.getSymbol(); + + if (parent) { + if (returnInstanceType && parent.isType() && parent.isContainer()) { + var instanceSymbol = (parent).getInstanceSymbol(); + + if (instanceSymbol) { + return instanceSymbol.getType(); + } + } + + return parent.getType(); + } + + return null; + }; + + PullSymbolBinder.prototype.findDeclsInContext = function (startingDecl, declKind, searchGlobally) { + if (!searchGlobally) { + var parentDecl = startingDecl.getParentDecl(); + return parentDecl.searchChildDecls(startingDecl.getName(), declKind); + } + + var contextSymbolPath = getPathToDecl(startingDecl); + + if (contextSymbolPath.length) { + var copyOfContextSymbolPath = []; + + for (var i = 0; i < contextSymbolPath.length; i++) { + if (contextSymbolPath[i].getKind() & 1 /* Script */) { + continue; + } + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].getName(); + } + + return this.semanticInfoChain.findDecls(copyOfContextSymbolPath, declKind); + } + + return this.semanticInfoChain.findDecls([name], declKind); + }; + + PullSymbolBinder.prototype.symbolIsRedeclaration = function (sym) { + var symID = sym.getSymbolID(); + return (symID >= this.startingSymbolForRebind) || ((sym.getRebindingID() === this.bindingPhase) && (symID !== this.startingSymbolForRebind)); + }; + + PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { + var modName = moduleContainerDecl.getName(); + + var moduleContainerTypeSymbol = null; + var moduleInstanceSymbol = null; + var moduleInstanceTypeSymbol = null; + + var moduleInstanceDecl = moduleContainerDecl.getValueDecl(); + + var moduleKind = moduleContainerDecl.getKind(); + + var parent = this.getParent(moduleContainerDecl); + var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); + var parentDecl = moduleContainerDecl.getParentDecl(); + var moduleAST = this.semanticInfo.getASTForDecl(moduleContainerDecl); + + var isExported = moduleContainerDecl.getFlags() & 1 /* Exported */; + var isEnum = (moduleKind & 64 /* Enum */) != 0; + var searchKind = isEnum ? 64 /* Enum */ : TypeScript.PullElementKind.SomeContainer; + var isInitializedModule = (moduleContainerDecl.getFlags() & TypeScript.PullElementFlags.SomeInitializedModule) != 0; + + var createdNewSymbol = false; + + if (parent) { + if (isExported) { + moduleContainerTypeSymbol = parent.findNestedType(modName, searchKind); + } else { + moduleContainerTypeSymbol = parent.findContainedMember(modName); + + if (moduleContainerTypeSymbol && !(moduleContainerTypeSymbol.getKind() & searchKind)) { + moduleContainerTypeSymbol = null; + } + } + } else if (!isExported || moduleContainerDecl.getKind() === 32 /* DynamicModule */) { + moduleContainerTypeSymbol = findSymbolInContext(modName, searchKind, moduleContainerDecl); + } + + if (moduleContainerTypeSymbol && moduleContainerTypeSymbol.getKind() !== moduleKind) { + if (isInitializedModule) { + moduleContainerDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), moduleAST.minChar, moduleAST.getLength(), 69 /* Duplicate_identifier__0_ */, [moduleContainerDecl.getDisplayName()])); + } + + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + moduleInstanceSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + } else { + moduleContainerTypeSymbol = new TypeScript.PullContainerTypeSymbol(modName, moduleKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(moduleContainerTypeSymbol, searchKind); + } + } + + if (!moduleInstanceSymbol && isInitializedModule) { + var variableSymbol = null; + if (!isEnum) { + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParent = declarations[0].getParentDecl(); + + if ((parentDecl !== variableSymbolParent) && (!this.reBindingAfterChange || (variableSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + variableSymbol = null; + } + } + } + } else if (!(moduleContainerDecl.getFlags() & 1 /* Exported */)) { + var siblingDecls = parentDecl.getChildDecls(); + var augmentedDecl = null; + + for (var i = 0; i < siblingDecls.length; i++) { + if (siblingDecls[i] == moduleContainerDecl) { + break; + } + + if ((siblingDecls[i].getName() == modName) && (siblingDecls[i].getKind() & (8 /* Class */ | TypeScript.PullElementKind.SomeFunction))) { + augmentedDecl = siblingDecls[i]; + break; + } + } + + if (augmentedDecl) { + variableSymbol = augmentedDecl.getSymbol(); + + if (variableSymbol && variableSymbol.isType()) { + variableSymbol = (variableSymbol).getConstructorMethod(); + } + } + } + } + + if (variableSymbol) { + var prevKind = variableSymbol.getKind(); + var acceptableRedeclaration = (prevKind == 16384 /* Function */) || (prevKind == 32768 /* ConstructorMethod */) || variableSymbol.hasFlag(TypeScript.PullElementFlags.ImplicitVariable); + + if (acceptableRedeclaration) { + moduleInstanceTypeSymbol = variableSymbol.getType(); + } else { + variableSymbol = null; + } + } + + if (!moduleInstanceTypeSymbol) { + moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol(modName, 8388608 /* ObjectType */); + } + + moduleInstanceTypeSymbol.addDeclaration(moduleContainerDecl); + + moduleInstanceTypeSymbol.setAssociatedContainerType(moduleContainerTypeSymbol); + + if (variableSymbol) { + moduleInstanceSymbol = variableSymbol; + } else { + moduleInstanceSymbol = new TypeScript.PullSymbol(modName, 1024 /* Variable */); + moduleInstanceSymbol.setType(moduleInstanceTypeSymbol); + } + + moduleContainerTypeSymbol.setInstanceSymbol(moduleInstanceSymbol); + } + + moduleContainerTypeSymbol.addDeclaration(moduleContainerDecl); + moduleContainerDecl.setSymbol(moduleContainerTypeSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(moduleAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(moduleContainerTypeSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(moduleAST, TypeScript.SymbolAndDiagnostics.fromSymbol(moduleContainerTypeSymbol)); + + var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); + if (isEnum && moduleDeclarations.length > 1 && moduleAST.members.members.length > 0) { + var multipleEnums = TypeScript.ArrayUtilities.where(moduleDeclarations, function (d) { + return d.getKind() === 64 /* Enum */; + }).length > 1; + if (multipleEnums) { + var firstVariable = moduleAST.members.members[0]; + var firstVariableDeclarator = firstVariable.declaration.declarators.members[0]; + if (firstVariableDeclarator.isImplicitlyInitialized) { + moduleContainerDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), firstVariableDeclarator.minChar, firstVariableDeclarator.getLength(), 264 /* Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element */, null)); + } + } + } + + if (createdNewSymbol) { + if (parent) { + var linkKind = moduleContainerDecl.getFlags() & 1 /* Exported */ ? 5 /* PublicMember */ : 6 /* PrivateMember */; + + if (linkKind === 5 /* PublicMember */) { + parent.addMember(moduleContainerTypeSymbol, linkKind); + } else { + moduleContainerTypeSymbol.setContainer(parent); + } + } + } else if (this.reBindingAfterChange) { + var decls = moduleContainerTypeSymbol.getDeclarations(); + var scriptName = moduleContainerDecl.getScriptName(); + + for (var i = 0; i < decls.length; i++) { + if (decls[i].getScriptName() === scriptName && decls[i].getDeclID() < this.startingDeclForRebind) { + moduleContainerTypeSymbol.removeDeclaration(decls[i]); + } + } + + moduleContainerTypeSymbol.invalidate(); + + moduleInstanceSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + + if (moduleInstanceSymbol) { + var moduleInstanceTypeSymbol = moduleInstanceSymbol.getType(); + decls = moduleInstanceTypeSymbol.getDeclarations(); + + for (var i = 0; i < decls.length; i++) { + if (decls[i].getScriptName() === scriptName && decls[i].getDeclID() < this.startingDeclForRebind) { + moduleInstanceTypeSymbol.removeDeclaration(decls[i]); + } + } + + moduleInstanceTypeSymbol.addDeclaration(moduleContainerDecl); + moduleInstanceTypeSymbol.invalidate(); + } + } + + if (isEnum) { + moduleInstanceTypeSymbol = moduleContainerTypeSymbol.getInstanceSymbol().getType(); + + if (this.reBindingAfterChange) { + var existingIndexSigs = moduleInstanceTypeSymbol.getIndexSignatures(); + + for (var i = 0; i < existingIndexSigs.length; i++) { + moduleInstanceTypeSymbol.removeIndexSignature(existingIndexSigs[i]); + } + } + + var enumIndexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var enumIndexParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); + enumIndexParameterSymbol.setType(this.semanticInfoChain.numberTypeSymbol); + enumIndexSignature.addParameter(enumIndexParameterSymbol); + enumIndexSignature.setReturnType(this.semanticInfoChain.stringTypeSymbol); + + moduleInstanceTypeSymbol.addIndexSignature(enumIndexSignature); + + moduleInstanceTypeSymbol.recomputeIndexSignatures(); + } + + var valueDecl = moduleContainerDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + var otherDecls = this.findDeclsInContext(moduleContainerDecl, moduleContainerDecl.getKind(), true); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindImportDeclaration = function (importDeclaration) { + var declFlags = importDeclaration.getFlags(); + var declKind = importDeclaration.getKind(); + var importDeclAST = this.semanticInfo.getASTForDecl(importDeclaration); + + var isExported = false; + var linkKind = 6 /* PrivateMember */; + var importSymbol = null; + var declName = importDeclaration.getName(); + var parentHadSymbol = false; + var parent = this.getParent(importDeclaration); + + if (parent) { + importSymbol = parent.findMember(declName, false); + + if (!importSymbol) { + importSymbol = parent.findContainedMember(declName); + + if (importSymbol) { + var declarations = importSymbol.getDeclarations(); + + if (declarations.length) { + var importSymbolParent = declarations[0].getParentDecl(); + + if ((importSymbolParent !== importDeclaration.getParentDecl()) && (!this.reBindingAfterChange || (importSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + importSymbol = null; + } + } + } + } + } else if (!(importDeclaration.getFlags() & 1 /* Exported */)) { + importSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeContainer, importDeclaration); + } + + if (importSymbol) { + parentHadSymbol = true; + } + + if (importSymbol && this.symbolIsRedeclaration(importSymbol)) { + importDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), importDeclAST.minChar, importDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [importDeclaration.getDisplayName()])); + importSymbol = null; + } + + if (this.reBindingAfterChange && importSymbol) { + var decls = importSymbol.getDeclarations(); + var scriptName = importDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + importSymbol.removeDeclaration(decls[j]); + } + } + + importSymbol.setUnresolved(); + } + + if (!importSymbol) { + importSymbol = new TypeScript.PullTypeAliasSymbol(declName); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(importSymbol, TypeScript.PullElementKind.SomeContainer); + } + } + + importSymbol.addDeclaration(importDeclaration); + importDeclaration.setSymbol(importSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(importDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(importSymbol)); + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(importSymbol, 5 /* PublicMember */); + } else { + importSymbol.setContainer(parent); + } + } + + importSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.cleanInterfaceSignatures = function (interfaceSymbol) { + var callSigs = interfaceSymbol.getCallSignatures(); + var constructSigs = interfaceSymbol.getConstructSignatures(); + var indexSigs = interfaceSymbol.getIndexSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + if (callSigs[i].getSymbolID() < this.startingSymbolForRebind) { + interfaceSymbol.removeCallSignature(callSigs[i], false); + } + } + for (var i = 0; i < constructSigs.length; i++) { + if (constructSigs[i].getSymbolID() < this.startingSymbolForRebind) { + interfaceSymbol.removeConstructSignature(constructSigs[i], false); + } + } + for (var i = 0; i < indexSigs.length; i++) { + if (indexSigs[i].getSymbolID() < this.startingSymbolForRebind) { + interfaceSymbol.removeIndexSignature(indexSigs[i], false); + } + } + + interfaceSymbol.recomputeCallSignatures(); + interfaceSymbol.recomputeConstructSignatures(); + interfaceSymbol.recomputeIndexSignatures(); + }; + + PullSymbolBinder.prototype.cleanClassSignatures = function (classSymbol) { + var callSigs = classSymbol.getCallSignatures(); + var constructSigs = classSymbol.getConstructSignatures(); + var indexSigs = classSymbol.getIndexSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + classSymbol.removeCallSignature(callSigs[i], false); + } + for (var i = 0; i < constructSigs.length; i++) { + classSymbol.removeConstructSignature(constructSigs[i], false); + } + for (var i = 0; i < indexSigs.length; i++) { + classSymbol.removeIndexSignature(indexSigs[i], false); + } + + classSymbol.recomputeCallSignatures(); + classSymbol.recomputeConstructSignatures(); + classSymbol.recomputeIndexSignatures(); + + var constructorSymbol = classSymbol.getConstructorMethod(); + var constructorTypeSymbol = (constructorSymbol ? constructorSymbol.getType() : null); + + if (constructorTypeSymbol) { + constructSigs = constructorTypeSymbol.getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + constructorTypeSymbol.removeConstructSignature(constructSigs[i], false); + } + + constructorTypeSymbol.recomputeConstructSignatures(); + constructorTypeSymbol.invalidate(); + constructorSymbol.invalidate(); + } + + classSymbol.invalidate(); + }; + + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { + var className = classDecl.getName(); + var classSymbol = null; + + var constructorSymbol = null; + var constructorTypeSymbol = null; + + var classAST = this.semanticInfo.getASTForDecl(classDecl); + var parentHadSymbol = false; + + var parent = this.getParent(classDecl); + var parentDecl = classDecl.getParentDecl(); + var cleanedPreviousDecls = false; + var isExported = classDecl.getFlags() & 1 /* Exported */; + var isGeneric = false; + + var acceptableSharedKind = 8 /* Class */; + + if (parent) { + if (isExported) { + classSymbol = parent.findNestedType(className); + + if (!classSymbol) { + classSymbol = parent.findMember(className, false); + } + } else { + classSymbol = parent.findContainedMember(className); + + if (classSymbol && (classSymbol.getKind() & acceptableSharedKind)) { + var declarations = classSymbol.getDeclarations(); + + if (declarations.length) { + var classSymbolParent = declarations[0].getParentDecl(); + + if ((classSymbolParent !== parentDecl) && (!this.reBindingAfterChange || (classSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + classSymbol = null; + } + } + } else { + classSymbol = null; + } + } + } else { + classSymbol = findSymbolInContext(className, acceptableSharedKind, classDecl); + } + + if (classSymbol && (!(classSymbol.getKind() & acceptableSharedKind) || !this.reBindingAfterChange || this.symbolIsRedeclaration(classSymbol))) { + classDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), classAST.minChar, classAST.getLength(), 69 /* Duplicate_identifier__0_ */, [classDecl.getDisplayName()])); + classSymbol = null; + } else if (classSymbol) { + parentHadSymbol = true; + } + + var decls; + + if (this.reBindingAfterChange && classSymbol) { + decls = classSymbol.getDeclarations(); + var scriptName = classDecl.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + classSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = constructorSymbol.getType(); + + decls = constructorSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + constructorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (constructorSymbol.getIsSynthesized()) { + classSymbol.setConstructorMethod(null); + } + + if (classSymbol.isGeneric()) { + isGeneric = true; + + var specializations = classSymbol.getKnownSpecializations(); + var specialization = null; + + for (var i = 0; i < specializations.length; i++) { + specializations[i].setUnresolved(); + specializations[i].invalidate(); + } + + classSymbol.cleanTypeParameters(); + constructorTypeSymbol.cleanTypeParameters(); + } + + classSymbol.setUnresolved(); + constructorSymbol.setUnresolved(); + constructorTypeSymbol.setUnresolved(); + } + + if (!parentHadSymbol) { + classSymbol = new TypeScript.PullClassTypeSymbol(className); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(classSymbol, acceptableSharedKind); + } + } + + classSymbol.addDeclaration(classDecl); + + classDecl.setSymbol(classSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(classAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(classSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(classAST, TypeScript.SymbolAndDiagnostics.fromSymbol(classSymbol)); + + if (parent && !parentHadSymbol) { + var linkKind = classDecl.getFlags() & 1 /* Exported */ ? 5 /* PublicMember */ : 6 /* PrivateMember */; + + if (linkKind === 5 /* PublicMember */) { + parent.addMember(classSymbol, linkKind); + } else { + classSymbol.setContainer(parent); + } + } + + if (parentHadSymbol && cleanedPreviousDecls) { + this.cleanClassSignatures(classSymbol); + + if (isGeneric) { + specializations = classSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + this.cleanClassSignatures(specializations[i]); + } + } + } + + this.resetTypeParameterCache(); + + this.resetTypeParameterCache(); + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = (constructorSymbol ? constructorSymbol.getType() : null); + + if (!constructorSymbol) { + constructorSymbol = new TypeScript.PullSymbol(className, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullConstructorTypeSymbol(); + + constructorSymbol.setIsSynthesized(); + + constructorSymbol.setType(constructorTypeSymbol); + constructorSymbol.addDeclaration(classDecl.getValueDecl()); + classSymbol.setConstructorMethod(constructorSymbol); + + constructorTypeSymbol.addDeclaration(classDecl); + + classSymbol.setHasDefaultConstructor(); + } + + constructorTypeSymbol.setAssociatedContainerType(classSymbol); + + var typeParameters = classDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = classSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + classSymbol.addMember(typeParameter, 18 /* TypeParameter */); + constructorTypeSymbol.addTypeParameter(typeParameter, true); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + classDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + var valueDecl = classDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + classSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { + var interfaceName = interfaceDecl.getName(); + var interfaceSymbol = findSymbolInContext(interfaceName, TypeScript.PullElementKind.SomeType, interfaceDecl); + + var interfaceAST = this.semanticInfo.getASTForDecl(interfaceDecl); + var createdNewSymbol = false; + var parent = this.getParent(interfaceDecl); + + var acceptableSharedKind = 16 /* Interface */; + + if (parent) { + interfaceSymbol = parent.findNestedType(interfaceName); + } else if (!(interfaceDecl.getFlags() & 1 /* Exported */)) { + interfaceSymbol = findSymbolInContext(interfaceName, acceptableSharedKind, interfaceDecl); + } + + if (interfaceSymbol && !(interfaceSymbol.getKind() & acceptableSharedKind)) { + interfaceDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), interfaceAST.minChar, interfaceAST.getLength(), 69 /* Duplicate_identifier__0_ */, [interfaceDecl.getDisplayName()])); + interfaceSymbol = null; + } + + if (!interfaceSymbol) { + interfaceSymbol = new TypeScript.PullTypeSymbol(interfaceName, 16 /* Interface */); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(interfaceSymbol, acceptableSharedKind); + } + } + + interfaceSymbol.addDeclaration(interfaceDecl); + interfaceDecl.setSymbol(interfaceSymbol); + + if (createdNewSymbol) { + if (parent) { + var linkKind = interfaceDecl.getFlags() & 1 /* Exported */ ? 5 /* PublicMember */ : 6 /* PrivateMember */; + + if (linkKind === 5 /* PublicMember */) { + parent.addMember(interfaceSymbol, linkKind); + } else { + interfaceSymbol.setContainer(parent); + } + } + } else if (this.reBindingAfterChange) { + var decls = interfaceSymbol.getDeclarations(); + var scriptName = interfaceDecl.getScriptName(); + + for (var i = 0; i < decls.length; i++) { + if (decls[i].getScriptName() === scriptName && decls[i].getDeclID() < this.startingDeclForRebind) { + interfaceSymbol.removeDeclaration(decls[i]); + } + } + + if (interfaceSymbol.isGeneric()) { + var specializations = interfaceSymbol.getKnownSpecializations(); + var specialization = null; + + for (var i = 0; i < specializations.length; i++) { + specialization = specializations[i]; + + this.cleanInterfaceSignatures(specialization); + specialization.invalidate(); + } + + interfaceSymbol.cleanTypeParameters(); + } + + this.cleanInterfaceSignatures(interfaceSymbol); + interfaceSymbol.invalidate(); + } + + this.resetTypeParameterCache(); + + this.resetTypeParameterCache(); + + var typeParameters = interfaceDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + interfaceSymbol.addMember(typeParameter, 18 /* TypeParameter */); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + for (var j = 0; j < typeParameterDecls.length; j++) { + var typeParameterDeclParent = typeParameterDecls[j].getParentDecl(); + + if (typeParameterDeclParent && typeParameterDeclParent === interfaceDecl) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + interfaceDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + + break; + } + } + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + var otherDecls = this.findDeclsInContext(interfaceDecl, interfaceDecl.getKind(), true); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { + var objectSymbolAST = this.semanticInfo.getASTForDecl(objectDecl); + + var objectSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + + objectSymbol.addDeclaration(objectDecl); + objectDecl.setSymbol(objectSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(objectSymbolAST, TypeScript.SymbolAndDiagnostics.fromSymbol(objectSymbol)); + + var childDecls = objectDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + + var typeParameters = objectDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = objectSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + objectSymbol.addMember(typeParameter, 18 /* TypeParameter */); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + objectDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindConstructorTypeDeclarationToPullSymbol = function (constructorTypeDeclaration) { + var declKind = constructorTypeDeclaration.getKind(); + var declFlags = constructorTypeDeclaration.getFlags(); + var constructorTypeAST = this.semanticInfo.getASTForDecl(constructorTypeDeclaration); + + var constructorTypeSymbol = new TypeScript.PullConstructorTypeSymbol(); + + constructorTypeDeclaration.setSymbol(constructorTypeSymbol); + constructorTypeSymbol.addDeclaration(constructorTypeDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(constructorTypeAST, TypeScript.SymbolAndDiagnostics.fromSymbol(constructorTypeSymbol)); + + var signature = new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */); + + if ((constructorTypeAST).variableArgList) { + signature.setHasVariableParamList(); + } + + signature.addDeclaration(constructorTypeDeclaration); + constructorTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(constructorTypeDeclaration), constructorTypeSymbol, signature); + + constructorTypeSymbol.addSignature(signature); + + var typeParameters = constructorTypeDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), false); + + constructorTypeSymbol.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + constructorTypeDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.getFlags(); + var declKind = variableDeclaration.getKind(); + var varDeclAST = this.semanticInfo.getASTForDecl(variableDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var linkKind = 6 /* PrivateMember */; + + var variableSymbol = null; + + var declName = variableDeclaration.getName(); + + var parentHadSymbol = false; + + var parent = this.getParent(variableDeclaration, true); + + var parentDecl = variableDeclaration.getParentDecl(); + + var isImplicit = (declFlags & TypeScript.PullElementFlags.ImplicitVariable) !== 0; + var isModuleValue = (declFlags & (32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */ | 131072 /* InitializedEnum */)) != 0; + var isEnumValue = (declFlags & 131072 /* InitializedEnum */) != 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) != 0; + + if (parentDecl && !isImplicit) { + parentDecl.addVariableDeclToGroup(variableDeclaration); + } + + if (parent) { + if (isExported) { + variableSymbol = parent.findMember(declName, false); + } else { + variableSymbol = parent.findContainedMember(declName); + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParent = declarations[0].getParentDecl(); + + if ((parentDecl !== variableSymbolParent) && (!this.reBindingAfterChange || (variableSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + variableSymbol = null; + } + } + } + } else if (!(variableDeclaration.getFlags() & 1 /* Exported */)) { + variableSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeValue, variableDeclaration); + } + + if (variableSymbol && !variableSymbol.isType()) { + parentHadSymbol = true; + } + + var span; + var decl; + var decls; + var ast; + var members; + + if (variableSymbol && this.symbolIsRedeclaration(variableSymbol)) { + var prevKind = variableSymbol.getKind(); + var prevIsAmbient = variableSymbol.hasFlag(8 /* Ambient */); + var prevIsEnum = variableSymbol.hasFlag(131072 /* InitializedEnum */); + var prevIsClass = prevKind == 32768 /* ConstructorMethod */; + var prevIsContainer = variableSymbol.hasFlag(32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */); + var onlyOneIsEnum = (isEnumValue || prevIsEnum) && !(isEnumValue && prevIsEnum); + var isAmbient = (variableDeclaration.getFlags() & 8 /* Ambient */) != 0; + var isClass = variableDeclaration.getKind() == 32768 /* ConstructorMethod */; + + var acceptableRedeclaration = isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevKind == 16384 /* Function */) || (!isModuleValue && prevIsContainer && isAmbient) || (!isModuleValue && prevIsClass) || variableSymbol.hasFlag(TypeScript.PullElementFlags.ImplicitVariable)); + + if (acceptableRedeclaration && prevIsClass && !prevIsAmbient) { + if (variableSymbol.getDeclarations()[0].getScriptName() != variableDeclaration.getScriptName()) { + acceptableRedeclaration = false; + } + } + + if ((!isModuleValue && !isClass && !isAmbient) || !acceptableRedeclaration || onlyOneIsEnum) { + span = variableDeclaration.getSpan(); + if (!parent || variableSymbol.getIsSynthesized()) { + var errorDecl = isImplicit ? variableSymbol.getDeclarations()[0] : variableDeclaration; + errorDecl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), span.start(), span.length(), 69 /* Duplicate_identifier__0_ */, [variableDeclaration.getDisplayName()])); + } + + variableSymbol = null; + parentHadSymbol = false; + } + } else if (variableSymbol && (variableSymbol.getKind() !== 1024 /* Variable */) && !isImplicit) { + span = variableDeclaration.getSpan(); + + variableDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), span.start(), span.length(), 69 /* Duplicate_identifier__0_ */, [variableDeclaration.getDisplayName()])); + variableSymbol = null; + parentHadSymbol = false; + } + + if (this.reBindingAfterChange && variableSymbol && !variableSymbol.isType()) { + decls = variableSymbol.getDeclarations(); + var scriptName = variableDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + variableSymbol.removeDeclaration(decls[j]); + } + } + + variableSymbol.invalidate(); + } + + var replaceProperty = false; + var previousProperty = null; + + if ((declFlags & TypeScript.PullElementFlags.ImplicitVariable) === 0) { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(varDeclAST.id, TypeScript.SymbolAndDiagnostics.fromSymbol(variableSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(varDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(variableSymbol)); + } else if (!parentHadSymbol) { + if (isClassConstructorVariable) { + var classTypeSymbol = variableSymbol; + + if (parent) { + members = parent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].getName() === declName) && (members[i].getKind() === 8 /* Class */)) { + classTypeSymbol = members[i]; + break; + } + } + } + + if (!classTypeSymbol) { + var parentDecl = variableDeclaration.getParentDecl(); + + if (parentDecl) { + var childDecls = parentDecl.searchChildDecls(declName, TypeScript.PullElementKind.SomeType); + + if (childDecls.length) { + for (var i = 0; i < childDecls.length; i++) { + if (childDecls[i].getValueDecl() === variableDeclaration) { + classTypeSymbol = childDecls[i].getSymbol(); + } + } + } + } + + if (!classTypeSymbol) { + classTypeSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeType, variableDeclaration); + } + } + + if (classTypeSymbol && (classTypeSymbol.getKind() !== 8 /* Class */)) { + classTypeSymbol = null; + } + + if (classTypeSymbol && classTypeSymbol.isClass()) { + replaceProperty = variableSymbol && variableSymbol.getIsSynthesized(); + + if (replaceProperty) { + previousProperty = variableSymbol; + } + + variableSymbol = classTypeSymbol.getConstructorMethod(); + variableDeclaration.setSymbol(variableSymbol); + + decls = classTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfo.getASTForDecl(decl); + + if (ast) { + this.semanticInfo.setASTForDecl(variableDeclaration, ast); + } + } + } else { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.setType(this.semanticInfoChain.anyTypeSymbol); + } + } else if (declFlags & TypeScript.PullElementFlags.SomeInitializedModule) { + var moduleContainerTypeSymbol = null; + var moduleParent = this.getParent(variableDeclaration); + + if (moduleParent) { + members = moduleParent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].getName() === declName) && (members[i].isContainer())) { + moduleContainerTypeSymbol = members[i]; + break; + } + } + } + + if (!moduleContainerTypeSymbol) { + var parentDecl = variableDeclaration.getParentDecl(); + + if (parentDecl) { + var searchKind = (declFlags & (32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */)) ? TypeScript.PullElementKind.SomeContainer : 64 /* Enum */; + var childDecls = parentDecl.searchChildDecls(declName, searchKind); + + if (childDecls.length) { + for (var i = 0; i < childDecls.length; i++) { + if (childDecls[i].getValueDecl() === variableDeclaration) { + moduleContainerTypeSymbol = childDecls[i].getSymbol(); + } + } + } + } + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = findSymbolInContext(declName, TypeScript.PullElementKind.SomeContainer, variableDeclaration); + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = findSymbolInContext(declName, 64 /* Enum */, variableDeclaration); + } + } + } + + if (moduleContainerTypeSymbol && (!moduleContainerTypeSymbol.isContainer())) { + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + decls = moduleContainerTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfo.getASTForDecl(decl); + + if (ast) { + this.semanticInfo.setASTForDecl(variableDeclaration, ast); + } + } + } else { + TypeScript.Debug.assert(false, "Attempted to bind invalid implicit variable symbol"); + } + } + } else { + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + } + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(variableSymbol, 5 /* PublicMember */); + } else { + variableSymbol.setContainer(parent); + } + } else if (replaceProperty) { + parent.removeMember(previousProperty); + parent.addMember(variableSymbol, linkKind); + } + + variableSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindPropertyDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.getFlags(); + var declKind = propertyDeclaration.getKind(); + var propDeclAST = this.semanticInfo.getASTForDecl(propertyDeclaration); + + var isStatic = false; + var isOptional = false; + + var linkKind = 5 /* PublicMember */; + + var propertySymbol = null; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + linkKind = 6 /* PrivateMember */; + } + + if (TypeScript.hasFlag(declFlags, 128 /* Optional */)) { + isOptional = true; + } + + var declName = propertyDeclaration.getName(); + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + if (parent.isClass() && isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + propertySymbol = parent.findMember(declName, false); + + if (propertySymbol && (!this.reBindingAfterChange || this.symbolIsRedeclaration(propertySymbol))) { + var span = propertyDeclaration.getSpan(); + + propertyDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), span.start(), span.length(), 69 /* Duplicate_identifier__0_ */, [propertyDeclaration.getDisplayName()])); + + propertySymbol = null; + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + if (this.reBindingAfterChange && propertySymbol) { + var decls = propertySymbol.getDeclarations(); + var scriptName = propertyDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + propertySymbol.removeDeclaration(decls[j]); + } + } + + propertySymbol.setUnresolved(); + } + + var classTypeSymbol; + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(propDeclAST.id, TypeScript.SymbolAndDiagnostics.fromSymbol(propertySymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(propDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(propertySymbol)); + + if (isOptional) { + propertySymbol.setIsOptional(); + } + + if (parent && !parentHadSymbol) { + if (parent.isClass()) { + classTypeSymbol = parent; + + classTypeSymbol.addMember(propertySymbol, linkKind); + } else { + parent.addMember(propertySymbol, linkKind); + } + } + + propertySymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindParameterSymbols = function (funcDecl, funcType, signatureSymbol) { + var parameters = []; + var decl = null; + var argDecl = null; + var parameterSymbol = null; + var isProperty = false; + var params = new TypeScript.BlockIntrinsics(); + + if (funcDecl.arguments) { + for (var i = 0; i < funcDecl.arguments.members.length; i++) { + argDecl = funcDecl.arguments.members[i]; + decl = this.semanticInfo.getDeclForAST(argDecl); + isProperty = TypeScript.hasFlag(argDecl.getVarFlags(), 256 /* Property */); + parameterSymbol = new TypeScript.PullSymbol(argDecl.id.text, 2048 /* Parameter */); + + if (funcDecl.variableArgList && i === funcDecl.arguments.members.length - 1) { + parameterSymbol.setIsVarArg(); + } + + if (decl.getFlags() & 128 /* Optional */) { + parameterSymbol.setIsOptional(); + } + + if (params[argDecl.id.text]) { + decl.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), argDecl.minChar, argDecl.getLength(), 69 /* Duplicate_identifier__0_ */, [argDecl.id.actualText])); + } else { + params[argDecl.id.text] = true; + } + if (decl) { + if (isProperty) { + decl.ensureSymbolIsBound(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + valDecl.setSymbol(parameterSymbol); + parameterSymbol.addDeclaration(valDecl); + } + } else { + parameterSymbol.addDeclaration(decl); + decl.setSymbol(parameterSymbol); + } + } + + signatureSymbol.addParameter(parameterSymbol, parameterSymbol.getIsOptional()); + + if (signatureSymbol.isDefinition()) { + parameterSymbol.setContainer(funcType); + } + } + } + }; + + PullSymbolBinder.prototype.bindFunctionDeclarationToPullSymbol = function (functionDeclaration) { + var declKind = functionDeclaration.getKind(); + var declFlags = functionDeclaration.getFlags(); + var funcDeclAST = this.semanticInfo.getASTForDecl(functionDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = functionDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(functionDeclaration, true); + var parentDecl = functionDeclaration.getParentDecl(); + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var functionSymbol = null; + var functionTypeSymbol = null; + + if (parent) { + functionSymbol = parent.findMember(funcName, false); + + if (!functionSymbol) { + functionSymbol = parent.findContainedMember(funcName); + + if (functionSymbol) { + var declarations = functionSymbol.getDeclarations(); + + if (declarations.length) { + var funcSymbolParent = declarations[0].getParentDecl(); + + if ((parentDecl !== funcSymbolParent) && (!this.reBindingAfterChange || (funcSymbolParent.getDeclID() >= this.startingDeclForRebind))) { + functionSymbol = null; + } + } + } + } + } else if (!(functionDeclaration.getFlags() & 1 /* Exported */)) { + functionSymbol = findSymbolInContext(funcName, TypeScript.PullElementKind.SomeValue, functionDeclaration); + } + + if (functionSymbol && (functionSymbol.getKind() !== 16384 /* Function */ || (this.symbolIsRedeclaration(functionSymbol) && !isSignature && !functionSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + functionDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [functionDeclaration.getDisplayName()])); + functionSymbol = null; + } + + if (functionSymbol) { + functionTypeSymbol = functionSymbol.getType(); + parentHadSymbol = true; + } + + if (this.reBindingAfterChange && functionSymbol) { + var decls = functionSymbol.getDeclarations(); + var scriptName = functionDeclaration.getScriptName(); + var isGeneric = functionTypeSymbol.isGeneric(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + functionSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + decls = functionTypeSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + functionTypeSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (isGeneric) { + var specializations = functionTypeSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + } + + functionSymbol.invalidate(); + functionTypeSymbol.invalidate(); + } + + if (!functionSymbol) { + functionSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + } + + if (!functionTypeSymbol) { + functionTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + functionSymbol.setType(functionTypeSymbol); + } + + functionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionDeclaration); + functionTypeSymbol.addDeclaration(functionDeclaration); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + + if (parent && !parentHadSymbol) { + if (isExported) { + parent.addMember(functionSymbol, 5 /* PublicMember */); + } else { + functionSymbol.setContainer(parent); + } + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = functionTypeSymbol.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + functionTypeSymbol.removeCallSignature(callSigs[i], false); + } + + functionSymbol.invalidate(); + functionTypeSymbol.invalidate(); + functionTypeSymbol.recomputeCallSignatures(); + + if (isGeneric) { + var specializations = functionTypeSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + callSigs = specializations[j].getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + callSigs[i].invalidate(); + } + } + } + } + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + signature.addDeclaration(functionDeclaration); + functionDeclaration.setSignatureSymbol(signature); + + if (funcDeclAST.variableArgList) { + signature.setHasVariableParamList(); + } + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(functionDeclaration), functionTypeSymbol, signature); + + var typeParameters = functionDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + functionDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + functionTypeSymbol.addCallSignature(signature); + + if (!isSignature) { + } + + functionSymbol.setIsBound(this.bindingPhase); + + var otherDecls = this.findDeclsInContext(functionDeclaration, functionDeclaration.getKind(), false); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { + var declKind = functionExpressionDeclaration.getKind(); + var declFlags = functionExpressionDeclaration.getFlags(); + var funcExpAST = this.semanticInfo.getASTForDecl(functionExpressionDeclaration); + + var functionName = declKind == 131072 /* FunctionExpression */ ? (functionExpressionDeclaration).getFunctionExpressionName() : functionExpressionDeclaration.getName(); + var functionSymbol = new TypeScript.PullSymbol(functionName, 16384 /* Function */); + var functionTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + functionSymbol.setType(functionTypeSymbol); + + functionExpressionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionExpressionDeclaration); + functionTypeSymbol.addDeclaration(functionExpressionDeclaration); + + if (funcExpAST.name) { + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcExpAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + } + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcExpAST, TypeScript.SymbolAndDiagnostics.fromSymbol(functionSymbol)); + + var signature = new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + if (funcExpAST.variableArgList) { + signature.setHasVariableParamList(); + } + + var typeParameters = functionExpressionDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + functionExpressionDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionExpressionDeclaration); + functionExpressionDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(functionExpressionDeclaration), functionTypeSymbol, signature); + + functionTypeSymbol.addSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { + var declKind = functionTypeDeclaration.getKind(); + var declFlags = functionTypeDeclaration.getFlags(); + var funcTypeAST = this.semanticInfo.getASTForDecl(functionTypeDeclaration); + + var functionTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + functionTypeDeclaration.setSymbol(functionTypeSymbol); + functionTypeSymbol.addDeclaration(functionTypeDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcTypeAST, TypeScript.SymbolAndDiagnostics.fromSymbol(functionTypeSymbol)); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + if (funcTypeAST.variableArgList) { + signature.setHasVariableParamList(); + } + + var typeParameters = functionTypeDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + functionTypeDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionTypeDeclaration); + functionTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(functionTypeDeclaration), functionTypeSymbol, signature); + + functionTypeSymbol.addSignature(signature); + }; + + PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { + var declKind = methodDeclaration.getKind(); + var declFlags = methodDeclaration.getFlags(); + var methodAST = this.semanticInfo.getASTForDecl(methodDeclaration); + + var isPrivate = (declFlags & 2 /* Private */) !== 0; + var isStatic = (declFlags & 16 /* Static */) !== 0; + var isOptional = (declFlags & 128 /* Optional */) !== 0; + + var methodName = methodDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(methodDeclaration, true); + var parentHadSymbol = false; + + var cleanedPreviousDecls = false; + + var methodSymbol = null; + var methodTypeSymbol = null; + + var linkKind = isPrivate ? 6 /* PrivateMember */ : 5 /* PublicMember */; + + if (parent.isClass() && isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + methodSymbol = parent.findMember(methodName, false); + + if (methodSymbol && (methodSymbol.getKind() !== 65536 /* Method */ || (this.symbolIsRedeclaration(methodSymbol) && !isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + methodDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), methodAST.minChar, methodAST.getLength(), 69 /* Duplicate_identifier__0_ */, [methodDeclaration.getDisplayName()])); + methodSymbol = null; + } + + if (methodSymbol) { + methodTypeSymbol = methodSymbol.getType(); + parentHadSymbol = true; + } + + if (this.reBindingAfterChange && methodSymbol) { + var decls = methodSymbol.getDeclarations(); + var scriptName = methodDeclaration.getScriptName(); + var isGeneric = methodTypeSymbol.isGeneric(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + methodSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + decls = methodTypeSymbol.getDeclarations(); + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + methodTypeSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (isGeneric) { + var specializations = methodTypeSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + } + + methodSymbol.invalidate(); + methodTypeSymbol.invalidate(); + } + + if (!methodSymbol) { + methodSymbol = new TypeScript.PullSymbol(methodName, 65536 /* Method */); + } + + if (!methodTypeSymbol) { + methodTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + methodSymbol.setType(methodTypeSymbol); + } + + methodDeclaration.setSymbol(methodSymbol); + methodSymbol.addDeclaration(methodDeclaration); + methodTypeSymbol.addDeclaration(methodDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(methodAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(methodSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(methodAST, TypeScript.SymbolAndDiagnostics.fromSymbol(methodSymbol)); + + if (isOptional) { + methodSymbol.setIsOptional(); + } + + if (!parentHadSymbol) { + parent.addMember(methodSymbol, linkKind); + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = methodTypeSymbol.getCallSignatures(); + var constructSigs = methodTypeSymbol.getConstructSignatures(); + var indexSigs = methodTypeSymbol.getIndexSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + methodTypeSymbol.removeCallSignature(callSigs[i], false); + } + for (var i = 0; i < constructSigs.length; i++) { + methodTypeSymbol.removeConstructSignature(constructSigs[i], false); + } + for (var i = 0; i < indexSigs.length; i++) { + methodTypeSymbol.removeIndexSignature(indexSigs[i], false); + } + + methodSymbol.invalidate(); + methodTypeSymbol.invalidate(); + methodTypeSymbol.recomputeCallSignatures(); + methodTypeSymbol.recomputeConstructSignatures(); + methodTypeSymbol.recomputeIndexSignatures(); + + if (isGeneric) { + var specializations = methodTypeSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + callSigs = specializations[j].getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + callSigs[i].invalidate(); + } + } + } + } + + var sigKind = 1048576 /* CallSignature */; + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(sigKind) : new TypeScript.PullDefinitionSignatureSymbol(sigKind); + + if (methodAST.variableArgList) { + signature.setHasVariableParamList(); + } + + var typeParameters = methodDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + var typeParameterName; + var typeParameterAST; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterName = typeParameters[i].getName(); + typeParameterAST = this.semanticInfo.getASTForDecl(typeParameters[i]); + + typeParameter = signature.findTypeParameter(typeParameterName); + + if (!typeParameter) { + if (!typeParameterAST.constraint) { + typeParameter = this.findTypeParameterInCache(typeParameterName); + } + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName, true); + + if (!typeParameterAST.constraint) { + this.addTypeParameterToCache(typeParameter); + } + } + + signature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + methodDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(methodDeclaration); + methodDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(methodDeclaration), methodTypeSymbol, signature); + + methodTypeSymbol.addSignature(signature); + + if (!isSignature) { + } + + var otherDecls = this.findDeclsInContext(methodDeclaration, methodDeclaration.getKind(), false); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindConstructorDeclarationToPullSymbol = function (constructorDeclaration) { + var declKind = constructorDeclaration.getKind(); + var declFlags = constructorDeclaration.getFlags(); + var constructorAST = this.semanticInfo.getASTForDecl(constructorDeclaration); + + var constructorName = constructorDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(constructorDeclaration, true); + + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var constructorSymbol = parent.getConstructorMethod(); + var constructorTypeSymbol = null; + + var linkKind = 7 /* ConstructorMethod */; + + if (constructorSymbol && (constructorSymbol.getKind() !== 32768 /* ConstructorMethod */ || (!isSignature && constructorSymbol.getType() && constructorSymbol.getType().hasOwnConstructSignatures() && (constructorSymbol.getType()).getDefinitionSignature() && !constructorSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + constructorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), constructorAST.minChar, constructorAST.getLength(), 139 /* Multiple_constructor_implementations_are_not_allowed */, null)); + + constructorSymbol = null; + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.getType(); + + if (this.reBindingAfterChange) { + var decls = constructorSymbol.getDeclarations(); + var scriptName = constructorDeclaration.getScriptName(); + var isGeneric = constructorTypeSymbol.isGeneric(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + constructorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + decls = constructorTypeSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + constructorTypeSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (isGeneric) { + var specializations = constructorTypeSymbol.getKnownSpecializations(); + + for (var i = 0; i < specializations.length; i++) { + specializations[i].invalidate(); + } + } + + constructorSymbol.invalidate(); + constructorTypeSymbol.invalidate(); + } + } + + if (!constructorSymbol) { + constructorSymbol = new TypeScript.PullSymbol(constructorName, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullConstructorTypeSymbol(); + } + + parent.setConstructorMethod(constructorSymbol); + constructorSymbol.setType(constructorTypeSymbol); + + constructorDeclaration.setSymbol(constructorSymbol); + constructorSymbol.addDeclaration(constructorDeclaration); + constructorTypeSymbol.addDeclaration(constructorDeclaration); + this.semanticInfo.setSymbolAndDiagnosticsForAST(constructorAST, TypeScript.SymbolAndDiagnostics.fromSymbol(constructorSymbol)); + + if (parentHadSymbol && cleanedPreviousDecls) { + var constructSigs = constructorTypeSymbol.getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + constructorTypeSymbol.removeConstructSignature(constructSigs[i]); + } + + constructorSymbol.invalidate(); + constructorTypeSymbol.invalidate(); + constructorTypeSymbol.recomputeConstructSignatures(); + + if (isGeneric) { + var specializations = constructorTypeSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + constructSigs = specializations[j].getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + constructSigs[i].invalidate(); + } + } + } + } + + var constructSignature = isSignature ? new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */); + + constructSignature.setReturnType(parent); + + constructSignature.addDeclaration(constructorDeclaration); + constructorDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(constructorAST, constructorTypeSymbol, constructSignature); + + var typeParameters = constructorTypeSymbol.getTypeParameters(); + + for (var i = 0; i < typeParameters.length; i++) { + constructSignature.addTypeParameter(typeParameters[i]); + } + + if (constructorAST.variableArgList) { + constructSignature.setHasVariableParamList(); + } + + constructorTypeSymbol.addSignature(constructSignature); + + if (!isSignature) { + } + + var otherDecls = this.findDeclsInContext(constructorDeclaration, constructorDeclaration.getKind(), false); + + if (otherDecls && otherDecls.length) { + for (var i = 0; i < otherDecls.length; i++) { + otherDecls[i].ensureSymbolIsBound(); + } + } + }; + + PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { + var parent = this.getParent(constructSignatureDeclaration, true); + var constructorAST = this.semanticInfo.getASTForDecl(constructSignatureDeclaration); + + var constructSigs = parent.getConstructSignatures(); + + for (var i = 0; i < constructSigs.length; i++) { + if (constructSigs[i].getSymbolID() < this.startingSymbolForRebind) { + parent.removeConstructSignature(constructSigs[i], false); + } + } + + parent.recomputeConstructSignatures(); + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + if (constructorAST.variableArgList) { + constructSignature.setHasVariableParamList(); + } + + var typeParameters = constructSignatureDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructSignature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + constructSignature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + constructSignatureDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructSignature.addDeclaration(constructSignatureDeclaration); + constructSignatureDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(constructSignatureDeclaration), null, constructSignature); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(this.semanticInfo.getASTForDecl(constructSignatureDeclaration), TypeScript.SymbolAndDiagnostics.fromSymbol(constructSignature)); + + parent.addConstructSignature(constructSignature); + }; + + PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { + var parent = this.getParent(callSignatureDeclaration, true); + var callSignatureAST = this.semanticInfo.getASTForDecl(callSignatureDeclaration); + + var callSigs = parent.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + if (callSigs[i].getSymbolID() < this.startingSymbolForRebind) { + parent.removeCallSignature(callSigs[i], false); + } + } + + parent.recomputeCallSignatures(); + + var callSignature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */); + + if (callSignatureAST.variableArgList) { + callSignature.setHasVariableParamList(); + } + + var typeParameters = callSignatureDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = callSignature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + callSignature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + callSignatureDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + callSignature.addDeclaration(callSignatureDeclaration); + callSignatureDeclaration.setSignatureSymbol(callSignature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(callSignatureDeclaration), null, callSignature); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(this.semanticInfo.getASTForDecl(callSignatureDeclaration), TypeScript.SymbolAndDiagnostics.fromSymbol(callSignature)); + + parent.addCallSignature(callSignature); + }; + + PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { + var parent = this.getParent(indexSignatureDeclaration, true); + + var indexSigs = parent.getIndexSignatures(); + + for (var i = 0; i < indexSigs.length; i++) { + if (indexSigs[i].getSymbolID() < this.startingSymbolForRebind) { + parent.removeIndexSignature(indexSigs[i], false); + } + } + + parent.recomputeIndexSignatures(); + + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + + var typeParameters = indexSignatureDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = indexSignature.findTypeParameter(typeParameters[i].getName()); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].getName(), true); + + indexSignature.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + if (this.symbolIsRedeclaration(typeParameter)) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + indexSignatureDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), typeParameterAST.minChar, typeParameterAST.getLength(), 69 /* Duplicate_identifier__0_ */, [typeParameter.getName()])); + } + + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + if (typeParameterDecls[j].getDeclID() < this.startingDeclForRebind) { + typeParameter.removeDeclaration(typeParameterDecls[j]); + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + indexSignature.addDeclaration(indexSignatureDeclaration); + indexSignatureDeclaration.setSignatureSymbol(indexSignature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(indexSignatureDeclaration), null, indexSignature); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(this.semanticInfo.getASTForDecl(indexSignatureDeclaration), TypeScript.SymbolAndDiagnostics.fromSymbol(indexSignature)); + + parent.addIndexSignature(indexSignature); + }; + + PullSymbolBinder.prototype.bindGetAccessorDeclarationToPullSymbol = function (getAccessorDeclaration) { + var declKind = getAccessorDeclaration.getKind(); + var declFlags = getAccessorDeclaration.getFlags(); + var funcDeclAST = this.semanticInfo.getASTForDecl(getAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = getAccessorDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + var linkKind = 5 /* PublicMember */; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + linkKind = 6 /* PrivateMember */; + } + + var parent = this.getParent(getAccessorDeclaration, true); + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var accessorSymbol = null; + var getterSymbol = null; + var getterTypeSymbol = null; + + if (isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + getAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [getAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + } else { + getterSymbol = accessorSymbol.getGetter(); + + if (getterSymbol && (!this.reBindingAfterChange || this.symbolIsRedeclaration(getterSymbol))) { + getAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 84 /* Getter__0__already_declared */, [getAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + getterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && getterSymbol) { + getterTypeSymbol = getterSymbol.getType(); + } + + if (this.reBindingAfterChange && accessorSymbol) { + var decls = accessorSymbol.getDeclarations(); + var scriptName = getAccessorDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + accessorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (getterSymbol) { + decls = getterSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + getterSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + } + + accessorSymbol.invalidate(); + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!getterSymbol) { + getterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + getterTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + getterSymbol.setType(getterTypeSymbol); + + accessorSymbol.setGetter(getterSymbol); + } + + getAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(getAccessorDeclaration); + getterSymbol.addDeclaration(getAccessorDeclaration); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(getterSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(getterSymbol)); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol, linkKind); + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = getterTypeSymbol.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + getterTypeSymbol.removeCallSignature(callSigs[i], false); + } + + getterSymbol.invalidate(); + getterTypeSymbol.invalidate(); + getterTypeSymbol.recomputeCallSignatures(); + } + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + signature.addDeclaration(getAccessorDeclaration); + getAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(getAccessorDeclaration), getterTypeSymbol, signature); + + var typeParameters = getAccessorDeclaration.getTypeParameters(); + + if (typeParameters.length) { + getAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 86 /* Accessor_cannot_have_type_parameters */, null)); + } + + getterTypeSymbol.addSignature(signature); + + if (!isSignature) { + } + + getterSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { + var declKind = setAccessorDeclaration.getKind(); + var declFlags = setAccessorDeclaration.getFlags(); + var funcDeclAST = this.semanticInfo.getASTForDecl(setAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = setAccessorDeclaration.getName(); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + var linkKind = 5 /* PublicMember */; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 2 /* Private */)) { + linkKind = 6 /* PrivateMember */; + } + + var parent = this.getParent(setAccessorDeclaration, true); + var parentHadSymbol = false; + var cleanedPreviousDecls = false; + + var accessorSymbol = null; + var setterSymbol = null; + var setterTypeSymbol = null; + + if (isStatic) { + parent = (parent).getConstructorMethod().getType(); + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + setAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 69 /* Duplicate_identifier__0_ */, [setAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + } else { + setterSymbol = accessorSymbol.getSetter(); + + if (setterSymbol && (!this.reBindingAfterChange || this.symbolIsRedeclaration(setterSymbol))) { + setAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 85 /* Setter__0__already_declared */, [setAccessorDeclaration.getDisplayName()])); + accessorSymbol = null; + setterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && setterSymbol) { + setterTypeSymbol = setterSymbol.getType(); + } + + if (this.reBindingAfterChange && accessorSymbol) { + var decls = accessorSymbol.getDeclarations(); + var scriptName = setAccessorDeclaration.getScriptName(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + accessorSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + + if (setterSymbol) { + decls = setterSymbol.getDeclarations(); + + for (var j = 0; j < decls.length; j++) { + if (decls[j].getScriptName() === scriptName && decls[j].getDeclID() < this.startingDeclForRebind) { + setterSymbol.removeDeclaration(decls[j]); + + cleanedPreviousDecls = true; + } + } + } + + accessorSymbol.invalidate(); + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!setterSymbol) { + setterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + setterTypeSymbol = new TypeScript.PullFunctionTypeSymbol(); + + setterSymbol.setType(setterTypeSymbol); + + accessorSymbol.setSetter(setterSymbol); + } + + setAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(setAccessorDeclaration); + setterSymbol.addDeclaration(setAccessorDeclaration); + + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST.name, TypeScript.SymbolAndDiagnostics.fromSymbol(setterSymbol)); + this.semanticInfo.setSymbolAndDiagnosticsForAST(funcDeclAST, TypeScript.SymbolAndDiagnostics.fromSymbol(setterSymbol)); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol, linkKind); + } + + if (parentHadSymbol && cleanedPreviousDecls) { + var callSigs = setterTypeSymbol.getCallSignatures(); + + for (var i = 0; i < callSigs.length; i++) { + setterTypeSymbol.removeCallSignature(callSigs[i], false); + } + + setterSymbol.invalidate(); + setterTypeSymbol.invalidate(); + setterTypeSymbol.recomputeCallSignatures(); + } + + var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + + signature.addDeclaration(setAccessorDeclaration); + setAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(this.semanticInfo.getASTForDecl(setAccessorDeclaration), setterTypeSymbol, signature); + + var typeParameters = setAccessorDeclaration.getTypeParameters(); + + if (typeParameters.length) { + setAccessorDeclaration.addDiagnostic(new TypeScript.SemanticDiagnostic(this.semanticInfo.getPath(), funcDeclAST.minChar, funcDeclAST.getLength(), 86 /* Accessor_cannot_have_type_parameters */, null)); + } + + setterTypeSymbol.addSignature(signature); + + if (!isSignature) { + } + + setterSymbol.setIsBound(this.bindingPhase); + }; + + PullSymbolBinder.prototype.bindCatchBlockPullSymbols = function (catchBlockDecl) { + }; + + PullSymbolBinder.prototype.bindWithBlockPullSymbols = function (withBlockDecl) { + }; + + PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl, rebind) { + if (typeof rebind === "undefined") { rebind = false; } + if (rebind) { + this.startingDeclForRebind = TypeScript.lastBoundPullDeclId; + this.startingSymbolForRebind = TypeScript.lastBoundPullSymbolID; + this.reBindingAfterChange = true; + } + + if (decl.isBound()) { + return; + } + + decl.setIsBound(true); + + switch (decl.getKind()) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + break; + + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + this.bindModuleDeclarationToPullSymbol(decl); + break; + + case 16 /* Interface */: + this.bindInterfaceDeclarationToPullSymbol(decl); + break; + + case 8 /* Class */: + this.bindClassDeclarationToPullSymbol(decl); + break; + + case 16384 /* Function */: + this.bindFunctionDeclarationToPullSymbol(decl); + break; + + case 1024 /* Variable */: + this.bindVariableDeclarationToPullSymbol(decl); + break; + + case 67108864 /* EnumMember */: + case 4096 /* Property */: + this.bindPropertyDeclarationToPullSymbol(decl); + break; + + case 65536 /* Method */: + this.bindMethodDeclarationToPullSymbol(decl); + break; + + case 32768 /* ConstructorMethod */: + this.bindConstructorDeclarationToPullSymbol(decl); + break; + + case 1048576 /* CallSignature */: + this.bindCallSignatureDeclarationToPullSymbol(decl); + break; + + case 2097152 /* ConstructSignature */: + this.bindConstructSignatureDeclarationToPullSymbol(decl); + break; + + case 4194304 /* IndexSignature */: + this.bindIndexSignatureDeclarationToPullSymbol(decl); + break; + + case 262144 /* GetAccessor */: + this.bindGetAccessorDeclarationToPullSymbol(decl); + break; + + case 524288 /* SetAccessor */: + this.bindSetAccessorDeclarationToPullSymbol(decl); + break; + + case 8388608 /* ObjectType */: + this.bindObjectTypeDeclarationToPullSymbol(decl); + break; + + case 16777216 /* FunctionType */: + this.bindFunctionTypeDeclarationToPullSymbol(decl); + break; + + case 33554432 /* ConstructorType */: + this.bindConstructorTypeDeclarationToPullSymbol(decl); + break; + + case 131072 /* FunctionExpression */: + this.bindFunctionExpressionToPullSymbol(decl); + break; + + case 256 /* TypeAlias */: + this.bindImportDeclaration(decl); + break; + + case 2048 /* Parameter */: + case 8192 /* TypeParameter */: + break; + + case 1073741824 /* CatchBlock */: + this.bindCatchBlockPullSymbols(decl); + + case 536870912 /* WithBlock */: + this.bindWithBlockPullSymbols(decl); + break; + + default: + throw new Error("Unrecognized type declaration"); + } + }; + + PullSymbolBinder.prototype.bindDeclsForUnit = function (filePath, rebind) { + if (typeof rebind === "undefined") { rebind = false; } + this.setUnit(filePath); + + var topLevelDecls = this.semanticInfo.getTopLevelDecls(); + + for (var i = 0; i < topLevelDecls.length; i++) { + this.bindDeclToPullSymbol(topLevelDecls[i], rebind); + } + }; + return PullSymbolBinder; + })(); + TypeScript.PullSymbolBinder = PullSymbolBinder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.linkID = 0; + + var IListItem = (function () { + function IListItem(value) { + this.value = value; + this.next = null; + this.prev = null; + } + return IListItem; + })(); + TypeScript.IListItem = IListItem; + + var LinkList = (function () { + function LinkList() { + this.head = null; + this.last = null; + this.length = 0; + } + LinkList.prototype.addItem = function (item) { + if (!this.head) { + this.head = new IListItem(item); + this.last = this.head; + } else { + this.last.next = new IListItem(item); + this.last.next.prev = this.last; + this.last = this.last.next; + } + + this.length++; + }; + + LinkList.prototype.find = function (p) { + var node = this.head; + var vals = []; + + while (node) { + if (p(node.value)) { + vals[vals.length] = node.value; + } + node = node.next; + } + + return vals; + }; + + LinkList.prototype.remove = function (p) { + var node = this.head; + var prev = null; + var next = null; + + while (node) { + if (p(node.value)) { + if (node === this.head) { + if (this.last === this.head) { + this.last = null; + } + + this.head = this.head.next; + + if (this.head) { + this.head.prev = null; + } + } else { + prev = node.prev; + next = node.next; + + if (prev) { + prev.next = next; + } + if (next) { + next.prev = prev; + } + + if (node === this.last) { + this.last = prev; + } + } + + this.length--; + } + node = node.next; + } + }; + + LinkList.prototype.update = function (map, context) { + var node = this.head; + + while (node) { + map(node.value, context); + + node = node.next; + } + }; + return LinkList; + })(); + TypeScript.LinkList = LinkList; + + var PullSymbolLink = (function () { + function PullSymbolLink(start, end, kind) { + this.start = start; + this.end = end; + this.kind = kind; + this.id = TypeScript.linkID++; + } + return PullSymbolLink; + })(); + TypeScript.PullSymbolLink = PullSymbolLink; + + (function (GraphUpdateKind) { + GraphUpdateKind[GraphUpdateKind["NoUpdate"] = 0] = "NoUpdate"; + + GraphUpdateKind[GraphUpdateKind["SymbolRemoved"] = 1] = "SymbolRemoved"; + GraphUpdateKind[GraphUpdateKind["SymbolAdded"] = 2] = "SymbolAdded"; + + GraphUpdateKind[GraphUpdateKind["TypeChanged"] = 3] = "TypeChanged"; + })(TypeScript.GraphUpdateKind || (TypeScript.GraphUpdateKind = {})); + var GraphUpdateKind = TypeScript.GraphUpdateKind; + + var PullSymbolUpdate = (function () { + function PullSymbolUpdate(updateKind, symbolToUpdate, updater) { + this.updateKind = updateKind; + this.symbolToUpdate = symbolToUpdate; + this.updater = updater; + } + return PullSymbolUpdate; + })(); + TypeScript.PullSymbolUpdate = PullSymbolUpdate; + + TypeScript.updateVersion = 0; + + var PullSymbolGraphUpdater = (function () { + function PullSymbolGraphUpdater(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + } + PullSymbolGraphUpdater.prototype.removeDecl = function (declToRemove) { + var declSymbol = declToRemove.getSymbol(); + + if (declSymbol) { + declSymbol.removeDeclaration(declToRemove); + + var childDecls = declToRemove.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.removeDecl(childDecls[i]); + } + + var remainingDecls = declSymbol.getDeclarations(); + + if (!remainingDecls.length) { + this.removeSymbol(declSymbol); + + this.semanticInfoChain.removeSymbolFromCache(declSymbol); + } else { + declSymbol.invalidate(); + } + } + + var valDecl = declToRemove.getValueDecl(); + + if (valDecl) { + this.removeDecl(valDecl); + } + + TypeScript.updateVersion++; + }; + + PullSymbolGraphUpdater.prototype.addDecl = function (declToAdd) { + var symbolToAdd = declToAdd.getSymbol(); + + if (symbolToAdd) { + this.addSymbol(symbolToAdd); + } + + TypeScript.updateVersion++; + }; + + PullSymbolGraphUpdater.prototype.removeSymbol = function (symbolToRemove) { + if (symbolToRemove.removeUpdateVersion === TypeScript.updateVersion) { + return; + } + + symbolToRemove.removeUpdateVersion = TypeScript.updateVersion; + + symbolToRemove.updateOutgoingLinks(propagateRemovalToOutgoingLinks, new PullSymbolUpdate(1 /* SymbolRemoved */, symbolToRemove, this)); + + symbolToRemove.updateIncomingLinks(propagateRemovalToIncomingLinks, new PullSymbolUpdate(1 /* SymbolRemoved */, symbolToRemove, this)); + + symbolToRemove.unsetContainer(); + + this.semanticInfoChain.removeSymbolFromCache(symbolToRemove); + + var container = symbolToRemove.getContainer(); + + if (container) { + container.removeMember(symbolToRemove); + this.semanticInfoChain.removeSymbolFromCache(symbolToRemove); + } + + if (symbolToRemove.isAccessor()) { + var getterSymbol = (symbolToRemove).getGetter(); + var setterSymbol = (symbolToRemove).getSetter(); + + if (getterSymbol) { + this.removeSymbol(getterSymbol); + } + + if (setterSymbol) { + this.removeSymbol(setterSymbol); + } + } + + symbolToRemove.removeAllLinks(); + }; + + PullSymbolGraphUpdater.prototype.addSymbol = function (symbolToAdd) { + if (symbolToAdd.addUpdateVersion === TypeScript.updateVersion) { + return; + } + + symbolToAdd.addUpdateVersion = TypeScript.updateVersion; + + symbolToAdd.updateOutgoingLinks(propagateAdditionToOutgoingLinks, new PullSymbolUpdate(2 /* SymbolAdded */, symbolToAdd, this)); + + symbolToAdd.updateIncomingLinks(propagateAdditionToIncomingLinks, new PullSymbolUpdate(2 /* SymbolAdded */, symbolToAdd, this)); + }; + + PullSymbolGraphUpdater.prototype.invalidateType = function (symbolWhoseTypeChanged) { + if (!symbolWhoseTypeChanged) { + return; + } + + if (symbolWhoseTypeChanged.isPrimitive()) { + return; + } + + if (symbolWhoseTypeChanged.typeChangeUpdateVersion === TypeScript.updateVersion) { + return; + } + + symbolWhoseTypeChanged.typeChangeUpdateVersion = TypeScript.updateVersion; + + symbolWhoseTypeChanged.updateOutgoingLinks(propagateChangedTypeToOutgoingLinks, new PullSymbolUpdate(3 /* TypeChanged */, symbolWhoseTypeChanged, this)); + + symbolWhoseTypeChanged.updateIncomingLinks(propagateChangedTypeToIncomingLinks, new PullSymbolUpdate(3 /* TypeChanged */, symbolWhoseTypeChanged, this)); + + if (symbolWhoseTypeChanged.getKind() === 4 /* Container */) { + var instanceSymbol = (symbolWhoseTypeChanged).getInstanceSymbol(); + + this.invalidateType(instanceSymbol); + } + + if (symbolWhoseTypeChanged.isResolved()) { + symbolWhoseTypeChanged.invalidate(); + } + + this.invalidateUnitsForSymbol(symbolWhoseTypeChanged); + }; + + PullSymbolGraphUpdater.prototype.invalidateUnitsForSymbol = function (symbol) { + var declarations = symbol.getDeclarations(); + + for (var i = 0; i < declarations.length; i++) { + this.semanticInfoChain.invalidateUnit(declarations[i].getScriptName()); + } + }; + return PullSymbolGraphUpdater; + })(); + TypeScript.PullSymbolGraphUpdater = PullSymbolGraphUpdater; + + function propagateRemovalToOutgoingLinks(link, update) { + var symbolToRemove = update.symbolToUpdate; + var affectedSymbol = link.end; + + if (affectedSymbol.removeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 2 /* ProvidesInferredType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + (symbolToRemove).removeSpecialization(affectedSymbol); + update.updater.removeSymbol(affectedSymbol); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.removeSymbol(affectedSymbol); + } else if (link.kind === 6 /* PrivateMember */) { + update.updater.removeSymbol(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 10 /* ContainedBy */) { + (affectedSymbol).removeMember(symbolToRemove); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 13 /* Parameter */) { + update.updater.removeSymbol(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } + + symbolToRemove.removeOutgoingLink(link); + } + TypeScript.propagateRemovalToOutgoingLinks = propagateRemovalToOutgoingLinks; + + function propagateRemovalToIncomingLinks(link, update) { + var symbolToRemove = update.symbolToUpdate; + var affectedSymbol = link.start; + + if (affectedSymbol.removeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 0 /* TypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 1 /* ContextuallyTypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + (affectedSymbol).removeSpecialization(symbolToRemove); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + (affectedSymbol).removeMember(symbolToRemove); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 6 /* PrivateMember */) { + (affectedSymbol).removeMember(symbolToRemove); + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 10 /* ContainedBy */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 11 /* Extends */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 12 /* Implements */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 13 /* Parameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 8 /* Aliases */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 9 /* ExportAliases */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateRemovalToIncomingLinks = propagateRemovalToIncomingLinks; + + function propagateAdditionToOutgoingLinks(link, update) { + var symbolToAdd = update.symbolToUpdate; + var affectedSymbol = link.end; + + if (affectedSymbol.addUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 10 /* ContainedBy */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 2 /* ProvidesInferredType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateAdditionToOutgoingLinks = propagateAdditionToOutgoingLinks; + + function propagateAdditionToIncomingLinks(link, update) { + var symbolToAdd = update.symbolToUpdate; + var affectedSymbol = link.start; + + if (affectedSymbol.addUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 0 /* TypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 1 /* ContextuallyTypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 11 /* Extends */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 12 /* Implements */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 8 /* Aliases */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 9 /* ExportAliases */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateAdditionToIncomingLinks = propagateAdditionToIncomingLinks; + + function propagateChangedTypeToOutgoingLinks(link, update) { + var symbolWhoseTypeChanged = update.symbolToUpdate; + var affectedSymbol = link.end; + + if (affectedSymbol.typeChangeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 2 /* ProvidesInferredType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 10 /* ContainedBy */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 21 /* SpecializedTo */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 15 /* CallSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 7 /* ConstructorMethod */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 16 /* ConstructSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateChangedTypeToOutgoingLinks = propagateChangedTypeToOutgoingLinks; + + function propagateChangedTypeToIncomingLinks(link, update) { + var symbolWhoseTypeChanged = update.symbolToUpdate; + var affectedSymbol = link.start; + + if (affectedSymbol.typeChangeUpdateVersion === TypeScript.updateVersion || affectedSymbol.isPrimitive()) { + return; + } + + if (link.kind === 0 /* TypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 1 /* ContextuallyTypedAs */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 18 /* TypeParameter */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 19 /* TypeArgument */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 22 /* TypeConstraint */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 5 /* PublicMember */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 17 /* IndexSignature */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 11 /* Extends */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 12 /* Implements */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 14 /* ReturnType */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 8 /* Aliases */) { + update.updater.invalidateType(affectedSymbol); + } else if (link.kind === 9 /* ExportAliases */) { + update.updater.invalidateType(affectedSymbol); + } + } + TypeScript.propagateChangedTypeToIncomingLinks = propagateChangedTypeToIncomingLinks; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SemanticDiagnostic = (function (_super) { + __extends(SemanticDiagnostic, _super); + function SemanticDiagnostic() { + _super.apply(this, arguments); + } + SemanticDiagnostic.equals = function (diagnostic1, diagnostic2) { + return TypeScript.Diagnostic.equals(diagnostic1, diagnostic2); + }; + return SemanticDiagnostic; + })(TypeScript.Diagnostic); + TypeScript.SemanticDiagnostic = SemanticDiagnostic; + + function getDiagnosticsFromEnclosingDecl(enclosingDecl, errors) { + var declErrors = enclosingDecl.getDiagnostics(); + + if (declErrors) { + for (var i = 0; i < declErrors.length; i++) { + errors[errors.length] = declErrors[i]; + } + } + + var childDecls = enclosingDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + getDiagnosticsFromEnclosingDecl(childDecls[i], errors); + } + } + TypeScript.getDiagnosticsFromEnclosingDecl = getDiagnosticsFromEnclosingDecl; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullHelpers) { + function getSignatureForFuncDecl(funcDecl, semanticInfo) { + var functionDecl = semanticInfo.getDeclForAST(funcDecl); + var funcSymbol = functionDecl.getSymbol(); + + if (!funcSymbol) { + funcSymbol = functionDecl.getSignatureSymbol(); + } + + var functionSignature = null; + var typeSymbolWithAllSignatures = null; + if (funcSymbol.isSignature()) { + functionSignature = funcSymbol; + var parent = functionDecl.getParentDecl(); + typeSymbolWithAllSignatures = parent.getSymbol().getType(); + } else { + functionSignature = functionDecl.getSignatureSymbol(); + typeSymbolWithAllSignatures = funcSymbol.getType(); + } + var signatures; + if (funcDecl.isConstructor || funcDecl.isConstructMember()) { + signatures = typeSymbolWithAllSignatures.getConstructSignatures(); + } else if (funcDecl.isIndexerMember()) { + signatures = typeSymbolWithAllSignatures.getIndexSignatures(); + } else { + signatures = typeSymbolWithAllSignatures.getCallSignatures(); + } + return { + signature: functionSignature, + allSignatures: signatures + }; + } + PullHelpers.getSignatureForFuncDecl = getSignatureForFuncDecl; + + function getAccessorSymbol(getterOrSetter, semanticInfoChain, unitPath) { + var functionDecl = semanticInfoChain.getDeclForAST(getterOrSetter, unitPath); + var getterOrSetterSymbol = functionDecl.getSymbol(); + + return getterOrSetterSymbol; + } + PullHelpers.getAccessorSymbol = getAccessorSymbol; + + function getGetterAndSetterFunction(funcDecl, semanticInfoChain, unitPath) { + var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, semanticInfoChain, unitPath); + var result = { + getter: null, + setter: null + }; + var getter = accessorSymbol.getGetter(); + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + result.getter = semanticInfoChain.getASTForDecl(getterDecl); + } + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + result.setter = semanticInfoChain.getASTForDecl(setterDecl); + } + + return result; + } + PullHelpers.getGetterAndSetterFunction = getGetterAndSetterFunction; + + function symbolIsEnum(source) { + return source && ((source.getKind() & (64 /* Enum */ | 67108864 /* EnumMember */)) || source.hasFlag(131072 /* InitializedEnum */)); + } + PullHelpers.symbolIsEnum = symbolIsEnum; + })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); + var PullHelpers = TypeScript.PullHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var incrementalAst = true; + var SyntaxPositionMap = (function () { + function SyntaxPositionMap(node) { + this.position = 0; + this.elementToPosition = TypeScript.Collections.createHashTable(2048, TypeScript.Collections.identityHashCode); + this.process(node); + } + SyntaxPositionMap.prototype.process = function (element) { + if (element !== null) { + if (element.isToken()) { + this.elementToPosition.add(element, this.position); + this.position += element.fullWidth(); + } else { + if (element.isNode() || (element.isList() && (element).childCount() > 0) || (element.isSeparatedList() && (element).childCount() > 0)) { + this.elementToPosition.add(element, this.position); + } + + for (var i = 0, n = element.childCount(); i < n; i++) { + this.process(element.childAt(i)); + } + } + } + }; + + SyntaxPositionMap.create = function (node) { + var map = new SyntaxPositionMap(node); + return map; + }; + + SyntaxPositionMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxPositionMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxPositionMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxPositionMap.prototype.fullEnd = function (element) { + return this.fullStart(element) + element.fullWidth(); + }; + return SyntaxPositionMap; + })(); + TypeScript.SyntaxPositionMap = SyntaxPositionMap; + + var SyntaxTreeToAstVisitor = (function () { + function SyntaxTreeToAstVisitor(syntaxPositionMap, fileName, lineMap, compilationSettings) { + this.syntaxPositionMap = syntaxPositionMap; + this.fileName = fileName; + this.lineMap = lineMap; + this.compilationSettings = compilationSettings; + this.position = 0; + this.requiresExtendsBlock = false; + this.previousTokenTrailingComments = null; + this.isParsingAmbientModule = false; + this.containingModuleHasExportAssignment = false; + this.isParsingDeclareFile = TypeScript.isDTSFile(fileName); + } + SyntaxTreeToAstVisitor.visit = function (syntaxTree, fileName, compilationSettings) { + var map = SyntaxTreeToAstVisitor.checkPositions ? SyntaxPositionMap.create(syntaxTree.sourceUnit()) : null; + var visitor = new SyntaxTreeToAstVisitor(map, fileName, syntaxTree.lineMap(), compilationSettings); + return syntaxTree.sourceUnit().accept(visitor); + }; + + SyntaxTreeToAstVisitor.prototype.assertElementAtPosition = function (element) { + if (SyntaxTreeToAstVisitor.checkPositions) { + TypeScript.Debug.assert(this.position === this.syntaxPositionMap.fullStart(element)); + } + }; + + SyntaxTreeToAstVisitor.prototype.movePast = function (element) { + if (element !== null) { + this.assertElementAtPosition(element); + this.position += element.fullWidth(); + } + }; + + SyntaxTreeToAstVisitor.prototype.moveTo = function (element1, element2) { + if (element2 !== null) { + this.position += TypeScript.Syntax.childOffset(element1, element2); + } + }; + + SyntaxTreeToAstVisitor.prototype.applyDelta = function (ast, delta) { + var _this = this; + if (delta === 0) { + return; + } + + var applyDelta = function (ast) { + if (ast.minChar !== -1) { + ast.minChar += delta; + } + if (ast.limChar !== -1) { + ast.limChar += delta; + } + }; + + var applyDeltaToComments = function (comments) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + applyDelta(comment); + comment.minLine = _this.lineMap.getLineNumberFromPosition(comment.minChar); + comment.limLine = _this.lineMap.getLineNumberFromPosition(comment.limChar); + } + } + }; + + var pre = function (cur, parent, walker) { + applyDelta(cur); + applyDeltaToComments(cur.preComments); + applyDeltaToComments(cur.postComments); + + return cur; + }; + + TypeScript.getAstWalkerFactory().walk(ast, pre); + }; + + SyntaxTreeToAstVisitor.prototype.setSpan = function (span, fullStart, element) { + var desiredMinChar = fullStart + element.leadingTriviaWidth(); + var desiredLimChar = desiredMinChar + element.width(); + + this.setSpanExplicit(span, desiredMinChar, desiredLimChar); + + span.trailingTriviaWidth = element.trailingTriviaWidth(); + }; + + SyntaxTreeToAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + if (span.minChar !== -1) { + TypeScript.Debug.assert(span.limChar !== -1); + TypeScript.Debug.assert((span).nodeType !== undefined); + + var delta = start - span.minChar; + this.applyDelta(span, delta); + + span.limChar = end; + + TypeScript.Debug.assert(span.minChar === start); + TypeScript.Debug.assert(span.limChar === end); + } else { + TypeScript.Debug.assert(span.limChar === -1); + + span.minChar = start; + span.limChar = end; + } + + TypeScript.Debug.assert(!isNaN(span.minChar)); + TypeScript.Debug.assert(!isNaN(span.limChar)); + TypeScript.Debug.assert(span.minChar !== -1); + TypeScript.Debug.assert(span.limChar !== -1); + }; + + SyntaxTreeToAstVisitor.prototype.identifierFromToken = function (token, isOptional, useValueText) { + this.assertElementAtPosition(token); + + var result = null; + if (token.fullWidth() === 0) { + result = new TypeScript.MissingIdentifier(); + } else { + result = new TypeScript.Identifier(token.text()); + result.text = useValueText ? token.valueText() : result.text; + if (result.text == SyntaxTreeToAstVisitor.protoString) { + result.text = SyntaxTreeToAstVisitor.protoSubstitutionString; + } + } + + if (isOptional) { + result.setFlags(result.getFlags() | 4 /* OptionalName */); + } + + var start = this.position + token.leadingTriviaWidth(); + this.setSpanExplicit(result, start, start + token.width()); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getAST = function (element) { + if (this.previousTokenTrailingComments !== null) { + return null; + } + + if (incrementalAst) { + var result = (element)._ast; + return result ? result : null; + } else { + return null; + } + }; + + SyntaxTreeToAstVisitor.prototype.setAST = function (element, ast) { + if (incrementalAst) { + (element)._ast = ast; + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSyntaxList = function (list) { + var start = this.position; + var result = this.getAST(list); + if (result) { + this.movePast(list); + } else { + result = new TypeScript.ASTList(); + + for (var i = 0, n = list.childCount(); i < n; i++) { + result.append(list.childAt(i).accept(this)); + } + + if (n > 0) { + this.setAST(list, result); + } + } + + this.setSpan(result, start, list); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var start = this.position; + var result = this.getAST(list); + if (result) { + this.movePast(list); + } else { + result = new TypeScript.ASTList(); + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i % 2 === 0) { + result.append(list.childAt(i).accept(this)); + this.previousTokenTrailingComments = null; + } else { + var separatorToken = list.childAt(i); + this.previousTokenTrailingComments = this.convertTokenTrailingComments(separatorToken, this.position + separatorToken.leadingTriviaWidth() + separatorToken.width()); + this.movePast(separatorToken); + } + } + + result.postComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + if (n > 0) { + this.setAST(list, result); + } + } + + this.setSpan(result, start, list); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.createRef = function (text, minChar) { + var id = new TypeScript.Identifier(text); + id.minChar = minChar; + return id; + }; + + SyntaxTreeToAstVisitor.prototype.convertComment = function (trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia.fullText(), trivia.kind() === 6 /* MultiLineCommentTrivia */, hasTrailingNewLine); + + comment.minChar = commentStartPosition; + comment.limChar = commentStartPosition + trivia.fullWidth(); + comment.minLine = this.lineMap.getLineNumberFromPosition(comment.minChar); + comment.limLine = this.lineMap.getLineNumberFromPosition(comment.limChar); + + return comment; + }; + + SyntaxTreeToAstVisitor.prototype.convertComments = function (triviaList, commentStartPosition) { + var result = []; + + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result.push(this.convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + + commentStartPosition += trivia.fullWidth(); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.mergeComments = function (comments1, comments2) { + if (comments1 === null) { + return comments2; + } + + if (comments2 === null) { + return comments1; + } + + return comments1.concat(comments2); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenLeadingComments = function (token, commentStartPosition) { + if (token === null) { + return null; + } + + var preComments = token.hasLeadingComment() ? this.convertComments(token.leadingTrivia(), commentStartPosition) : null; + + var previousTokenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + return this.mergeComments(previousTokenTrailingComments, preComments); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenTrailingComments = function (token, commentStartPosition) { + if (token === null || !token.hasTrailingComment() || token.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(token.trailingTrivia(), commentStartPosition); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeLeadingComments = function (node, nodeStart) { + return this.convertTokenLeadingComments(node.firstToken(), nodeStart); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeTrailingComments = function (node, nodeStart) { + return this.convertTokenTrailingComments(node.lastToken(), nodeStart + node.leadingTriviaWidth() + node.width()); + }; + + SyntaxTreeToAstVisitor.prototype.visitToken = function (token) { + this.assertElementAtPosition(token); + + var result = this.getAST(token); + var fullStart = this.position; + + if (result) { + this.movePast(token); + } else { + if (token.kind() === 35 /* ThisKeyword */) { + result = new TypeScript.ThisExpression(); + } else if (token.kind() === 50 /* SuperKeyword */) { + result = new TypeScript.SuperExpression(); + } else if (token.kind() === 37 /* TrueKeyword */) { + result = new TypeScript.LiteralExpression(3 /* TrueLiteral */); + } else if (token.kind() === 24 /* FalseKeyword */) { + result = new TypeScript.LiteralExpression(4 /* FalseLiteral */); + } else if (token.kind() === 32 /* NullKeyword */) { + result = new TypeScript.LiteralExpression(8 /* NullLiteral */); + } else if (token.kind() === 14 /* StringLiteral */) { + result = new TypeScript.StringLiteral(token.text(), token.valueText()); + } else if (token.kind() === 12 /* RegularExpressionLiteral */) { + result = new TypeScript.RegexLiteral(token.text()); + } else if (token.kind() === 13 /* NumericLiteral */) { + var preComments = this.convertTokenLeadingComments(token, fullStart); + + var value = token.text().indexOf(".") > 0 ? parseFloat(token.text()) : parseInt(token.text()); + result = new TypeScript.NumberLiteral(value, token.text()); + + result.preComments = preComments; + } else { + result = this.identifierFromToken(token, false, true); + } + + this.movePast(token); + } + + var start = fullStart + token.leadingTriviaWidth(); + this.setAST(token, result); + this.setSpanExplicit(result, start, start + token.width()); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getLeadingComments = function (node) { + var firstToken = node.firstToken(); + var result = []; + + if (firstToken.hasLeadingComment()) { + var leadingTrivia = firstToken.leadingTrivia(); + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.isComment()) { + result.push(trivia); + } + } + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.hasTopLevelImportOrExport = function (node) { + var firstToken; + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var moduleElement = node.moduleElements.childAt(i); + + firstToken = moduleElement.firstToken(); + if (firstToken !== null && firstToken.kind() === 47 /* ExportKeyword */) { + return true; + } + + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + return true; + } + } + } + + var leadingComments = this.getLeadingComments(node); + for (var i = 0, n = leadingComments.length; i < n; i++) { + var trivia = leadingComments[i]; + + if (TypeScript.getImplicitImport(trivia.fullText())) { + return true; + } + } + + return false; + }; + + SyntaxTreeToAstVisitor.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s* 0; + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setVarFlags(result.getVarFlags() | 1 /* Exported */); + } else { + result.setVarFlags(result.getVarFlags() & ~1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + result.setVarFlags(result.getVarFlags() | 8 /* Ambient */); + } else { + result.setVarFlags(result.getVarFlags() & ~8 /* Ambient */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + + var extendsList = null; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + var heritageClause = node.heritageClauses.childAt(i); + if (i === 0) { + extendsList = heritageClause.accept(this); + } else { + this.movePast(heritageClause); + } + } + + this.movePast(node.body.openBraceToken); + var members = this.visitSeparatedSyntaxList(node.body.typeMembers); + + this.movePast(node.body.closeBraceToken); + + result = new TypeScript.InterfaceDeclaration(name, typeParameters, members, extendsList, null); + + result.preComments = preComments; + result.postComments = postComments; + } + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setVarFlags(result.getVarFlags() | 1 /* Exported */); + } else { + result.setVarFlags(result.getVarFlags() & ~1 /* Exported */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitHeritageClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + result = new TypeScript.ASTList(); + + this.movePast(node.extendsOrImplementsKeyword); + for (var i = 0, n = node.typeNames.childCount(); i < n; i++) { + if (i % 2 === 1) { + this.movePast(node.typeNames.childAt(i)); + } else { + var type = this.visitType(node.typeNames.childAt(i)).term; + result.append(type); + } + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getModuleNames = function (node) { + var result = []; + + if (node.stringLiteral !== null) { + result.push(this.identifierFromToken(node.stringLiteral, false, false)); + this.movePast(node.stringLiteral); + } else { + this.getModuleNamesHelper(node.moduleName, result); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getModuleNamesHelper = function (name, result) { + this.assertElementAtPosition(name); + + if (name.kind() === 122 /* QualifiedName */) { + var qualifiedName = name; + this.getModuleNamesHelper(qualifiedName.left, result); + this.movePast(qualifiedName.dotToken); + result.push(this.identifierFromToken(qualifiedName.right, false, false)); + this.movePast(qualifiedName.right); + } else { + result.push(this.identifierFromToken(name, false, false)); + this.movePast(name); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.moduleKeyword); + this.movePast(node.moduleKeyword); + var names = this.getModuleNames(node); + this.movePast(node.openBraceToken); + + var savedIsParsingAmbientModule = this.isParsingAmbientModule; + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingDeclareFile) { + this.isParsingAmbientModule = true; + } + + var savedContainingModuleHasExportAssignment = this.containingModuleHasExportAssignment; + this.containingModuleHasExportAssignment = TypeScript.ArrayUtilities.any(node.moduleElements.toArray(), function (m) { + return m.kind() === 134 /* ExportAssignment */; + }); + + var members = this.visitSyntaxList(node.moduleElements); + + this.isParsingAmbientModule = savedIsParsingAmbientModule; + this.containingModuleHasExportAssignment = savedContainingModuleHasExportAssignment; + + var closeBracePosition = this.position; + this.movePast(node.closeBraceToken); + var closeBraceSpan = new TypeScript.ASTSpan(); + this.setSpan(closeBraceSpan, closeBracePosition, node.closeBraceToken); + + for (var i = names.length - 1; i >= 0; i--) { + var innerName = names[i]; + + result = new TypeScript.ModuleDeclaration(innerName, members, closeBraceSpan); + this.setSpan(result, start, node); + + result.preComments = preComments; + result.postComments = postComments; + + preComments = null; + postComments = null; + + if (i) { + result.setModuleFlags(result.getModuleFlags() | 1 /* Exported */); + } else if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setModuleFlags(result.getModuleFlags() | 1 /* Exported */); + } + + members = new TypeScript.ASTList(); + members.append(result); + } + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + result.setModuleFlags(result.getModuleFlags() | 8 /* Ambient */); + } else { + result.setModuleFlags(result.getModuleFlags() & ~8 /* Ambient */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.hasDotDotDotParameter = function (parameters) { + for (var i = 0, n = parameters.nonSeparatorCount(); i < n; i++) { + if ((parameters.nonSeparatorAt(i)).dotDotDotToken) { + return true; + } + } + + return false; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + + this.movePast(node.identifier); + + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + result = new TypeScript.FunctionDeclaration(name, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + if (node.semicolonToken) { + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + } + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + result.setFunctionFlags(result.getFunctionFlags() | 1 /* Exported */); + } else { + result.setFunctionFlags(result.getFunctionFlags() & ~1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + result.setFunctionFlags(result.getFunctionFlags() | 8 /* Ambient */); + } else { + result.setFunctionFlags(result.getFunctionFlags() & ~8 /* Ambient */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + + this.movePast(node.openBraceToken); + var members = new TypeScript.ASTList(); + + var lastValue = null; + var memberNames = []; + var memberName; + + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + if (i % 2 === 1) { + this.movePast(node.enumElements.childAt(i)); + } else { + var enumElement = node.enumElements.childAt(i); + + var memberValue = null; + + memberName = this.identifierFromToken(enumElement.propertyName, false, true); + this.movePast(enumElement.propertyName); + + if (enumElement.equalsValueClause !== null) { + memberValue = enumElement.equalsValueClause.accept(this); + lastValue = null; + } + + var memberStart = this.position; + + if (memberValue === null) { + if (lastValue === null) { + memberValue = new TypeScript.NumberLiteral(0, "0"); + lastValue = memberValue; + } else { + var nextValue = lastValue.value + 1; + memberValue = new TypeScript.NumberLiteral(nextValue, nextValue.toString()); + lastValue = memberValue; + } + } + + var declarator = new TypeScript.VariableDeclarator(memberName); + declarator.init = memberValue; + declarator.isImplicitlyInitialized = enumElement.equalsValueClause === null; + + declarator.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, -1), 0); + declarator.setVarFlags(declarator.getVarFlags() | 256 /* Property */); + this.setSpanExplicit(declarator, memberStart, this.position); + + if (memberValue.nodeType === 7 /* NumericLiteral */) { + declarator.setVarFlags(declarator.getVarFlags() | 4096 /* Constant */); + } else if (memberValue.nodeType === 69 /* LeftShiftExpression */) { + var binop = memberValue; + if (binop.operand1.nodeType === 7 /* NumericLiteral */ && binop.operand2.nodeType === 7 /* NumericLiteral */) { + declarator.setVarFlags(declarator.getVarFlags() | 4096 /* Constant */); + } + } else if (memberValue.nodeType === 20 /* Name */) { + var nameNode = memberValue; + for (var j = 0; j < memberNames.length; j++) { + memberName = memberNames[j]; + if (memberName.text === nameNode.text) { + declarator.setVarFlags(declarator.getVarFlags() | 4096 /* Constant */); + break; + } + } + } + + var declarators = new TypeScript.ASTList(); + declarators.append(declarator); + var declaration = new TypeScript.VariableDeclaration(declarators); + this.setSpanExplicit(declaration, memberStart, this.position); + + var statement = new TypeScript.VariableStatement(declaration); + statement.setFlags(16 /* EnumElement */); + this.setSpanExplicit(statement, memberStart, this.position); + + members.append(statement); + memberNames.push(memberName); + + declarator.setVarFlags(declarator.getVarFlags() | 1 /* Exported */); + } + } + + var closeBracePosition = this.position; + this.movePast(node.closeBraceToken); + var closeBraceSpan = new TypeScript.ASTSpan(); + this.setSpan(closeBraceSpan, closeBracePosition, node.closeBraceToken); + + var modDecl = new TypeScript.ModuleDeclaration(name, members, closeBraceSpan); + this.setSpan(modDecl, start, node); + + modDecl.preComments = preComments; + modDecl.postComments = postComments; + modDecl.setModuleFlags(modDecl.getModuleFlags() | 128 /* IsEnum */); + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + modDecl.setModuleFlags(modDecl.getModuleFlags() | 1 /* Exported */); + } + + return modDecl; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumElement = function (node) { + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxTreeToAstVisitor.prototype.visitImportDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.equalsToken); + var alias = node.moduleReference.accept(this); + this.movePast(node.semicolonToken); + + result = new TypeScript.ImportDeclaration(name, alias); + + result.preComments = preComments; + result.postComments = postComments; + result.isDynamicImport = node.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExportAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.identifier); + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.semicolonToken); + + result = new TypeScript.ExportAssignment(name); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var preComments = null; + if (node.modifiers.childCount() > 0) { + preComments = this.convertTokenLeadingComments(node.modifiers.firstToken(), start); + } + + this.moveTo(node, node.variableDeclaration); + + var declaration = node.variableDeclaration.accept(this); + this.movePast(node.semicolonToken); + + for (var i = 0, n = declaration.declarators.members.length; i < n; i++) { + var varDecl = declaration.declarators.members[i]; + + if (i === 0) { + varDecl.preComments = this.mergeComments(preComments, varDecl.preComments); + } + + if (!this.containingModuleHasExportAssignment && (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 47 /* ExportKeyword */) || this.isParsingAmbientModule)) { + varDecl.setVarFlags(varDecl.getVarFlags() | 1 /* Exported */); + } else { + varDecl.setVarFlags(varDecl.getVarFlags() & ~1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 64 /* DeclareKeyword */) || this.isParsingAmbientModule || this.isParsingDeclareFile) { + varDecl.setVarFlags(varDecl.getVarFlags() | 8 /* Ambient */); + } else { + varDecl.setVarFlags(varDecl.getVarFlags() & ~8 /* Ambient */); + } + } + + var result = new TypeScript.VariableStatement(declaration); + + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.variableDeclarators); + var variableDecls = this.visitSeparatedSyntaxList(node.variableDeclarators); + + for (var i = 0; i < variableDecls.members.length; i++) { + if (i === 0) { + variableDecls.members[i].preComments = preComments; + variableDecls.members[i].postComments = postComments; + } + } + + var result = new TypeScript.VariableDeclaration(variableDecls); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclarator = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var name = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + var result = new TypeScript.VariableDeclarator(name); + this.setSpan(result, start, node); + + result.typeExpr = typeExpr; + result.init = init; + if (init && init.nodeType === 12 /* FunctionDeclaration */) { + var funcDecl = init; + funcDecl.hint = name.actualText; + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEqualsValueClause = function (node) { + this.assertElementAtPosition(node); + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(node.equalsToken, this.position + node.equalsToken.leadingTriviaWidth() + node.equalsToken.width()); + + this.movePast(node.equalsToken); + var result = node.value.accept(this); + + this.previousTokenTrailingComments = null; + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getUnaryExpressionNodeType = function (kind) { + switch (kind) { + case 163 /* PlusExpression */: + return 26 /* PlusExpression */; + case 164 /* NegateExpression */: + return 27 /* NegateExpression */; + case 165 /* BitwiseNotExpression */: + return 72 /* BitwiseNotExpression */; + case 166 /* LogicalNotExpression */: + return 73 /* LogicalNotExpression */; + case 167 /* PreIncrementExpression */: + return 74 /* PreIncrementExpression */; + case 168 /* PreDecrementExpression */: + return 75 /* PreDecrementExpression */; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.operatorToken); + var operand = node.operand.accept(this); + + result = new TypeScript.UnaryExpression(this.getUnaryExpressionNodeType(node.kind()), operand); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.isOnSingleLine = function (start, end) { + return this.lineMap.getLineNumberFromPosition(start) === this.lineMap.getLineNumberFromPosition(end); + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var openStart = this.position + node.openBracketToken.leadingTriviaWidth(); + this.movePast(node.openBracketToken); + + var expressions = this.visitSeparatedSyntaxList(node.expressions); + + var closeStart = this.position + node.closeBracketToken.leadingTriviaWidth(); + this.movePast(node.closeBracketToken); + + TypeScript.Debug.assert(expressions !== null); + result = new TypeScript.UnaryExpression(21 /* ArrayLiteralExpression */, expressions); + + if (this.isOnSingleLine(openStart, closeStart)) { + result.setFlags(result.getFlags() | 2 /* SingleLine */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitOmittedExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + result = new TypeScript.OmittedExpression(); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.openParenToken); + var expr = node.expression.accept(this); + this.movePast(node.closeParenToken); + + result = new TypeScript.ParenthesizedExpression(expr); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.getArrowFunctionStatements = function (body) { + if (body.kind() === 145 /* Block */) { + return body.accept(this); + } else { + var statements = new TypeScript.ASTList(); + var expression = body.accept(this); + var returnStatement = new TypeScript.ReturnStatement(expression); + + returnStatement.preComments = expression.preComments; + expression.preComments = null; + + statements.append(returnStatement); + var block = new TypeScript.Block(statements); + block.closeBraceSpan = statements.members[0]; + return block; + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.equalsGreaterThanToken); + + var parameters = new TypeScript.ASTList(); + + var parameter = new TypeScript.Parameter(identifier); + this.setSpanExplicit(parameter, identifier.minChar, identifier.limChar); + + parameters.append(parameter); + + var statements = this.getArrowFunctionStatements(node.body); + + result = new TypeScript.FunctionDeclaration(null, statements, false, null, parameters, 12 /* FunctionDeclaration */); + + result.returnTypeAnnotation = null; + result.setFunctionFlags(result.getFunctionFlags() | 8192 /* IsFunctionExpression */); + result.setFunctionFlags(result.getFunctionFlags() | 2048 /* IsFatArrowFunction */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + this.movePast(node.equalsGreaterThanToken); + + var block = this.getArrowFunctionStatements(node.body); + + result = new TypeScript.FunctionDeclaration(null, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.returnTypeAnnotation = returnType; + result.setFunctionFlags(result.getFunctionFlags() | 8192 /* IsFunctionExpression */); + result.setFunctionFlags(result.getFunctionFlags() | 2048 /* IsFatArrowFunction */); + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitType = function (type) { + this.assertElementAtPosition(type); + + var result; + if (type.isToken()) { + var start = this.position; + result = new TypeScript.TypeReference(type.accept(this), 0); + this.setSpan(result, start, type); + } else { + result = type.accept(this); + } + + TypeScript.Debug.assert(result.nodeType === 11 /* TypeRef */); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitQualifiedName = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var left = this.visitType(node.left).term; + this.movePast(node.dotToken); + var right = this.identifierFromToken(node.right, false, true); + this.movePast(node.right); + + var term = new TypeScript.BinaryExpression(32 /* MemberAccessExpression */, left, right); + this.setSpan(term, start, node); + + result = new TypeScript.TypeReference(term, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeArgumentList = function (node) { + this.assertElementAtPosition(node); + + var result = new TypeScript.ASTList(); + + this.movePast(node.lessThanToken); + + var start = this.position; + + for (var i = 0, n = node.typeArguments.childCount(); i < n; i++) { + if (i % 2 === 1) { + this.movePast(node.typeArguments.childAt(i)); + } else { + result.append(this.visitType(node.typeArguments.childAt(i))); + } + } + this.movePast(node.greaterThanToken); + + this.setSpan(result, start, node.typeArguments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.newKeyword); + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + var parameters = node.parameterList.accept(this); + this.movePast(node.equalsGreaterThanToken); + var returnType = node.type ? this.visitType(node.type) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.returnTypeAnnotation = returnType; + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 128 /* Signature */); + funcDecl.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 1024 /* ConstructMember */); + funcDecl.setFlags(funcDecl.getFlags() | 8 /* TypeReference */); + funcDecl.hint = "_construct"; + funcDecl.classDecl = null; + + result = new TypeScript.TypeReference(funcDecl, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + var parameters = node.parameterList.accept(this); + this.movePast(node.equalsGreaterThanToken); + var returnType = node.type ? this.visitType(node.type) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.returnTypeAnnotation = returnType; + + funcDecl.setFlags(funcDecl.getFunctionFlags() | 128 /* Signature */); + funcDecl.setFlags(funcDecl.getFlags() | 8 /* TypeReference */); + funcDecl.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + + result = new TypeScript.TypeReference(funcDecl, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.openBraceToken); + var typeMembers = this.visitSeparatedSyntaxList(node.typeMembers); + this.movePast(node.closeBraceToken); + + var interfaceDecl = new TypeScript.InterfaceDeclaration(new TypeScript.Identifier("__anonymous"), null, typeMembers, null, null); + this.setSpan(interfaceDecl, start, node); + + interfaceDecl.setFlags(interfaceDecl.getFlags() | 8 /* TypeReference */); + + result = new TypeScript.TypeReference(interfaceDecl, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var underlying = this.visitType(node.type); + this.movePast(node.openBracketToken); + this.movePast(node.closeBracketToken); + + if (underlying.nodeType === 11 /* TypeRef */) { + result = underlying; + result.arrayCount++; + } else { + result = new TypeScript.TypeReference(underlying, 1); + } + + result.setFlags(result.getFlags() | 8 /* TypeReference */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGenericType = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var underlying = this.visitType(node.name).term; + var typeArguments = node.typeArgumentList.accept(this); + + var genericType = new TypeScript.GenericType(underlying, typeArguments); + this.setSpan(genericType, start, node); + + genericType.setFlags(genericType.getFlags() | 8 /* TypeReference */); + + result = new TypeScript.TypeReference(genericType, 0); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeAnnotation = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.colonToken); + return this.visitType(node.type); + }; + + SyntaxTreeToAstVisitor.prototype.visitBlock = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.openBraceToken); + var statements = this.visitSyntaxList(node.statements); + var closeBracePosition = this.position; + this.movePast(node.closeBraceToken); + var closeBraceSpan = new TypeScript.ASTSpan(); + this.setSpan(closeBraceSpan, closeBracePosition, node.closeBraceToken); + + result = new TypeScript.Block(statements); + result.closeBraceSpan = closeBraceSpan; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameter = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.identifier); + var identifier = this.identifierFromToken(node.identifier, !!node.questionToken, true); + this.movePast(node.identifier); + this.movePast(node.questionToken); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + result = new TypeScript.Parameter(identifier); + + result.preComments = preComments; + result.postComments = postComments; + result.isOptional = !!node.questionToken; + result.init = init; + result.typeExpr = typeExpr; + + if (node.publicOrPrivateKeyword) { + result.setVarFlags(result.getVarFlags() | 256 /* Property */); + + if (node.publicOrPrivateKeyword.kind() === 57 /* PublicKeyword */) { + result.setVarFlags(result.getVarFlags() | 4 /* Public */); + } else { + result.setVarFlags(result.getVarFlags() | 2 /* Private */); + } + } + + if (node.equalsValueClause || node.dotDotDotToken) { + result.setFlags(result.getFlags() | 4 /* OptionalName */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var expression = node.expression.accept(this); + this.movePast(node.dotToken); + var name = this.identifierFromToken(node.name, false, true); + this.movePast(node.name); + + result = new TypeScript.BinaryExpression(32 /* MemberAccessExpression */, expression, name); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var operand = node.operand.accept(this); + this.movePast(node.operatorToken); + + result = new TypeScript.UnaryExpression(node.kind() === 209 /* PostIncrementExpression */ ? 76 /* PostIncrementExpression */ : 77 /* PostDecrementExpression */, operand); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElementAccessExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var expression = node.expression.accept(this); + this.movePast(node.openBracketToken); + var argumentExpression = node.argumentExpression.accept(this); + this.movePast(node.closeBracketToken); + + result = new TypeScript.BinaryExpression(35 /* ElementAccessExpression */, expression, argumentExpression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.convertArgumentListArguments = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + + this.movePast(node.openParenToken); + + var result = this.visitSeparatedSyntaxList(node.arguments); + + if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { + var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); + this.setSpanExplicit(result, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + } + + this.movePast(node.closeParenToken); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInvocationExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var expression = node.expression.accept(this); + var typeArguments = node.argumentList.typeArgumentList !== null ? node.argumentList.typeArgumentList.accept(this) : null; + var argumentList = this.convertArgumentListArguments(node.argumentList); + + result = new TypeScript.CallExpression(36 /* InvocationExpression */, expression, typeArguments, argumentList); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArgumentList = function (node) { + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxTreeToAstVisitor.prototype.getBinaryExpressionNodeType = function (node) { + switch (node.kind()) { + case 172 /* CommaExpression */: + return 25 /* CommaExpression */; + case 173 /* AssignmentExpression */: + return 38 /* AssignmentExpression */; + case 174 /* AddAssignmentExpression */: + return 39 /* AddAssignmentExpression */; + case 175 /* SubtractAssignmentExpression */: + return 40 /* SubtractAssignmentExpression */; + case 176 /* MultiplyAssignmentExpression */: + return 42 /* MultiplyAssignmentExpression */; + case 177 /* DivideAssignmentExpression */: + return 41 /* DivideAssignmentExpression */; + case 178 /* ModuloAssignmentExpression */: + return 43 /* ModuloAssignmentExpression */; + case 179 /* AndAssignmentExpression */: + return 44 /* AndAssignmentExpression */; + case 180 /* ExclusiveOrAssignmentExpression */: + return 45 /* ExclusiveOrAssignmentExpression */; + case 181 /* OrAssignmentExpression */: + return 46 /* OrAssignmentExpression */; + case 182 /* LeftShiftAssignmentExpression */: + return 47 /* LeftShiftAssignmentExpression */; + case 183 /* SignedRightShiftAssignmentExpression */: + return 48 /* SignedRightShiftAssignmentExpression */; + case 184 /* UnsignedRightShiftAssignmentExpression */: + return 49 /* UnsignedRightShiftAssignmentExpression */; + case 186 /* LogicalOrExpression */: + return 51 /* LogicalOrExpression */; + case 187 /* LogicalAndExpression */: + return 52 /* LogicalAndExpression */; + case 188 /* BitwiseOrExpression */: + return 53 /* BitwiseOrExpression */; + case 189 /* BitwiseExclusiveOrExpression */: + return 54 /* BitwiseExclusiveOrExpression */; + case 190 /* BitwiseAndExpression */: + return 55 /* BitwiseAndExpression */; + case 191 /* EqualsWithTypeConversionExpression */: + return 56 /* EqualsWithTypeConversionExpression */; + case 192 /* NotEqualsWithTypeConversionExpression */: + return 57 /* NotEqualsWithTypeConversionExpression */; + case 193 /* EqualsExpression */: + return 58 /* EqualsExpression */; + case 194 /* NotEqualsExpression */: + return 59 /* NotEqualsExpression */; + case 195 /* LessThanExpression */: + return 60 /* LessThanExpression */; + case 196 /* GreaterThanExpression */: + return 62 /* GreaterThanExpression */; + case 197 /* LessThanOrEqualExpression */: + return 61 /* LessThanOrEqualExpression */; + case 198 /* GreaterThanOrEqualExpression */: + return 63 /* GreaterThanOrEqualExpression */; + case 199 /* InstanceOfExpression */: + return 33 /* InstanceOfExpression */; + case 200 /* InExpression */: + return 31 /* InExpression */; + case 201 /* LeftShiftExpression */: + return 69 /* LeftShiftExpression */; + case 202 /* SignedRightShiftExpression */: + return 70 /* SignedRightShiftExpression */; + case 203 /* UnsignedRightShiftExpression */: + return 71 /* UnsignedRightShiftExpression */; + case 204 /* MultiplyExpression */: + return 66 /* MultiplyExpression */; + case 205 /* DivideExpression */: + return 67 /* DivideExpression */; + case 206 /* ModuloExpression */: + return 68 /* ModuloExpression */; + case 207 /* AddExpression */: + return 64 /* AddExpression */; + case 208 /* SubtractExpression */: + return 65 /* SubtractExpression */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxTreeToAstVisitor.prototype.visitBinaryExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var nodeType = this.getBinaryExpressionNodeType(node); + var left = node.left.accept(this); + this.movePast(node.operatorToken); + var right = node.right.accept(this); + + result = new TypeScript.BinaryExpression(nodeType, left, right); + + if (right.nodeType === 12 /* FunctionDeclaration */) { + var id = left.nodeType === 32 /* MemberAccessExpression */ ? (left).operand2 : left; + var idHint = id.nodeType === 20 /* Name */ ? id.actualText : null; + + var funcDecl = right; + funcDecl.hint = idHint; + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConditionalExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var condition = node.condition.accept(this); + this.movePast(node.questionToken); + var whenTrue = node.whenTrue.accept(this); + this.movePast(node.colonToken); + var whenFalse = node.whenFalse.accept(this); + + result = new TypeScript.ConditionalExpression(condition, whenTrue, whenFalse); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + this.movePast(node.newKeyword); + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.returnTypeAnnotation = returnType; + + result.hint = "_construct"; + result.setFunctionFlags(result.getFunctionFlags() | 1024 /* ConstructMember */); + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMethodSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var name = this.identifierFromToken(node.propertyName, !!node.questionToken, true); + this.movePast(node.propertyName); + this.movePast(node.questionToken); + + var typeParameters = node.callSignature.typeParameterList ? node.callSignature.typeParameterList.accept(this) : null; + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(name, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + this.movePast(node.openBracketToken); + + var parameter = node.parameter.accept(this); + + this.movePast(node.closeBracketToken); + var returnType = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + var name = new TypeScript.Identifier("__item"); + this.setSpanExplicit(name, start, start); + + var parameters = new TypeScript.ASTList(); + parameters.append(parameter); + + result = new TypeScript.FunctionDeclaration(name, null, false, null, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = false; + result.returnTypeAnnotation = returnType; + + result.setFunctionFlags(result.getFunctionFlags() | 4096 /* IndexerMember */); + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPropertySignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var name = this.identifierFromToken(node.propertyName, !!node.questionToken, true); + this.movePast(node.propertyName); + this.movePast(node.questionToken); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + result = new TypeScript.VariableDeclarator(name); + + result.preComments = preComments; + result.typeExpr = typeExpr; + result.setVarFlags(result.getVarFlags() | 256 /* Property */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameterList = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var openParenToken = node.openParenToken; + this.previousTokenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + + this.movePast(node.openParenToken); + var result = this.visitSeparatedSyntaxList(node.parameters); + this.movePast(node.closeParenToken); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCallSignature = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var typeParameters = node.typeParameterList === null ? null : node.typeParameterList.accept(this); + var parameters = node.parameterList.accept(this); + var returnType = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(null, null, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + result.hint = "_call"; + result.setFunctionFlags(result.getFunctionFlags() | 512 /* CallMember */); + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameterList = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.lessThanToken); + var result = this.visitSeparatedSyntaxList(node.typeParameters); + this.movePast(node.greaterThanToken); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameter = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var constraint = node.constraint ? node.constraint.accept(this) : null; + + result = new TypeScript.TypeParameter(identifier, constraint); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstraint = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.extendsKeyword); + return this.visitType(node.type); + }; + + SyntaxTreeToAstVisitor.prototype.visitIfStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var thenBod = node.statement.accept(this); + var elseBod = node.elseClause ? node.elseClause.accept(this) : null; + + result = new TypeScript.IfStatement(condition, thenBod, elseBod); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElseClause = function (node) { + this.assertElementAtPosition(node); + + this.movePast(node.elseKeyword); + return node.statement.accept(this); + }; + + SyntaxTreeToAstVisitor.prototype.visitExpressionStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + result = new TypeScript.ExpressionStatement(expression); + result.preComments = preComments; + result.postComments = postComments; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.parameterList); + var parameters = node.parameterList.accept(this); + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + result = new TypeScript.FunctionDeclaration(null, block, true, null, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + + if (node.semicolonToken) { + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + + this.movePast(node.propertyName); + + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + this.movePast(node.semicolonToken); + + result = new TypeScript.FunctionDeclaration(name, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + if (node.semicolonToken) { + result.setFunctionFlags(result.getFunctionFlags() | 128 /* Signature */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 55 /* PrivateKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 2 /* Private */); + } else { + result.setFunctionFlags(result.getFunctionFlags() | 4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 58 /* StaticKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 16 /* Static */); + } + + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessorDeclaration = function (node, typeAnnotation) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + this.movePast(node.propertyName); + var parameters = node.parameterList.accept(this); + var returnType = typeAnnotation ? typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + result = new TypeScript.FunctionDeclaration(name, block, false, null, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.postComments = postComments; + result.variableArgList = this.hasDotDotDotParameter(node.parameterList.parameters); + result.returnTypeAnnotation = returnType; + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 55 /* PrivateKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 2 /* Private */); + } else { + result.setFunctionFlags(result.getFunctionFlags() | 4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 58 /* StaticKeyword */)) { + result.setFunctionFlags(result.getFunctionFlags() | 16 /* Static */); + } + + result.setFunctionFlags(result.getFunctionFlags() | 256 /* Method */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetMemberAccessorDeclaration = function (node) { + this.assertElementAtPosition(node); + + var result = this.visitMemberAccessorDeclaration(node, node.typeAnnotation); + + result.setFunctionFlags(result.getFunctionFlags() | 32 /* GetAccessor */); + result.hint = "get" + result.name.actualText; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetMemberAccessorDeclaration = function (node) { + this.assertElementAtPosition(node); + + var result = this.visitMemberAccessorDeclaration(node, null); + + result.setFunctionFlags(result.getFunctionFlags() | 64 /* SetAccessor */); + result.hint = "set" + result.name.actualText; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.moveTo(node, node.variableDeclarator); + this.moveTo(node.variableDeclarator, node.variableDeclarator.identifier); + + var name = this.identifierFromToken(node.variableDeclarator.identifier, false, true); + this.movePast(node.variableDeclarator.identifier); + var typeExpr = node.variableDeclarator.typeAnnotation ? node.variableDeclarator.typeAnnotation.accept(this) : null; + var init = node.variableDeclarator.equalsValueClause ? node.variableDeclarator.equalsValueClause.accept(this) : null; + this.movePast(node.semicolonToken); + + result = new TypeScript.VariableDeclarator(name); + + result.preComments = preComments; + result.postComments = postComments; + result.typeExpr = typeExpr; + result.init = init; + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 58 /* StaticKeyword */)) { + result.setVarFlags(result.getVarFlags() | 16 /* Static */); + } + + if (TypeScript.SyntaxUtilities.containsToken(node.modifiers, 55 /* PrivateKeyword */)) { + result.setVarFlags(result.getVarFlags() | 2 /* Private */); + } else { + result.setVarFlags(result.getVarFlags() | 4 /* Public */); + } + + result.setVarFlags(result.getVarFlags() | 2048 /* ClassProperty */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitThrowStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.throwKeyword); + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + result = new TypeScript.ThrowStatement(expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitReturnStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + var postComments = this.convertNodeTrailingComments(node, start); + + this.movePast(node.returnKeyword); + var expression = node.expression ? node.expression.accept(this) : null; + this.movePast(node.semicolonToken); + + result = new TypeScript.ReturnStatement(expression); + result.preComments = preComments; + result.postComments = postComments; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectCreationExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.newKeyword); + var expression = node.expression.accept(this); + var typeArgumentList = node.argumentList === null || node.argumentList.typeArgumentList === null ? null : node.argumentList.typeArgumentList.accept(this); + var argumentList = this.convertArgumentListArguments(node.argumentList); + + result = new TypeScript.CallExpression(37 /* ObjectCreationExpression */, expression, typeArgumentList, argumentList); + + if (expression.nodeType === 11 /* TypeRef */) { + var typeRef = expression; + + if (typeRef.arrayCount === 0) { + var term = typeRef.term; + if (term.nodeType === 32 /* MemberAccessExpression */ || term.nodeType === 20 /* Name */) { + expression = term; + } + } + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSwitchStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.switchKeyword); + this.movePast(node.openParenToken); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var closeParenPosition = this.position; + this.movePast(node.openBraceToken); + + result = new TypeScript.SwitchStatement(expression); + + result.statement.minChar = start; + result.statement.limChar = closeParenPosition; + + result.caseList = new TypeScript.ASTList(); + + for (var i = 0, n = node.switchClauses.childCount(); i < n; i++) { + var switchClause = node.switchClauses.childAt(i); + var translated = switchClause.accept(this); + + if (switchClause.kind() === 232 /* DefaultSwitchClause */) { + result.defaultCase = translated; + } + + result.caseList.append(translated); + } + + this.movePast(node.closeBraceToken); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCaseSwitchClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.caseKeyword); + var expression = node.expression.accept(this); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + result = new TypeScript.CaseClause(); + + result.expr = expression; + result.body = statements; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.defaultKeyword); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + result = new TypeScript.CaseClause(); + result.body = statements; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBreakStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.breakKeyword); + this.movePast(node.identifier); + this.movePast(node.semicolonToken); + + result = new TypeScript.Jump(82 /* BreakStatement */); + + if (node.identifier !== null) { + result.target = node.identifier.valueText(); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitContinueStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.continueKeyword); + this.movePast(node.identifier); + this.movePast(node.semicolonToken); + + result = new TypeScript.Jump(83 /* ContinueStatement */); + + if (node.identifier !== null) { + result.target = node.identifier.valueText(); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var init = node.variableDeclaration ? node.variableDeclaration.accept(this) : node.initializer ? node.initializer.accept(this) : null; + this.movePast(node.firstSemicolonToken); + var cond = node.condition ? node.condition.accept(this) : null; + this.movePast(node.secondSemicolonToken); + var incr = node.incrementor ? node.incrementor.accept(this) : null; + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + result = new TypeScript.ForStatement(init, cond, incr, body); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForInStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var init = node.variableDeclaration ? node.variableDeclaration.accept(this) : node.left.accept(this); + this.movePast(node.inKeyword); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + result = new TypeScript.ForInStatement(init, expression, body); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWhileStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + result = new TypeScript.WhileStatement(condition, statement); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWithStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + result = new TypeScript.WithStatement(condition, statement); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCastExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.lessThanToken); + var castTerm = this.visitType(node.type); + this.movePast(node.greaterThanToken); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(78 /* CastExpression */, expression); + result.castTerm = castTerm; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var openStart = this.position + node.openBraceToken.leadingTriviaWidth(); + this.movePast(node.openBraceToken); + + var propertyAssignments = this.visitSeparatedSyntaxList(node.propertyAssignments); + + var closeStart = this.position + node.closeBraceToken.leadingTriviaWidth(); + this.movePast(node.closeBraceToken); + + result = new TypeScript.UnaryExpression(22 /* ObjectLiteralExpression */, propertyAssignments); + result.preComments = preComments; + + if (this.isOnSingleLine(openStart, closeStart)) { + result.setFlags(result.getFlags() | 2 /* SingleLine */); + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + var left = node.propertyName.accept(this); + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(node.colonToken, this.position + node.colonToken.leadingTriviaWidth() + node.colonToken.width()); + + this.movePast(node.colonToken); + var right = node.expression.accept(this); + + result = new TypeScript.BinaryExpression(80 /* Member */, left, right); + result.preComments = preComments; + + if (right.nodeType === 12 /* FunctionDeclaration */) { + var funcDecl = right; + funcDecl.hint = left.text; + } + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var left = node.propertyName.accept(this); + var functionDeclaration = node.callSignature.accept(this); + var block = node.block.accept(this); + + functionDeclaration.hint = left.text; + functionDeclaration.block = block; + functionDeclaration.setFunctionFlags(16384 /* IsFunctionProperty */); + + result = new TypeScript.BinaryExpression(80 /* Member */, left, functionDeclaration); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetAccessorPropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + var functionName = this.identifierFromToken(node.propertyName, false, true); + this.movePast(node.propertyName); + this.movePast(node.openParenToken); + this.movePast(node.closeParenToken); + var returnType = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(functionName, block, false, null, new TypeScript.ASTList(), 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 32 /* GetAccessor */); + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 8192 /* IsFunctionExpression */); + funcDecl.hint = "get" + node.propertyName.valueText(); + funcDecl.returnTypeAnnotation = returnType; + + result = new TypeScript.BinaryExpression(80 /* Member */, name, funcDecl); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetAccessorPropertyAssignment = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.moveTo(node, node.propertyName); + var name = this.identifierFromToken(node.propertyName, false, true); + var functionName = this.identifierFromToken(node.propertyName, false, true); + this.movePast(node.propertyName); + this.movePast(node.openParenToken); + var parameter = node.parameter.accept(this); + this.movePast(node.closeParenToken); + + var parameters = new TypeScript.ASTList(); + parameters.append(parameter); + + var block = node.block ? node.block.accept(this) : null; + + var funcDecl = new TypeScript.FunctionDeclaration(functionName, block, false, null, parameters, 12 /* FunctionDeclaration */); + this.setSpan(funcDecl, start, node); + + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 64 /* SetAccessor */); + funcDecl.setFunctionFlags(funcDecl.getFunctionFlags() | 8192 /* IsFunctionExpression */); + funcDecl.hint = "set" + node.propertyName.valueText(); + + result = new TypeScript.BinaryExpression(80 /* Member */, name, funcDecl); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var preComments = this.convertNodeLeadingComments(node, start); + + this.movePast(node.functionKeyword); + var name = node.identifier === null ? null : this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeParameters = node.callSignature.typeParameterList === null ? null : node.callSignature.typeParameterList.accept(this); + var parameters = node.callSignature.parameterList.accept(this); + var returnType = node.callSignature.typeAnnotation ? node.callSignature.typeAnnotation.accept(this) : null; + + var block = node.block ? node.block.accept(this) : null; + + result = new TypeScript.FunctionDeclaration(name, block, false, typeParameters, parameters, 12 /* FunctionDeclaration */); + + result.preComments = preComments; + result.variableArgList = this.hasDotDotDotParameter(node.callSignature.parameterList.parameters); + result.returnTypeAnnotation = returnType; + result.setFunctionFlags(result.getFunctionFlags() | 8192 /* IsFunctionExpression */); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEmptyStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.semicolonToken); + + result = new TypeScript.EmptyStatement(); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTryStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.tryKeyword); + var tryBody = node.block.accept(this); + + var catchClause = null; + if (node.catchClause !== null) { + catchClause = node.catchClause.accept(this); + } + + var finallyBody = null; + if (node.finallyClause !== null) { + finallyBody = node.finallyClause.accept(this); + } + + result = new TypeScript.TryStatement(tryBody, catchClause, finallyBody); + } + + TypeScript.Debug.assert(result !== null); + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCatchClause = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.catchKeyword); + this.movePast(node.openParenToken); + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + var typeExpr = node.typeAnnotation ? node.typeAnnotation.accept(this) : null; + this.movePast(node.closeParenToken); + var block = node.block.accept(this); + + var varDecl = new TypeScript.VariableDeclarator(identifier); + this.setSpanExplicit(varDecl, identifier.minChar, identifier.limChar); + + varDecl.typeExpr = typeExpr; + + result = new TypeScript.CatchClause(varDecl, block); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFinallyClause = function (node) { + this.movePast(node.finallyKeyword); + return node.block.accept(this); + }; + + SyntaxTreeToAstVisitor.prototype.visitLabeledStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + var identifier = this.identifierFromToken(node.identifier, false, true); + this.movePast(node.identifier); + this.movePast(node.colonToken); + var statement = node.statement.accept(this); + + result = new TypeScript.LabeledStatement(identifier, statement); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDoStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.doKeyword); + var statement = node.statement.accept(this); + var whileSpan = new TypeScript.ASTSpan(); + this.setSpan(whileSpan, this.position, node.whileKeyword); + + this.movePast(node.whileKeyword); + this.movePast(node.openParenToken); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + this.movePast(node.semicolonToken); + + result = new TypeScript.DoStatement(statement, condition); + result.whileSpan = whileSpan; + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeOfExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.typeOfKeyword); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(34 /* TypeOfExpression */, expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDeleteExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.deleteKeyword); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(28 /* DeleteExpression */, expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVoidExpression = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.voidKeyword); + var expression = node.expression.accept(this); + + result = new TypeScript.UnaryExpression(24 /* VoidExpression */, expression); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDebuggerStatement = function (node) { + this.assertElementAtPosition(node); + + var start = this.position; + var result = this.getAST(node); + if (result) { + this.movePast(node); + } else { + this.movePast(node.debuggerKeyword); + this.movePast(node.semicolonToken); + + result = new TypeScript.DebuggerStatement(); + } + + this.setAST(node, result); + this.setSpan(result, start, node); + return result; + }; + SyntaxTreeToAstVisitor.checkPositions = false; + + SyntaxTreeToAstVisitor.protoString = "__proto__"; + SyntaxTreeToAstVisitor.protoSubstitutionString = "#__proto__"; + return SyntaxTreeToAstVisitor; + })(); + TypeScript.SyntaxTreeToAstVisitor = SyntaxTreeToAstVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Document = (function () { + function Document(fileName, compilationSettings, scriptSnapshot, byteOrderMark, version, isOpen, syntaxTree) { + this.fileName = fileName; + this.compilationSettings = compilationSettings; + this.scriptSnapshot = scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this.isOpen = isOpen; + this._diagnostics = null; + this._syntaxTree = null; + this._bloomFilter = null; + if (isOpen) { + this._syntaxTree = syntaxTree; + } else { + this._diagnostics = syntaxTree.diagnostics(); + } + + var identifiers = new TypeScript.BlockIntrinsics(); + + var identifierWalker = new TypeScript.IdentifierWalker(identifiers); + syntaxTree.sourceUnit().accept(identifierWalker); + + var identifierCount = 0; + for (var name in identifiers) { + identifierCount++; + } + this._bloomFilter = new TypeScript.BloomFilter(identifierCount); + this._bloomFilter.addKeys(identifiers); + + this.lineMap = syntaxTree.lineMap(); + this.script = TypeScript.SyntaxTreeToAstVisitor.visit(syntaxTree, fileName, compilationSettings); + } + Document.prototype.diagnostics = function () { + if (this._diagnostics === null) { + this._diagnostics = this._syntaxTree.diagnostics(); + } + + return this._diagnostics; + }; + + Document.prototype.syntaxTree = function () { + if (this._syntaxTree) { + return this._syntaxTree; + } + + return TypeScript.Parser.parse(this.fileName, TypeScript.SimpleText.fromScriptSnapshot(this.scriptSnapshot), TypeScript.isDTSFile(this.fileName), this.compilationSettings.codeGenTarget, TypeScript.getParseOptions(this.compilationSettings)); + }; + + Document.prototype.bloomFilter = function () { + return this._bloomFilter; + }; + + Document.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange, settings) { + var oldScript = this.script; + var oldSyntaxTree = this._syntaxTree; + + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null ? TypeScript.Parser.parse(this.fileName, text, TypeScript.isDTSFile(this.fileName), settings.codeGenTarget, TypeScript.getParseOptions(this.compilationSettings)) : TypeScript.Parser.incrementalParse(oldSyntaxTree, textChangeRange, text); + + return new Document(this.fileName, this.compilationSettings, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree); + }; + + Document.create = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles, compilationSettings) { + var syntaxTree = TypeScript.Parser.parse(fileName, TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot), TypeScript.isDTSFile(fileName), compilationSettings.codeGenTarget, TypeScript.getParseOptions(compilationSettings)); + + var document = new Document(fileName, compilationSettings, scriptSnapshot, byteOrderMark, version, isOpen, syntaxTree); + document.script.referencedFiles = referencedFiles; + + return document; + }; + return Document; + })(); + TypeScript.Document = Document; + + TypeScript.globalSemanticInfoChain = null; + TypeScript.globalBinder = null; + TypeScript.globalLogger = null; + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(logger, settings, diagnosticMessages) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof settings === "undefined") { settings = new TypeScript.CompilationSettings(); } + if (typeof diagnosticMessages === "undefined") { diagnosticMessages = null; } + this.logger = logger; + this.settings = settings; + this.diagnosticMessages = diagnosticMessages; + this.pullTypeChecker = null; + this.semanticInfoChain = null; + this.fileNameToDocument = new TypeScript.StringHashTable(); + this.emitOptions = new TypeScript.EmitOptions(this.settings); + TypeScript.globalLogger = logger; + if (this.diagnosticMessages) { + TypeScript.diagnosticMessages = this.diagnosticMessages; + } + } + TypeScriptCompiler.prototype.getDocument = function (fileName) { + return this.fileNameToDocument.lookup(fileName); + }; + + TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { + return TypeScript.timeFunction(this.logger, funcDescription, func); + }; + + TypeScriptCompiler.prototype.addSourceUnit = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + var _this = this; + return this.timeFunction("addSourceUnit(" + fileName + ")", function () { + var document = Document.create(fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles, _this.emitOptions.compilationSettings); + _this.fileNameToDocument.addOrUpdate(fileName, document); + + return document; + }); + }; + + TypeScriptCompiler.prototype.updateSourceUnit = function (fileName, scriptSnapshot, version, isOpen, textChangeRange) { + var _this = this; + return this.timeFunction("pullUpdateUnit(" + fileName + ")", function () { + var document = _this.getDocument(fileName); + var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange, _this.settings); + + _this.fileNameToDocument.addOrUpdate(fileName, updatedDocument); + + _this.pullUpdateScript(document, updatedDocument); + + return updatedDocument; + }); + }; + + TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { + var fileNames = this.fileNameToDocument.getAllKeys(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + var script = document.script; + if (!script.isDeclareFile && script.topLevelMod !== null) { + return true; + } + } + return false; + }; + + TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { + var commonComponents = []; + var commonComponentsLength = -1; + + var fileNames = this.fileNameToDocument.getAllKeys(); + for (var i = 0, len = fileNames.length; i < len; i++) { + var fileName = fileNames[i]; + var document = this.getDocument(fileNames[i]); + var script = document.script; + + if (!script.isDeclareFile) { + var fileComponents = TypeScript.filePathComponents(fileName); + if (commonComponentsLength === -1) { + commonComponents = fileComponents; + commonComponentsLength = commonComponents.length; + } else { + var updatedPath = false; + for (var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { + if (commonComponents[j] !== fileComponents[j]) { + commonComponentsLength = j; + updatedPath = true; + + if (j === 0) { + return new TypeScript.Diagnostic(null, 0, 0, 273 /* Cannot_find_the_common_subdirectory_path_for_the_input_files */, null); + } + + break; + } + } + + if (!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + + this.emitOptions.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + if (this.emitOptions.compilationSettings.outputOption.charAt(this.emitOptions.compilationSettings.outputOption.length - 1) !== "/") { + this.emitOptions.compilationSettings.outputOption += "/"; + } + + return null; + }; + + TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { + this.emitOptions.ioHost = ioHost; + if (this.emitOptions.compilationSettings.outputOption === "") { + this.emitOptions.outputMany = true; + this.emitOptions.commonDirectoryPath = ""; + return null; + } + + this.emitOptions.compilationSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitOptions.ioHost.resolvePath(this.emitOptions.compilationSettings.outputOption)); + + if (this.emitOptions.ioHost.directoryExists(this.emitOptions.compilationSettings.outputOption)) { + this.emitOptions.outputMany = true; + } else if (this.emitOptions.ioHost.fileExists(this.emitOptions.compilationSettings.outputOption)) { + this.emitOptions.outputMany = false; + } else { + this.emitOptions.outputMany = !TypeScript.isJSFile(this.emitOptions.compilationSettings.outputOption); + } + + if (this.isDynamicModuleCompilation() && !this.emitOptions.outputMany) { + return new TypeScript.Diagnostic(null, 0, 0, 274 /* Cannot_compile_dynamic_modules_when_emitting_into_single_file */, null); + } + + if (this.emitOptions.outputMany) { + return this.updateCommonDirectoryPath(); + } + + return null; + }; + + TypeScriptCompiler.prototype.getScripts = function () { + var result = []; + var fileNames = this.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + result.push(document.script); + } + + return result; + }; + + TypeScriptCompiler.prototype.writeByteOrderMarkForDocument = function (document) { + if (this.emitOptions.outputMany) { + return document.byteOrderMark !== 0 /* None */; + } else { + var fileNames = this.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + if (document.byteOrderMark !== 0 /* None */) { + return true; + } + } + + return false; + } + }; + + TypeScriptCompiler.mapToDTSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + + TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { + if (!this.settings.generateDeclarationFiles) { + return false; + } + + if (!!script && (script.isDeclareFile || script.moduleElements === null)) { + return false; + } + + return true; + }; + + TypeScriptCompiler.prototype.emitDeclarations = function (document, declarationEmitter) { + var script = document.script; + if (this.canEmitDeclarations(script)) { + if (!declarationEmitter) { + var declareFileName = this.emitOptions.mapOutputFileName(document.fileName, TypeScriptCompiler.mapToDTSFileName); + declarationEmitter = new TypeScript.DeclarationEmitter(declareFileName, this.semanticInfoChain, this.emitOptions, document.byteOrderMark !== 0 /* None */); + } + + declarationEmitter.fileName = document.fileName; + declarationEmitter.emitDeclarations(script); + } + + return declarationEmitter; + }; + + TypeScriptCompiler.prototype.emitAllDeclarations = function () { + if (this.canEmitDeclarations()) { + var sharedEmitter = null; + var fileNames = this.fileNameToDocument.getAllKeys(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + try { + var document = this.getDocument(fileNames[i]); + + if (this.emitOptions.outputMany) { + var singleEmitter = this.emitDeclarations(document); + if (singleEmitter) { + singleEmitter.close(); + } + } else { + sharedEmitter = this.emitDeclarations(document, sharedEmitter); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + } + + if (sharedEmitter) { + try { + sharedEmitter.close(); + } catch (ex2) { + return TypeScript.Emitter.handleEmitterError(sharedEmitter.fileName, ex2); + } + } + } + + return []; + }; + + TypeScriptCompiler.prototype.emitUnitDeclarations = function (fileName) { + if (this.canEmitDeclarations()) { + if (this.emitOptions.outputMany) { + try { + var document = this.getDocument(fileName); + var emitter = this.emitDeclarations(document); + if (emitter) { + emitter.close(); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + } else { + return this.emitAllDeclarations(); + } + } + + return []; + }; + + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { + if (wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + + TypeScriptCompiler.mapToJSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + + TypeScriptCompiler.prototype.emit = function (document, inputOutputMapper, emitter) { + var script = document.script; + if (!script.isDeclareFile) { + var typeScriptFileName = document.fileName; + if (!emitter) { + var javaScriptFileName = this.emitOptions.mapOutputFileName(typeScriptFileName, TypeScriptCompiler.mapToJSFileName); + var outFile = this.createFile(javaScriptFileName, this.writeByteOrderMarkForDocument(document)); + + emitter = new TypeScript.Emitter(javaScriptFileName, outFile, this.emitOptions, this.semanticInfoChain); + + if (this.settings.mapSourceFiles) { + var sourceMapFileName = javaScriptFileName + TypeScript.SourceMapper.MapFileExtension; + emitter.setSourceMappings(new TypeScript.SourceMapper(typeScriptFileName, javaScriptFileName, sourceMapFileName, outFile, this.createFile(sourceMapFileName, false), this.settings.emitFullSourceMapPath)); + } + + if (inputOutputMapper) { + inputOutputMapper(typeScriptFileName, javaScriptFileName); + } + } else if (this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(typeScriptFileName, emitter.emittingFileName, emitter.sourceMapper.sourceMapFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.settings.emitFullSourceMapPath)); + } + + emitter.setDocument(document); + emitter.emitJavascript(script, false); + } + + return emitter; + }; + + TypeScriptCompiler.prototype.emitAll = function (ioHost, inputOutputMapper) { + var optionsDiagnostic = this.parseEmitOption(ioHost); + if (optionsDiagnostic) { + return [optionsDiagnostic]; + } + + var startEmitTime = (new Date()).getTime(); + + var fileNames = this.fileNameToDocument.getAllKeys(); + var sharedEmitter = null; + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileName); + + try { + if (this.emitOptions.outputMany) { + var singleEmitter = this.emit(document, inputOutputMapper); + + if (singleEmitter) { + singleEmitter.emitSourceMapsAndClose(); + } + } else { + sharedEmitter = this.emit(document, inputOutputMapper, sharedEmitter); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + } + + this.logger.log("Emit: " + ((new Date()).getTime() - startEmitTime)); + + if (sharedEmitter) { + try { + sharedEmitter.emitSourceMapsAndClose(); + } catch (ex2) { + return TypeScript.Emitter.handleEmitterError(sharedEmitter.document.fileName, ex2); + } + } + + return []; + }; + + TypeScriptCompiler.prototype.emitUnit = function (fileName, ioHost, inputOutputMapper) { + var optionsDiagnostic = this.parseEmitOption(ioHost); + if (optionsDiagnostic) { + return [optionsDiagnostic]; + } + + if (this.emitOptions.outputMany) { + var document = this.getDocument(fileName); + try { + var emitter = this.emit(document, inputOutputMapper); + + if (emitter) { + emitter.emitSourceMapsAndClose(); + } + } catch (ex1) { + return TypeScript.Emitter.handleEmitterError(fileName, ex1); + } + + return []; + } else { + return this.emitAll(ioHost, inputOutputMapper); + } + }; + + TypeScriptCompiler.prototype.createFile = function (fileName, writeByteOrderMark) { + return new TypeScript.TextWriter(this.emitOptions.ioHost, fileName, writeByteOrderMark); + }; + + TypeScriptCompiler.prototype.getSyntacticDiagnostics = function (fileName) { + return this.getDocument(fileName).diagnostics(); + }; + + TypeScriptCompiler.prototype.getSyntaxTree = function (fileName) { + return this.getDocument(fileName).syntaxTree(); + }; + TypeScriptCompiler.prototype.getScript = function (fileName) { + return this.getDocument(fileName).script; + }; + + TypeScriptCompiler.prototype.getSemanticDiagnostics = function (fileName) { + var errors = []; + var unit = this.semanticInfoChain.getUnit(fileName); + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + if (unit) { + var document = this.getDocument(fileName); + var script = document.script; + + if (script) { + this.pullTypeChecker.typeCheckScript(script, fileName, this); + + unit.getDiagnostics(errors); + } + } + + return errors; + }; + + TypeScriptCompiler.prototype.pullTypeCheck = function () { + var _this = this; + return this.timeFunction("pullTypeCheck()", function () { + _this.semanticInfoChain = new TypeScript.SemanticInfoChain(); + TypeScript.globalSemanticInfoChain = _this.semanticInfoChain; + _this.pullTypeChecker = new TypeScript.PullTypeChecker(_this.settings, _this.semanticInfoChain); + + var declCollectionContext = null; + var i, n; + + var createDeclsStartTime = new Date().getTime(); + + var fileNames = _this.fileNameToDocument.getAllKeys(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + var document = _this.getDocument(fileName); + var semanticInfo = new TypeScript.SemanticInfo(fileName); + + declCollectionContext = new TypeScript.DeclCollectionContext(semanticInfo); + declCollectionContext.scriptName = fileName; + + TypeScript.getAstWalkerFactory().walk(document.script, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + semanticInfo.addTopLevelDecl(declCollectionContext.getParent()); + + _this.semanticInfoChain.addUnit(semanticInfo); + } + + var createDeclsEndTime = new Date().getTime(); + + var bindStartTime = new Date().getTime(); + + var binder = new TypeScript.PullSymbolBinder(_this.semanticInfoChain); + TypeScript.globalBinder = binder; + + var bindEndTime = new Date().getTime(); + + _this.logger.log("Decl creation: " + (createDeclsEndTime - createDeclsStartTime)); + _this.logger.log("Binding: " + (bindEndTime - bindStartTime)); + _this.logger.log(" Time in findSymbol: " + TypeScript.time_in_findSymbol); + _this.logger.log("Number of symbols created: " + TypeScript.pullSymbolID); + _this.logger.log("Number of specialized types created: " + TypeScript.nSpecializationsCreated); + _this.logger.log("Number of specialized signatures created: " + TypeScript.nSpecializedSignaturesCreated); + }); + }; + + TypeScriptCompiler.prototype.pullUpdateScript = function (oldDocument, newDocument) { + var _this = this; + this.timeFunction("pullUpdateScript: ", function () { + var oldScript = oldDocument.script; + var newScript = newDocument.script; + + var newScriptSemanticInfo = new TypeScript.SemanticInfo(oldDocument.fileName); + var oldScriptSemanticInfo = _this.semanticInfoChain.getUnit(oldDocument.fileName); + + TypeScript.lastBoundPullDeclId = TypeScript.pullDeclID; + TypeScript.lastBoundPullSymbolID = TypeScript.pullSymbolID; + + var declCollectionContext = new TypeScript.DeclCollectionContext(newScriptSemanticInfo); + + declCollectionContext.scriptName = oldDocument.fileName; + + TypeScript.getAstWalkerFactory().walk(newScript, TypeScript.preCollectDecls, TypeScript.postCollectDecls, null, declCollectionContext); + + var oldTopLevelDecl = oldScriptSemanticInfo.getTopLevelDecls()[0]; + var newTopLevelDecl = declCollectionContext.getParent(); + + newScriptSemanticInfo.addTopLevelDecl(newTopLevelDecl); + + if (_this.pullTypeChecker && _this.pullTypeChecker.resolver) { + _this.pullTypeChecker.resolver.cleanCachedGlobals(); + } + + _this.semanticInfoChain.updateUnit(oldScriptSemanticInfo, newScriptSemanticInfo); + + _this.logger.log("Cleaning symbols..."); + var cleanStart = new Date().getTime(); + _this.semanticInfoChain.update(); + var cleanEnd = new Date().getTime(); + _this.logger.log(" time to clean: " + (cleanEnd - cleanStart)); + + if (_this.pullTypeChecker && _this.pullTypeChecker.resolver) { + _this.pullTypeChecker.resolver.setUnitPath(oldDocument.fileName); + } + }); + }; + + TypeScriptCompiler.prototype.getSymbolOfDeclaration = function (decl) { + if (!decl) { + return null; + } + var ast = this.pullTypeChecker.resolver.getASTForDecl(decl); + if (!ast) { + return null; + } + var enlosingDecl = this.pullTypeChecker.resolver.getEnclosingDecl(decl); + if (ast.nodeType === 80 /* Member */) { + return this.getSymbolOfDeclaration(enlosingDecl); + } + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + return this.pullTypeChecker.resolver.resolveAST(ast, false, enlosingDecl, resolutionContext).symbol; + }; + + TypeScriptCompiler.prototype.resolvePosition = function (pos, document) { + var declStack = []; + var resultASTs = []; + var script = document.script; + var scriptName = document.fileName; + + var semanticInfo = this.semanticInfoChain.getUnit(scriptName); + var lastDeclAST = null; + var foundAST = null; + var symbol = null; + var candidateSignature = null; + var callSignatures = null; + + var lambdaAST = null; + var declarationInitASTs = []; + var objectLitAST = null; + var asgAST = null; + var typeAssertionASTs = []; + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + var inTypeReference = false; + var enclosingDecl = null; + var isConstructorCall = false; + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var pre = function (cur, parent) { + if (TypeScript.isValidAstNode(cur)) { + if (pos >= cur.minChar && pos <= cur.limChar) { + var previous = resultASTs[resultASTs.length - 1]; + + if (previous === undefined || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + var decl = semanticInfo.getDeclForAST(cur); + + if (decl) { + declStack[declStack.length] = decl; + lastDeclAST = cur; + } + + if (cur.nodeType === 12 /* FunctionDeclaration */ && TypeScript.hasFlag((cur).getFunctionFlags(), 8192 /* IsFunctionExpression */)) { + lambdaAST = cur; + } else if (cur.nodeType === 17 /* VariableDeclarator */) { + declarationInitASTs[declarationInitASTs.length] = cur; + } else if (cur.nodeType === 22 /* ObjectLiteralExpression */) { + objectLitAST = cur; + } else if (cur.nodeType === 78 /* CastExpression */) { + typeAssertionASTs[typeAssertionASTs.length] = cur; + } else if (cur.nodeType === 38 /* AssignmentExpression */) { + asgAST = cur; + } else if (cur.nodeType === 11 /* TypeRef */) { + inTypeReference = true; + } + + resultASTs[resultASTs.length] = cur; + } + } + } + return cur; + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + + if (resultASTs.length) { + this.pullTypeChecker.setUnit(scriptName); + + foundAST = resultASTs[resultASTs.length - 1]; + + if (foundAST.nodeType === 20 /* Name */ && resultASTs.length > 1) { + var previousAST = resultASTs[resultASTs.length - 2]; + switch (previousAST.nodeType) { + case 14 /* InterfaceDeclaration */: + case 13 /* ClassDeclaration */: + case 15 /* ModuleDeclaration */: + if (foundAST === (previousAST).name) { + foundAST = previousAST; + } + break; + + case 17 /* VariableDeclarator */: + if (foundAST === (previousAST).id) { + foundAST = previousAST; + } + break; + + case 12 /* FunctionDeclaration */: + if (foundAST === (previousAST).name) { + foundAST = previousAST; + } + break; + } + } + + var funcDecl = null; + if (lastDeclAST === foundAST) { + symbol = declStack[declStack.length - 1].getSymbol(); + this.pullTypeChecker.resolver.resolveDeclaredSymbol(symbol, null, resolutionContext); + symbol.setUnresolved(); + enclosingDecl = declStack[declStack.length - 1].getParentDecl(); + if (foundAST.nodeType === 12 /* FunctionDeclaration */) { + funcDecl = foundAST; + } + } else { + for (var i = declStack.length - 1; i >= 0; i--) { + if (!(declStack[i].getKind() & (1024 /* Variable */ | 2048 /* Parameter */))) { + enclosingDecl = declStack[i]; + break; + } + } + + var callExpression = null; + if ((foundAST.nodeType === 30 /* SuperExpression */ || foundAST.nodeType === 29 /* ThisExpression */ || foundAST.nodeType === 20 /* Name */) && resultASTs.length > 1) { + for (var i = resultASTs.length - 2; i >= 0; i--) { + if (resultASTs[i].nodeType === 32 /* MemberAccessExpression */ && (resultASTs[i]).operand2 === resultASTs[i + 1]) { + foundAST = resultASTs[i]; + } else if ((resultASTs[i].nodeType === 36 /* InvocationExpression */ || resultASTs[i].nodeType === 37 /* ObjectCreationExpression */) && (resultASTs[i]).target === resultASTs[i + 1]) { + callExpression = resultASTs[i]; + break; + } else if (resultASTs[i].nodeType === 12 /* FunctionDeclaration */ && (resultASTs[i]).name === resultASTs[i + 1]) { + funcDecl = resultASTs[i]; + break; + } else { + break; + } + } + } + + if (foundAST.nodeType === 1 /* List */) { + for (var i = 0; i < (foundAST).members.length; i++) { + if ((foundAST).members[i].minChar > pos) { + foundAST = (foundAST).members[i]; + break; + } + } + } + + resolutionContext.resolvingTypeReference = inTypeReference; + + var inContextuallyTypedAssignment = false; + + if (declarationInitASTs.length) { + var assigningAST; + + for (var i = 0; i < declarationInitASTs.length; i++) { + assigningAST = declarationInitASTs[i]; + inContextuallyTypedAssignment = (assigningAST !== null) && (assigningAST.typeExpr !== null); + + this.pullTypeChecker.resolver.resolveAST(assigningAST, false, null, resolutionContext); + var varSymbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(assigningAST, scriptName); + var varSymbol = varSymbolAndDiagnostics && varSymbolAndDiagnostics.symbol; + + if (varSymbol && inContextuallyTypedAssignment) { + var contextualType = varSymbol.getType(); + resolutionContext.pushContextualType(contextualType, false, null); + } + + if (assigningAST.init) { + this.pullTypeChecker.resolver.resolveAST(assigningAST.init, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + } + } + + if (typeAssertionASTs.length) { + for (var i = 0; i < typeAssertionASTs.length; i++) { + this.pullTypeChecker.resolver.resolveAST(typeAssertionASTs[i], inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + } + + if (asgAST) { + this.pullTypeChecker.resolver.resolveAST(asgAST, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + + if (objectLitAST) { + this.pullTypeChecker.resolver.resolveAST(objectLitAST, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + + if (lambdaAST) { + this.pullTypeChecker.resolver.resolveAST(lambdaAST, true, enclosingDecl, resolutionContext); + enclosingDecl = semanticInfo.getDeclForAST(lambdaAST); + } + + symbol = this.pullTypeChecker.resolver.resolveAST(foundAST, inContextuallyTypedAssignment, enclosingDecl, resolutionContext).symbol; + if (callExpression) { + var isPropertyOrVar = symbol.getKind() === 4096 /* Property */ || symbol.getKind() === 1024 /* Variable */; + var typeSymbol = symbol.getType(); + if (isPropertyOrVar) { + isPropertyOrVar = (typeSymbol.getKind() !== 16 /* Interface */ && typeSymbol.getKind() !== 8388608 /* ObjectType */) || typeSymbol.getName() === ""; + } + + if (!isPropertyOrVar) { + isConstructorCall = foundAST.nodeType === 30 /* SuperExpression */ || callExpression.nodeType === 37 /* ObjectCreationExpression */; + + if (foundAST.nodeType === 30 /* SuperExpression */) { + if (symbol.getKind() === 8 /* Class */) { + callSignatures = (symbol).getConstructorMethod().getType().getConstructSignatures(); + } + } else { + callSignatures = callExpression.nodeType === 36 /* InvocationExpression */ ? typeSymbol.getCallSignatures() : typeSymbol.getConstructSignatures(); + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (callExpression.nodeType === 36 /* InvocationExpression */) { + this.pullTypeChecker.resolver.resolveCallExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } else { + this.pullTypeChecker.resolver.resolveNewExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.candidateSignature) { + candidateSignature = callResolutionResults.candidateSignature; + } + if (callResolutionResults.targetSymbol && callResolutionResults.targetSymbol.getName() !== "") { + symbol = callResolutionResults.targetSymbol; + } + foundAST = callExpression; + } + } + } + + if (funcDecl) { + if (symbol && symbol.getKind() !== 4096 /* Property */) { + var signatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(funcDecl, this.semanticInfoChain.getUnit(scriptName)); + candidateSignature = signatureInfo.signature; + callSignatures = signatureInfo.allSignatures; + } + } else if (!callSignatures && symbol && (symbol.getKind() === 65536 /* Method */ || symbol.getKind() === 16384 /* Function */)) { + var typeSym = symbol.getType(); + if (typeSym) { + callSignatures = typeSym.getCallSignatures(); + } + } + } + + var enclosingScopeSymbol = this.getSymbolOfDeclaration(enclosingDecl); + + return { + symbol: symbol, + ast: foundAST, + enclosingScopeSymbol: enclosingScopeSymbol, + candidateSignature: candidateSignature, + callSignatures: callSignatures, + isConstructorCall: isConstructorCall + }; + }; + + TypeScriptCompiler.prototype.extractResolutionContextFromPath = function (path, document) { + var script = document.script; + var scriptName = document.fileName; + + var semanticInfo = this.semanticInfoChain.getUnit(scriptName); + var enclosingDecl = null; + var enclosingDeclAST = null; + var inContextuallyTypedAssignment = false; + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var resolutionContext = new TypeScript.PullTypeResolutionContext(); + resolutionContext.resolveAggressively = true; + + if (path.count() === 0) { + return null; + } + + this.pullTypeChecker.setUnit(semanticInfo.getPath()); + + for (var i = 0, n = path.count(); i < n; i++) { + var current = path.asts[i]; + + switch (current.nodeType) { + case 12 /* FunctionDeclaration */: + if (TypeScript.hasFlag((current).getFunctionFlags(), 8192 /* IsFunctionExpression */)) { + this.pullTypeChecker.resolver.resolveAST((current), true, enclosingDecl, resolutionContext); + } + + break; + + case 17 /* VariableDeclarator */: + var assigningAST = current; + inContextuallyTypedAssignment = (assigningAST.typeExpr !== null); + + this.pullTypeChecker.resolver.resolveAST(assigningAST, false, null, resolutionContext); + var varSymbolAndDiagnostics = this.semanticInfoChain.getSymbolAndDiagnosticsForAST(assigningAST, scriptName); + var varSymbol = varSymbolAndDiagnostics && varSymbolAndDiagnostics.symbol; + + var contextualType = null; + if (varSymbol && inContextuallyTypedAssignment) { + contextualType = varSymbol.getType(); + } + + resolutionContext.pushContextualType(contextualType, false, null); + + if (assigningAST.init) { + this.pullTypeChecker.resolver.resolveAST(assigningAST.init, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + + break; + + case 36 /* InvocationExpression */: + case 37 /* ObjectCreationExpression */: + var isNew = current.nodeType === 37 /* ObjectCreationExpression */; + var callExpression = current; + var contextualType = null; + + if ((i + 1 < n) && callExpression.arguments === path.asts[i + 1]) { + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (isNew) { + this.pullTypeChecker.resolver.resolveNewExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } else { + this.pullTypeChecker.resolver.resolveCallExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.actualParametersContextTypeSymbols) { + var argExpression = (path.asts[i + 1] && path.asts[i + 1].nodeType === 1 /* List */) ? path.asts[i + 2] : path.asts[i + 1]; + if (argExpression) { + for (var j = 0, m = callExpression.arguments.members.length; j < m; j++) { + if (callExpression.arguments.members[j] === argExpression) { + var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j]; + if (callContextualType) { + contextualType = callContextualType; + break; + } + } + } + } + } + } else { + if (isNew) { + this.pullTypeChecker.resolver.resolveNewExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } else { + this.pullTypeChecker.resolver.resolveCallExpression(callExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 21 /* ArrayLiteralExpression */: + this.pullTypeChecker.resolver.resolveAST(current, inContextuallyTypedAssignment, enclosingDecl, resolutionContext); + + var contextualType = null; + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isArray()) { + contextualType = currentContextualType.getElementType(); + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 22 /* ObjectLiteralExpression */: + var objectLiteralExpression = current; + var objectLiteralResolutionContext = new TypeScript.PullAdditionalObjectLiteralResolutionData(); + this.pullTypeChecker.resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext, objectLiteralResolutionContext); + + var memeberAST = (path.asts[i + 1] && path.asts[i + 1].nodeType === 1 /* List */) ? path.asts[i + 2] : path.asts[i + 1]; + if (memeberAST) { + var contextualType = null; + var memberDecls = objectLiteralExpression.operand; + if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) { + for (var j = 0, m = memberDecls.members.length; j < m; j++) { + if (memberDecls.members[j] === memeberAST) { + var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j]; + if (memberContextualType) { + contextualType = memberContextualType; + break; + } + } + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + } + + break; + + case 38 /* AssignmentExpression */: + var assignmentExpression = current; + var contextualType = null; + + if (path.asts[i + 1] && path.asts[i + 1] === assignmentExpression.operand2) { + var leftType = this.pullTypeChecker.resolver.resolveAST(assignmentExpression.operand1, inContextuallyTypedAssignment, enclosingDecl, resolutionContext).symbol.getType(); + if (leftType) { + inContextuallyTypedAssignment = true; + contextualType = leftType; + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 78 /* CastExpression */: + var castExpression = current; + var contextualType = null; + + if (i + 1 < n && path.asts[i + 1] === castExpression.castTerm) { + resolutionContext.resolvingTypeReference = true; + } + + var typeSymbol = this.pullTypeChecker.resolver.resolveTypeAssertionExpression(castExpression, inContextuallyTypedAssignment, enclosingDecl, resolutionContext).symbol; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 93 /* ReturnStatement */: + var returnStatement = current; + var contextualType = null; + + if (enclosingDecl && (enclosingDecl.getKind() & TypeScript.PullElementKind.SomeFunction)) { + var functionDeclaration = enclosingDeclAST; + if (functionDeclaration.returnTypeAnnotation) { + var currentResolvingTypeReference = resolutionContext.resolvingTypeReference; + resolutionContext.resolvingTypeReference = true; + var returnTypeSymbol = this.pullTypeChecker.resolver.resolveTypeReference(functionDeclaration.returnTypeAnnotation, enclosingDecl, resolutionContext).symbol; + resolutionContext.resolvingTypeReference = currentResolvingTypeReference; + if (returnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = returnTypeSymbol; + } + } else { + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var currentContextualTypeSignatureSymbol = currentContextualType.getDeclarations()[0].getSignatureSymbol(); + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.getReturnType(); + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = currentContextualTypeReturnTypeSymbol; + } + } + } + } + + resolutionContext.pushContextualType(contextualType, false, null); + + break; + + case 11 /* TypeRef */: + case 9 /* TypeParameter */: + resolutionContext.resolvingTypeReference = true; + break; + } + + var decl = semanticInfo.getDeclForAST(current); + if (decl && !(decl.getKind() & (1024 /* Variable */ | 2048 /* Parameter */ | 8192 /* TypeParameter */))) { + enclosingDecl = decl; + enclosingDeclAST = current; + } + } + + if (path.isNameOfInterface() || path.isInClassImplementsList() || path.isInInterfaceExtendsList()) { + resolutionContext.resolvingTypeReference = true; + } + + if (path.ast().nodeType === 20 /* Name */ && path.count() > 1) { + for (var i = path.count() - 1; i >= 0; i--) { + if (path.asts[path.top - 1].nodeType === 32 /* MemberAccessExpression */ && (path.asts[path.top - 1]).operand2 === path.asts[path.top]) { + path.pop(); + } else { + break; + } + } + } + + return { + ast: path.ast(), + enclosingDecl: enclosingDecl, + resolutionContext: resolutionContext, + inContextuallyTypedAssignment: inContextuallyTypedAssignment + }; + }; + + TypeScriptCompiler.prototype.pullGetSymbolInformationFromPath = function (path, document) { + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var symbolAndDiagnostics = this.pullTypeChecker.resolver.resolveAST(path.ast(), context.inContextuallyTypedAssignment, context.enclosingDecl, context.resolutionContext); + var symbol = symbolAndDiagnostics && symbolAndDiagnostics.symbol; + + return { + symbol: symbol, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclarationSymbolInformation = function (path, document) { + var script = document.script; + var scriptName = document.fileName; + + var ast = path.ast(); + + if (ast.nodeType !== 13 /* ClassDeclaration */ && ast.nodeType !== 14 /* InterfaceDeclaration */ && ast.nodeType !== 15 /* ModuleDeclaration */ && ast.nodeType !== 12 /* FunctionDeclaration */ && ast.nodeType !== 17 /* VariableDeclarator */) { + return null; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var semanticInfo = this.semanticInfoChain.getUnit(scriptName); + var decl = semanticInfo.getDeclForAST(ast); + var symbol = (decl.getKind() & TypeScript.PullElementKind.SomeSignature) ? decl.getSignatureSymbol() : decl.getSymbol(); + this.pullTypeChecker.resolver.resolveDeclaredSymbol(symbol, null, context.resolutionContext); + + symbol.setUnresolved(); + + return { + symbol: symbol, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetCallInformationFromPath = function (path, document) { + if (path.ast().nodeType !== 36 /* InvocationExpression */ && path.ast().nodeType !== 37 /* ObjectCreationExpression */) { + return null; + } + + var isNew = (path.ast().nodeType === 37 /* ObjectCreationExpression */); + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + + if (isNew) { + this.pullTypeChecker.resolver.resolveNewExpression(path.ast(), context.inContextuallyTypedAssignment, context.enclosingDecl, context.resolutionContext, callResolutionResults); + } else { + this.pullTypeChecker.resolver.resolveCallExpression(path.ast(), context.inContextuallyTypedAssignment, context.enclosingDecl, context.resolutionContext, callResolutionResults); + } + + return { + targetSymbol: callResolutionResults.targetSymbol, + resolvedSignatures: callResolutionResults.resolvedSignatures, + candidateSignature: callResolutionResults.candidateSignature, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl), + isConstructorCall: isNew + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleMemberSymbolsFromPath = function (path, document) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + var symbols = this.pullTypeChecker.resolver.getVisibleMembersFromExpression(path.ast(), context.enclosingDecl, context.resolutionContext); + if (!symbols) { + return null; + } + + return { + symbols: symbols, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleDeclsFromPath = function (path, document) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + var symbols = null; + + return this.pullTypeChecker.resolver.getVisibleDecls(context.enclosingDecl, context.resolutionContext); + }; + + TypeScriptCompiler.prototype.pullGetContextualMembersFromPath = function (path, document) { + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + if (path.ast().nodeType !== 22 /* ObjectLiteralExpression */) { + return null; + } + + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + var members = this.pullTypeChecker.resolver.getVisibleContextSymbols(context.enclosingDecl, context.resolutionContext); + + return { + symbols: members, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclInformation = function (decl, path, document) { + var context = this.extractResolutionContextFromPath(path, document); + if (!context) { + return null; + } + + TypeScript.globalSemanticInfoChain = this.semanticInfoChain; + if (TypeScript.globalBinder) { + TypeScript.globalBinder.semanticInfoChain = this.semanticInfoChain; + } + + var symbol = decl.getSymbol(); + this.pullTypeChecker.resolver.resolveDeclaredSymbol(symbol, context.enclosingDecl, context.resolutionContext); + symbol.setUnresolved(); + + return { + symbol: symbol, + ast: path.ast(), + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetTypeInfoAtPosition = function (pos, document) { + var _this = this; + return this.timeFunction("pullGetTypeInfoAtPosition for pos " + pos + ":", function () { + return _this.resolvePosition(pos, document); + }); + }; + + TypeScriptCompiler.prototype.getTopLevelDeclarations = function (scriptName) { + var unit = this.semanticInfoChain.getUnit(scriptName); + + if (!unit) { + return null; + } + + return unit.getTopLevelDecls(); + }; + + TypeScriptCompiler.prototype.reportDiagnostics = function (errors, errorReporter) { + for (var i = 0; i < errors.length; i++) { + errorReporter.addDiagnostic(errors[i]); + } + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + + CompilerDiagnostics.diagnosticWriter = null; + + CompilerDiagnostics.analysisPass = 0; + + function Alert(output) { + if (CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + + function debugPrint(s) { + if (CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + + function assert(condition, s) { + if (CompilerDiagnostics.debug) { + if (!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var CompilerDiagnostics = TypeScript.CompilerDiagnostics; + + var NullLogger = (function () { + function NullLogger() { + } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typescript_0.8.2/lib.d.ts b/_infrastructure/tests/typescript_0.8.2/lib.d.ts deleted file mode 100644 index 528c2439f..000000000 --- a/_infrastructure/tests/typescript_0.8.2/lib.d.ts +++ /dev/null @@ -1,8236 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// - -//////////////// -/// ECMAScript APIs -//////////////// - -declare var NaN: number; -declare var Infinity: number; - -/** - * Evaluates JavaScript code and executes it. - * @param x A String value that contains valid JavaScript code. - */ -declare function eval(x: string): any; - -/** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ -declare function parseInt(s: string, radix?: number): number; - -/** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ -declare function parseFloat(string: string): number; - -/** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). - * @param number A numeric value. - */ -declare function isNaN(number: number): bool; - -/** - * Determines whether a supplied number is finite. - * @param number Any numeric value. - */ -declare function isFinite(number: number): bool; - -/** - * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). - * @param encodedURI A value representing an encoded URI. - */ -declare function decodeURI(encodedURI: string): string; - -/** - * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). - * @param encodedURIComponent A value representing an encoded URI component. - */ -declare function decodeURIComponent(encodedURIComponent: string): string; - -/** - * Encodes a text string as a valid Uniform Resource Identifier (URI) - * @param uri A value representing an encoded URI. - */ -declare function encodeURI(uri: string): string; - -/** - * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). - * @param uriComponent A value representing an encoded URI component. - */ -declare function encodeURIComponent(uriComponent: string): string; - -interface PropertyDescriptor { - configurable?: bool; - enumerable?: bool; - value?: any; - writable?: bool; - get?(): any; - set?(v: any): void; -} - -interface PropertyDescriptorMap { - [s: string]: PropertyDescriptor; -} - -interface Object { - /** Returns a string representation of an object. */ - toString(): string; - - /** Returns a date converted to a string using the current locale. */ - toLocaleString(): string; - - /** Returns the primitive value of the specified object. */ - valueOf(): Object; - - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: string): bool; - - /** - * Determines whether an object exists in another object's prototype chain. - * @param v Another object whose prototype chain is to be checked. - */ - isPrototypeOf(v: Object): bool; - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: string): bool; - - [s: string]: any; -} - -/** - * Provides functionality common to all JavaScript objects. - */ -declare var Object: { - new (value?: any): Object; - (): any; - (value: any): any; - - /** A reference to the prototype for a class of objects. */ - prototype: Object; - - /** - * Returns the prototype of an object. - * @param o The object that references the prototype. - */ - getPrototypeOf(o: any): any; - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; - - /** - * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly - * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. - * @param o Object that contains the own properties. - */ - getOwnPropertyNames(o: any): string[]; - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - * @param properties JavaScript object that contains one or more property descriptors. - */ - create(o: any, properties?: PropertyDescriptorMap): any; - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor property. - */ - defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; - - /** - * Adds one or more properties to an object, and/or modifies attributes of existing properties. - * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. - * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. - */ - defineProperties(o: any, properties: PropertyDescriptorMap): any; - - /** - * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - seal(o: any): any; - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(o: any): any; - - /** - * Prevents the addition of new properties to an object. - * @param o Object to make non-extensible. - */ - preventExtensions(o: any): any; - - /** - * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. - * @param o Object to test. - */ - isSealed(o: any): bool; - - /** - * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. - * @param o Object to test. - */ - isFrozen(o: any): bool; - - /** - * Returns a value that indicates whether new properties can be added to an object. - * @param o Object to test. - */ - isExtensible(o: any): bool; - - /** - * Returns the names of the enumerable properties and methods of an object. - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - keys(o: any): string[]; -} - -/** - * Creates a new function. - */ -interface Function { - /** - * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. - * @param thisArg The object to be used as the this object. - * @param argArray A set of arguments to be passed to the function. - */ - apply(thisArg: any, ...argArray: any[]): any; - - /** - * Calls a method of an object, substituting another object for the current object. - * @param thisArg The object to be used as the current object. - * @param argArray A list of arguments to be passed to the method. - */ - call(thisArg: any, ...argArray: any[]): any; - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg An object to which the this keyword can refer inside the new function. - * @param argArray A list of arguments to be passed to the new function. - */ - bind(thisArg: any, ...argArray: any[]): any; - - prototype: any; - length: number; -} - -declare var Function: { - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - prototype: Function; -} - -interface IArguments { - [index: number]: any; - length: number; - callee: Function; -} - -interface String { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): string[]; - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): string[]; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: string, replaceValue: string): string; - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: RegExp, replaceValue: string): string; - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index integer indicating the beginning of the substring. - * @param end Zero-based index integer indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Removes the leading and trailing white space and line terminator characters from a string. */ - trim(): string; - - /** Returns the length of a String object. */ - length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; -} - -/** - * Allows manipulation and formatting of text strings and determination and location of substrings within strings. - */ -declare var String: { - new (value?: any): String; - (value?: any): string; - prototype: String; - fromCharCode(...codes: number[]): string; -} - -interface Boolean { -} -declare var Boolean: { - new (value?: any): Boolean; - (value?: any): bool; - prototype: Boolean; -} - -interface Number { - toString(radix?: number): string; - toFixed(fractionDigits?: number): string; - toExponential(fractionDigits?: number): string; - toPrecision(precision: number): string; -} -/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare var Number: { - new (value?: any): Number; - (value?: any): number; - prototype: Number; - /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - MAX_VALUE: number; - /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - MIN_VALUE: number; - /** - * A value that is not a number. - * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. - */ - NaN: number; - /** - * A value that is less than the largest negative number that can be represented in JavaScript. - * JavaScript displays NEGATIVE_INFINITY values as -infinity. - */ - NEGATIVE_INFINITY: number; - /** - * A value greater than the largest number that can be represented in JavaScript. - * JavaScript displays POSITIVE_INFINITY values as infinity. - */ - POSITIVE_INFINITY: number; -} - -interface Math { - /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - E: number; - /** The natural logarithm of 10. */ - LN10: number; - /** The natural logarithm of 2. */ - LN2: number; - /** The base-2 logarithm of e. */ - LOG2E: number; - /** The base-10 logarithm of e. */ - LOG10E: number; - /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - PI: number; - /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - SQRT1_2: number; - /** The square root of 2. */ - SQRT2: number; - /** - * Returns the absolute value of a number (the value without regard to whether it is positive or negative). - * For example, the absolute value of -5 is the same as the absolute value of 5. - * @param x A numeric expression for which the absolute value is needed. - */ - abs(x: number): number; - /** - * Returns the arc cosine (or inverse cosine) of a number. - * @param x A numeric expression. - */ - acos(x: number): number; - /** - * Returns the arcsine of a number. - * @param x A numeric expression. - */ - asin(x: number): number; - /** - * Returns the arctangent of a number. - * @param x A numeric expression for which the arctangent is needed. - */ - atan(x: number): number; - /** - * Returns the angle (in radians) from the X axis to a point (y,x). - * @param y A numeric expression representing the cartesian y-coordinate. - * @param x A numeric expression representing the cartesian x-coordinate. - */ - atan2(y: number, x: number): number; - /** - * Returns the smallest integer greater than or equal to its numeric argument. - * @param x A numeric expression. - */ - ceil(x: number): number; - /** - * Returns the cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cos(x: number): number; - /** - * Returns e (the base of natural logarithms) raised to a power. - * @param x A numeric expression representing the power of e. - */ - exp(x: number): number; - /** - * Returns the greatest integer less than or equal to its numeric argument. - * @param x A numeric expression. - */ - floor(x: number): number; - /** - * Returns the natural logarithm (base e) of a number. - * @param x A numeric expression. - */ - log(x: number): number; - /** - * Returns the larger of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - max(...values: number[]): number; - /** - * Returns the smaller of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - min(...values: number[]): number; - /** - * Returns the value of a base expression taken to a specified power. - * @param x The base value of the expression. - * @param y The exponent value of the expression. - */ - pow(x: number, y: number): number; - /** Returns a pseudorandom number between 0 and 1. */ - random(): number; - /** - * Returns a supplied numeric expression rounded to the nearest integer. - * @param x The value to be rounded to the nearest integer. - */ - round(x: number): number; - /** - * Returns the sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sin(x: number): number; - /** - * Returns the square root of a number. - * @param x A numeric expression. - */ - sqrt(x: number): number; - /** - * Returns the tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tan(x: number): number; -} -/** An intrinsic object that provides basic mathematics functionality and constants. */ -declare var Math: Math; - -/** Enables basic storage and retrieval of dates and times. */ -interface Date { - /** Returns a string representation of a date. The format of the string depends on the locale. */ - toString(): string; - /** Returns a date as a string value. */ - toDateString(): string; - /** Returns a time as a string value. */ - toTimeString(): string; - toLocaleString(): string; - /** Returns a date as a string value appropriate to the host environment's current locale. */ - toLocaleDateString(): string; - /** Returns a time as a string value appropriate to the host environment's current locale. */ - toLocaleTimeString(): string; - /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ - valueOf(): number; - /** Gets the time value in milliseconds. */ - getTime(): number; - /** Gets the year, using local time. */ - getFullYear(): number; - /** Gets the year using Universal Coordinated Time (UTC). */ - getUTCFullYear(): number; - /** Gets the month, using local time. */ - getMonth(): number; - /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ - getUTCMonth(): number; - /** Gets the day-of-the-month, using local time. */ - getDate(): number; - /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ - getUTCDate(): number; - /** Gets the day of the week, using local time. */ - getDay(): number; - /** Gets the day of the week using Universal Coordinated Time (UTC). */ - getUTCDay(): number; - /** Gets the hours in a date, using local time. */ - getHours(): number; - /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ - getUTCHours(): number; - /** Gets the minutes of a Date object, using local time. */ - getMinutes(): number; - /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ - getUTCMinutes(): number; - /** Gets the seconds of a Date object, using local time. */ - getSeconds(): number; - /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCSeconds(): number; - /** Gets the milliseconds of a Date, using local time. */ - getMilliseconds(): number; - /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCMilliseconds(): number; - /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ - getTimezoneOffset(): number; - /** - * Sets the date and time value in the Date object. - * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. - */ - setTime(time: number): void; - /** - * Sets the milliseconds value in the Date object using local time. - * @param ms A numeric value equal to the millisecond value. - */ - setMilliseconds(ms: number): void; - /** - * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). - * @param ms A numeric value equal to the millisecond value. - */ - setUTCMilliseconds(ms: number): void; - - /** - * Sets the seconds value in the Date object using local time. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setSeconds(sec: number, ms?: number): void; - /** - * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCSeconds(sec: number, ms?: number): void; - /** - * Sets the minutes value in the Date object using local time. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setMinutes(min: number, sec?: number, ms?: number): void; - /** - * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCMinutes(min: number, sec?: number, ms?: number): void; - /** - * Sets the hour value in the Date object using local time. - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setHours(hours: number, min?: number, sec?: number, ms?: number): void; - /** - * Sets the hours value in the Date object using Universal Coordinated Time (UTC). - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): void; - /** - * Sets the numeric day-of-the-month value of the Date object using local time. - * @param date A numeric value equal to the day of the month. - */ - setDate(date: number): void; - /** - * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). - * @param date A numeric value equal to the day of the month. - */ - setUTCDate(date: number): void; - /** - * Sets the month value in the Date object using local time. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. - */ - setMonth(month: number, date?: number): void; - /** - * Sets the month value in the Date object using Universal Coordinated Time (UTC). - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. - */ - setUTCMonth(month: number, date?: number): void; - /** - * Sets the year of the Date object using local time. - * @param year A numeric value for the year. - * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. - * @param date A numeric value equal for the day of the month. - */ - setFullYear(year: number, month?: number, date?: number): void; - /** - * Sets the year value in the Date object using Universal Coordinated Time (UTC). - * @param year A numeric value equal to the year. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. - * @param date A numeric value equal to the day of the month. - */ - setUTCFullYear(year: number, month?: number, date?: number): void; - /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ - toUTCString(): string; - /** Returns a date as a string value in ISO format. */ - toISOString(): string; - /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ - toJSON(key?: any): string; -} -/** - * Enables basic storage and retrieval of dates and times. - */ -declare var Date: { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; - (): string; - prototype: Date; - /** - * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. - * @param s A date string - */ - parse(s: string): number; - /** - * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. - * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an integer between 0 and 11 (January to December). - * @param date The date as an integer between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the seconds. - * @param ms An integer from 0 to 999 that specifies the milliseconds. - */ - UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; - now(): number; -} - -interface RegExpExecArray { - [index: number]: string; - length: number; - - index: number; - input: string; - - toString(): string; - toLocaleString(): string; - concat(...items: string[][]): string[]; - join(seperator?: string): string; - pop(): string; - push(...items: string[]): number; - reverse(): string[]; - shift(): string; - slice(start: number, end?: number): string[]; - sort(compareFn?: (a: string, b: string) => number): string[]; - splice(start: number): string[]; - splice(start: number, deleteCount: number, ...items: string[]): string[]; - unshift(...items: string[]): number; - - indexOf(searchElement: string, fromIndex?: number): number; - lastIndexOf(searchElement: string, fromIndex?: number): number; - every(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; - some(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; - forEach(callbackfn: (value: string, index: number, array: string[]) => void , thisArg?: any): void; - map(callbackfn: (value: string, index: number, array: string[]) => any, thisArg?: any): any[]; - filter(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): string[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; -} - - -interface RegExp { - /** - * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. - * @param string The String object or string literal on which to perform the search. - */ - exec(string: string): RegExpExecArray; - /** - * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. - * @param string String on which to perform the search. - */ - test(string: string): bool; - /** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */ - source: string; - /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - global: bool; - /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - ignoreCase: bool; - /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - multiline: bool; - - lastIndex: number; -} -declare var RegExp: { - new (pattern: string, flags?: string): RegExp; - (pattern: string, flags?: string): RegExp; -} - -interface Error { - name: string; - message: string; -} -declare var Error: { - new (message?: string): Error; - (message?: string): Error; - prototype: Error; -} - -interface EvalError extends Error { -} -declare var EvalError: { - new (message?: string): EvalError; - (message?: string): EvalError; - prototype: EvalError; -} - -interface RangeError extends Error { -} -declare var RangeError: { - new (message?: string): RangeError; - (message?: string): RangeError; - prototype: RangeError; -} - -interface ReferenceError extends Error { -} -declare var ReferenceError: { - new (message?: string): ReferenceError; - (message?: string): ReferenceError; - prototype: ReferenceError; -} - -interface SyntaxError extends Error { -} -declare var SyntaxError: { - new (message?: string): SyntaxError; - (message?: string): SyntaxError; - prototype: SyntaxError; -} - -interface TypeError extends Error { -} -declare var TypeError: { - new (message?: string): TypeError; - (message?: string): TypeError; - prototype: TypeError; -} - -interface URIError extends Error { -} -declare var URIError: { - new (message?: string): URIError; - (message?: string): URIError; - prototype: URIError; -} - -interface JSON { - /** - * Converts a JavaScript Object Notation (JSON) string into an object. - * @param text A valid JSON string. - * @param reviver A function that transforms the results. This function is called for each member of the object. - * If a member contains nested objects, the nested objects are transformed before the parent object is. - */ - parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - */ - stringify(value: any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - */ - stringify(value: any, replacer: (key: string, value: any) => any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. - */ - stringify(value: any, replacer: any[]): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer: (key: string, value: any) => any, space: any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify(value: any, replacer: any[], space: any): string; -} -/** - * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. - */ -declare var JSON: JSON; - -//////////////// -/// ECMAScript Array API (specially handled by compiler) -//////////////// - -interface Array { - toString(): string; - toLocaleString(): string; - concat(...items: _element[][]): _element[]; - join(seperator?: string): string; - pop(): _element; - push(...items: _element[]): number; - reverse(): _element[]; - shift(): _element; - slice(start: number, end?: number): _element[]; - sort(compareFn?: (a: _element, b: _element) => number): _element[]; - splice(start: number): _element[]; - splice(start: number, deleteCount: number, ...items: _element[]): _element[]; - unshift(...items: _element[]): number; - - indexOf(searchElement: _element, fromIndex?: number): number; - lastIndexOf(searchElement: _element, fromIndex?: number): number; - every(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; - some(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; - forEach(callbackfn: (value: _element, index: number, array: _element[]) => void , thisArg?: any): void; - map(callbackfn: (value: _element, index: number, array: _element[]) => any, thisArg?: any): any[]; - filter(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): _element[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; - - length: number; -} -declare var Array: { - new (...items: any[]): any[]; - (...items: any[]): any[]; - isArray(arg: any): bool; - prototype: Array; -} - -//////////////// -/// IE10 ECMAScript Extensions -//////////////// - -interface ArrayBuffer { - byteLength: number; -} -declare var ArrayBuffer: { - prototype: ArrayBuffer; - new (byteLength: number); -} - -interface ArrayBufferView { - buffer: ArrayBuffer; - byteOffset: number; - byteLength: number; -} - -interface Int8Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Int8Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Int8Array; -} -declare var Int8Array: { - prototype: Int8Array; - new (length: number): Int8Array; - new (array: Int8Array): Int8Array; - new (array: number[]): Int8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; - BYTES_PER_ELEMENT: number; -} - -interface Uint8Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Uint8Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Uint8Array; -} -declare var Uint8Array: { - prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: Uint8Array): Uint8Array; - new (array: number[]): Uint8Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; - BYTES_PER_ELEMENT: number; -} - -interface Int16Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Int16Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Int16Array; -} -declare var Int16Array: { - prototype: Int16Array; - new (length: number): Int16Array; - new (array: Int16Array): Int16Array; - new (array: number[]): Int16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; - BYTES_PER_ELEMENT: number; -} - -interface Uint16Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Uint16Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Uint16Array; -} -declare var Uint16Array: { - prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: Uint16Array): Uint16Array; - new (array: number[]): Uint16Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; - BYTES_PER_ELEMENT: number; -} - -interface Int32Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Int32Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Int32Array; -} -declare var Int32Array: { - prototype: Int32Array; - new (length: number): Int32Array; - new (array: Int32Array): Int32Array; - new (array: number[]): Int32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; - BYTES_PER_ELEMENT: number; -} - -interface Uint32Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Uint32Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Uint32Array; -} -declare var Uint32Array: { - prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: Uint32Array): Uint32Array; - new (array: number[]): Uint32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; - BYTES_PER_ELEMENT: number; -} - -interface Float32Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Float32Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Float32Array; -} -declare var Float32Array: { - prototype: Float32Array; - new (length: number): Float32Array; - new (array: Float32Array): Float32Array; - new (array: number[]): Float32Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; - BYTES_PER_ELEMENT: number; -} - -interface Float64Array extends ArrayBufferView { - BYTES_PER_ELEMENT: number; - length: number; - [index: number]: number; - get(index: number): number; - set(index: number, value: number): void; - set(array: Float64Array, offset?: number): void; - set(array: number[], offset?: number): void; - subarray(begin: number, end?: number): Float64Array; -} -declare var Float64Array: { - prototype: Float64Array; - new (length: number): Float64Array; - new (array: Float64Array): Float64Array; - new (array: number[]): Float64Array; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; - BYTES_PER_ELEMENT: number; -} - -interface DataView extends ArrayBufferView { - getInt8(byteOffset: number): number; - getUint8(byteOffset: number): number; - getInt16(byteOffset: number, littleEndian?: bool): number; - getUint16(byteOffset: number, littleEndian?: bool): number; - getInt32(byteOffset: number, littleEndian?: bool): number; - getUint32(byteOffset: number, littleEndian?: bool): number; - getFloat32(byteOffset: number, littleEndian?: bool): number; - getFloat64(byteOffset: number, littleEndian?: bool): number; - - setInt8(byteOffset: number, value: number): void; - setUint8(byteOffset: number, value: number): void; - setInt16(byteOffset: number, value: number, littleEndian?: bool): void; - setUint16(byteOffset: number, value: number, littleEndian?: bool): void; - setInt32(byteOffset: number, value: number, littleEndian?: bool): void; - setUint32(byteOffset: number, value: number, littleEndian?: bool): void; - setFloat32(byteOffset: number, value: number, littleEndian?: bool): void; - setFloat64(byteOffset: number, value: number, littleEndian?: bool): void; -} -declare var DataView: { - prototype: DataView; - new (buffer: ArrayBuffer, byteOffset?: number, length?: number): DataView; -} - -//////////////// -/// IE9 DOM APIs (note that -//////////////// - -interface NavigatorID { - appVersion: string; - appName: string; - userAgent: string; - platform: string; -} - -interface HTMLTableElement extends HTMLElement, DOML2DeprecatedBorderStyle_HTMLTableElement, DOML2DeprecatedAlignmentStyle_HTMLTableElement, MSBorderColorStyle, MSDataBindingExtensions, MSHTMLTableElementExtensions, DOML2DeprecatedBackgroundStyle, MSBorderColorHighlightStyle, MSDataBindingTableExtensions, DOML2DeprecatedBackgroundColorStyle { - tBodies: HTMLCollection; - width: string; - tHead: HTMLTableSectionElement; - cellSpacing: string; - tFoot: HTMLTableSectionElement; - frame: string; - rows: HTMLCollection; - rules: string; - cellPadding: string; - summary: string; - caption: HTMLTableCaptionElement; - deleteRow(index?: number): void; - createTBody(): HTMLElement; - deleteCaption(): void; - insertRow(index?: number): HTMLElement; - deleteTFoot(): void; - createTHead(): HTMLElement; - deleteTHead(): void; - createCaption(): HTMLElement; - createTFoot(): HTMLElement; -} -declare var HTMLTableElement: { - prototype: HTMLTableElement; - new(): HTMLTableElement; -} - -interface TreeWalker { - whatToShow: number; - filter: NodeFilterCallback; - root: Node; - currentNode: Node; - expandEntityReferences: bool; - previousSibling(): Node; - lastChild(): Node; - nextSibling(): Node; - nextNode(): Node; - parentNode(): Node; - firstChild(): Node; - previousNode(): Node; -} -declare var TreeWalker: { - prototype: TreeWalker; - new(): TreeWalker; -} - -interface GetSVGDocument { - getSVGDocument(): SVGDocument; -} - -interface HTMLHtmlElementDOML2Deprecated { - version: string; -} - -interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { - y: number; - y1: number; - x: number; - x1: number; -} -declare var SVGPathSegCurvetoQuadraticRel: { - prototype: SVGPathSegCurvetoQuadraticRel; - new(): SVGPathSegCurvetoQuadraticRel; -} - -interface Performance { - navigation: PerformanceNavigation; - timing: PerformanceTiming; - toJSON(): any; -} -declare var Performance: { - prototype: Performance; - new(): Performance; -} - -interface SVGSVGElementEventHandlers { - onresize: (ev: UIEvent) => any; - onunload: (ev: Event) => any; - onscroll: (ev: UIEvent) => any; - onerror: (ev: Event) => any; - onzoom: (ev: any) => any; - onabort: (ev: UIEvent) => any; -} - -interface MSDataBindingTableExtensions { - dataPageSize: number; - nextPage(): void; - firstPage(): void; - refresh(): void; - previousPage(): void; - lastPage(): void; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLParagraphElement { - align: string; -} - -interface CompositionEvent extends UIEvent { - data: string; - locale: string; - initCompositionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, locale: string): void; -} -declare var CompositionEvent: { - prototype: CompositionEvent; - new(): CompositionEvent; -} - -interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox { - orientType: SVGAnimatedEnumeration; - markerUnits: SVGAnimatedEnumeration; - markerWidth: SVGAnimatedLength; - markerHeight: SVGAnimatedLength; - orientAngle: SVGAnimatedAngle; - refY: SVGAnimatedLength; - refX: SVGAnimatedLength; - setOrientToAngle(angle: SVGAngle): void; - setOrientToAuto(): void; - SVG_MARKER_ORIENT_UNKNOWN: number; - SVG_MARKER_ORIENT_ANGLE: number; - SVG_MARKERUNITS_UNKNOWN: number; - SVG_MARKERUNITS_STROKEWIDTH: number; - SVG_MARKER_ORIENT_AUTO: number; - SVG_MARKERUNITS_USERSPACEONUSE: number; -} -declare var SVGMarkerElement: { - prototype: SVGMarkerElement; - new(): SVGMarkerElement; - SVG_MARKER_ORIENT_UNKNOWN: number; - SVG_MARKER_ORIENT_ANGLE: number; - SVG_MARKERUNITS_UNKNOWN: number; - SVG_MARKERUNITS_STROKEWIDTH: number; - SVG_MARKER_ORIENT_AUTO: number; - SVG_MARKERUNITS_USERSPACEONUSE: number; -} - -interface WindowTimers { - clearTimeout(handle: number): void; - setTimeout(expression: any, msec?: number, language?: any): number; - clearInterval(handle: number): void; - setInterval(expression: any, msec?: number, language?: any): number; -} - -interface CSSStyleDeclaration extends CSS3Properties, SVG1_1Properties, CSS2Properties { - cssText: string; - length: number; - parentRule: CSSRule; - getPropertyPriority(propertyName: string): string; - getPropertyValue(propertyName: string): string; - removeProperty(propertyName: string): string; - item(index: number): string; - [index: number]: string; - setProperty(propertyName: string, value: string, priority?: string): void; -} -declare var CSSStyleDeclaration: { - prototype: CSSStyleDeclaration; - new(): CSSStyleDeclaration; -} - -interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { -} -declare var SVGGElement: { - prototype: SVGGElement; - new(): SVGGElement; -} - -interface MSStyleCSSProperties extends MSCSSProperties { - pixelWidth: number; - posHeight: number; - posLeft: number; - pixelTop: number; - pixelBottom: number; - textDecorationNone: bool; - pixelLeft: number; - posTop: number; - posBottom: number; - textDecorationOverline: bool; - posWidth: number; - textDecorationLineThrough: bool; - pixelHeight: number; - textDecorationBlink: bool; - posRight: number; - pixelRight: number; - textDecorationUnderline: bool; -} -declare var MSStyleCSSProperties: { - prototype: MSStyleCSSProperties; - new(): MSStyleCSSProperties; -} - -interface MSCSSStyleSheetExtensions { - owningElement: Element; - imports: StyleSheetList; - isAlternate: bool; - rules: MSCSSRuleList; - isPrefAlternate: bool; - readOnly: bool; - cssText: string; - href: string; - id: string; - pages: StyleSheetPageList; - addImport(bstrURL: string, lIndex?: number): number; - addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; - removeRule(lIndex: number): void; - addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; - removeImport(lIndex: number): void; -} - -interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorDoNotTrack, NavigatorAbilities, NavigatorGeolocation, MSNavigatorAbilities { -} -declare var Navigator: { - prototype: Navigator; - new(): Navigator; -} - -interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { - y: number; - x2: number; - x: number; - y2: number; -} -declare var SVGPathSegCurvetoCubicSmoothAbs: { - prototype: SVGPathSegCurvetoCubicSmoothAbs; - new(): SVGPathSegCurvetoCubicSmoothAbs; -} - -interface MSBorderColorStyle_HTMLFrameSetElement { - borderColor: any; -} - -interface SVGZoomEvent extends UIEvent { - zoomRectScreen: SVGRect; - previousScale: number; - newScale: number; - previousTranslate: SVGPoint; - newTranslate: SVGPoint; -} -declare var SVGZoomEvent: { - prototype: SVGZoomEvent; - new(): SVGZoomEvent; -} - -interface NodeSelector { - querySelectorAll(selectors: string): NodeList; - querySelector(selectors: string): Element; -} - -interface HTMLTableDataCellElement extends HTMLTableCellElement, MSHTMLTableDataCellElementExtensions { -} -declare var HTMLTableDataCellElement: { - prototype: HTMLTableDataCellElement; - new(): HTMLTableDataCellElement; -} - -interface MSHTMLDirectoryElementExtensions extends DOML2DeprecatedListNumberingAndBulletStyle { -} - -interface HTMLBaseElement extends HTMLElement { - target: string; - href: string; -} -declare var HTMLBaseElement: { - prototype: HTMLBaseElement; - new(): HTMLBaseElement; -} - -interface ClientRect { - left: number; - width: number; - right: number; - top: number; - bottom: number; - height: number; -} -declare var ClientRect: { - prototype: ClientRect; - new(): ClientRect; -} - -interface PositionErrorCallback { - (error: PositionError): void; -} - -interface DOMImplementation extends DOMHTMLImplementation { - createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; - createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; - hasFeature(feature: string, version?: string): bool; -} -declare var DOMImplementation: { - prototype: DOMImplementation; - new(): DOMImplementation; -} - -interface DOML2DeprecatedWidthStyle_HTMLBlockElement { - width: number; -} - -interface SVGUnitTypes { - SVG_UNIT_TYPE_UNKNOWN: number; - SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; - SVG_UNIT_TYPE_USERSPACEONUSE: number; -} -declare var SVGUnitTypes: { - prototype: SVGUnitTypes; - new(): SVGUnitTypes; - SVG_UNIT_TYPE_UNKNOWN: number; - SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; - SVG_UNIT_TYPE_USERSPACEONUSE: number; -} - -interface DocumentRange { - createRange(): Range; -} - -interface MSHTMLDocumentExtensions { - onrowexit: (ev: MSEventObj) => any; - compatible: MSCompatibleInfoCollection; - oncontrolselect: (ev: MSEventObj) => any; - onrowsinserted: (ev: MSEventObj) => any; - onpropertychange: (ev: MSEventObj) => any; - media: string; - onafterupdate: (ev: MSEventObj) => any; - onhelp: (ev: Event) => any; - uniqueID: string; - onbeforeactivate: (ev: UIEvent) => any; - onstoragecommit: (ev: StorageEvent) => any; - onselectionchange: (ev: Event) => any; - documentMode: number; - onfocusout: (ev: FocusEvent) => any; - ondataavailable: (ev: MSEventObj) => any; - onbeforeupdate: (ev: MSEventObj) => any; - onfocusin: (ev: FocusEvent) => any; - security: string; - namespaces: MSNamespaceInfoCollection; - ondatasetcomplete: (ev: MSEventObj) => any; - onbeforedeactivate: (ev: UIEvent) => any; - onstop: (ev: Event) => any; - onactivate: (ev: UIEvent) => any; - onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; - frames: Window; - onselectstart: (ev: Event) => any; - onerrorupdate: (ev: MSEventObj) => any; - parentWindow: Window; - ondeactivate: (ev: UIEvent) => any; - ondatasetchanged: (ev: MSEventObj) => any; - onrowsdelete: (ev: MSEventObj) => any; - onmsthumbnailclick: (ev: MSSiteModeEvent) => any; - onrowenter: (ev: MSEventObj) => any; - onbeforeeditfocus: (ev: MSEventObj) => any; - Script: MSScriptHost; - oncellchange: (ev: MSEventObj) => any; - URLUnencoded: string; - updateSettings(): void; - execCommandShowHelp(commandId: string): bool; - releaseCapture(): void; - focus(): void; -} - -interface CSS2Properties { - backgroundAttachment: string; - visibility: string; - fontFamily: string; - borderRightStyle: string; - clear: string; - content: string; - counterIncrement: string; - orphans: string; - marginBottom: string; - borderStyle: string; - counterReset: string; - outlineWidth: string; - marginRight: string; - paddingLeft: string; - borderBottom: string; - marginTop: string; - borderTopColor: string; - top: string; - fontWeight: string; - textIndent: string; - borderRight: string; - width: string; - listStyleImage: string; - cursor: string; - listStylePosition: string; - borderTopStyle: string; - direction: string; - maxWidth: string; - color: string; - clip: string; - borderRightWidth: string; - verticalAlign: string; - pageBreakAfter: string; - overflow: string; - borderBottomStyle: string; - borderLeftStyle: string; - fontStretch: string; - emptyCells: string; - padding: string; - paddingRight: string; - background: string; - bottom: string; - height: string; - paddingTop: string; - right: string; - borderLeftWidth: string; - borderLeft: string; - backgroundPosition: string; - backgroundColor: string; - widows: string; - lineHeight: string; - pageBreakInside: string; - borderTopWidth: string; - left: string; - outlineStyle: string; - borderTop: string; - paddingBottom: string; - outlineColor: string; - wordSpacing: string; - outline: string; - font: string; - marginLeft: string; - display: string; - maxHeight: string; - cssFloat: string; - letterSpacing: string; - borderSpacing: string; - backgroundRepeat: string; - fontSizeAdjust: string; - borderLeftColor: string; - borderWidth: string; - backgroundImage: string; - listStyleType: string; - whiteSpace: string; - fontStyle: string; - borderBottomColor: string; - minWidth: string; - position: string; - zIndex: string; - borderColor: string; - listStyle: string; - captionSide: string; - borderCollapse: string; - fontVariant: string; - quotes: string; - tableLayout: string; - unicodeBidi: string; - borderBottomWidth: string; - minHeight: string; - textDecoration: string; - fontSize: string; - border: string; - pageBreakBefore: string; - textAlign: string; - textTransform: string; - margin: string; - borderRightColor: string; -} - -interface MSImageResourceExtensions_HTMLInputElement { - dynsrc: string; - vrml: string; - lowsrc: string; - start: string; - loop: number; -} - -interface MSHTMLEmbedElementExtensions { - palette: string; - hidden: string; - pluginspage: string; - units: string; -} - -interface MSHTMLModElementExtensions { -} - -interface Element extends Node, NodeSelector, ElementTraversal, MSElementExtensions { - scrollTop: number; - clientLeft: number; - scrollLeft: number; - tagName: string; - clientWidth: number; - scrollWidth: number; - clientHeight: number; - clientTop: number; - scrollHeight: number; - getAttribute(name?: string): string; - getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; - hasAttributeNS(namespaceURI: string, localName: string): bool; - getBoundingClientRect(): ClientRect; - getAttributeNS(namespaceURI: string, localName: string): string; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; - setAttributeNodeNS(newAttr: Attr): Attr; - hasAttribute(name: string): bool; - removeAttribute(name?: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; - getAttributeNode(name: string): Attr; - getElementsByTagName(name: string): NodeList; - setAttributeNode(newAttr: Attr): Attr; - getClientRects(): ClientRectList; - removeAttributeNode(oldAttr: Attr): Attr; - setAttribute(name?: string, value?: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; -} -declare var Element: { - prototype: Element; - new(): Element; -} - -interface SVGDocument { - rootElement: SVGSVGElement; -} - -interface HTMLNextIdElement extends HTMLElement { - n: string; -} -declare var HTMLNextIdElement: { - prototype: HTMLNextIdElement; - new(): HTMLNextIdElement; -} - -interface SVGPathSegMovetoRel extends SVGPathSeg { - y: number; - x: number; -} -declare var SVGPathSegMovetoRel: { - prototype: SVGPathSegMovetoRel; - new(): SVGPathSegMovetoRel; -} - -interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { - y1: SVGAnimatedLength; - x2: SVGAnimatedLength; - x1: SVGAnimatedLength; - y2: SVGAnimatedLength; -} -declare var SVGLineElement: { - prototype: SVGLineElement; - new(): SVGLineElement; -} - -interface HTMLParagraphElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLParagraphElement, MSHTMLParagraphElementExtensions { -} -declare var HTMLParagraphElement: { - prototype: HTMLParagraphElement; - new(): HTMLParagraphElement; -} - -interface MSHTMLTextAreaElementExtensions { - status: any; - createTextRange(): TextRange; -} - -interface ErrorFunction { - (eventOrMessage: any, source: string, fileno: number): any; -} - -interface HTMLAreasCollection extends HTMLCollection { - remove(index?: number): void; - add(element: HTMLElement, before?: any): void; -} -declare var HTMLAreasCollection: { - prototype: HTMLAreasCollection; - new(): HTMLAreasCollection; -} - -interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { -} -declare var SVGDescElement: { - prototype: SVGDescElement; - new(): SVGDescElement; -} - -interface Node extends EventTarget { - nodeType: number; - previousSibling: Node; - localName: string; - namespaceURI: string; - textContent: string; - parentNode: Node; - nextSibling: Node; - nodeValue: string; - lastChild: Node; - childNodes: NodeList; - nodeName: string; - ownerDocument: Document; - attributes: Attr[]; - firstChild: Node; - prefix: string; - removeChild(oldChild: Node): Node; - appendChild(newChild: Node): Node; - isSupported(feature: string, version: string): bool; - isEqualNode(arg: Node): bool; - lookupPrefix(namespaceURI: string): string; - isDefaultNamespace(namespaceURI: string): bool; - compareDocumentPosition(other: Node): number; - normalize(): void; - isSameNode(other: Node): bool; - hasAttributes(): bool; - lookupNamespaceURI(prefix: string): string; - cloneNode(deep?: bool): Node; - hasChildNodes(): bool; - replaceChild(newChild: Node, oldChild: Node): Node; - insertBefore(newChild: Node, refChild?: Node): Node; - ENTITY_REFERENCE_NODE: number; - ATTRIBUTE_NODE: number; - DOCUMENT_FRAGMENT_NODE: number; - TEXT_NODE: number; - ELEMENT_NODE: number; - COMMENT_NODE: number; - DOCUMENT_POSITION_DISCONNECTED: number; - DOCUMENT_POSITION_CONTAINED_BY: number; - DOCUMENT_POSITION_CONTAINS: number; - DOCUMENT_TYPE_NODE: number; - DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - DOCUMENT_NODE: number; - ENTITY_NODE: number; - PROCESSING_INSTRUCTION_NODE: number; - CDATA_SECTION_NODE: number; - NOTATION_NODE: number; - DOCUMENT_POSITION_FOLLOWING: number; - DOCUMENT_POSITION_PRECEDING: number; -} -declare var Node: { - prototype: Node; - new(): Node; - ENTITY_REFERENCE_NODE: number; - ATTRIBUTE_NODE: number; - DOCUMENT_FRAGMENT_NODE: number; - TEXT_NODE: number; - ELEMENT_NODE: number; - COMMENT_NODE: number; - DOCUMENT_POSITION_DISCONNECTED: number; - DOCUMENT_POSITION_CONTAINED_BY: number; - DOCUMENT_POSITION_CONTAINS: number; - DOCUMENT_TYPE_NODE: number; - DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; - DOCUMENT_NODE: number; - ENTITY_NODE: number; - PROCESSING_INSTRUCTION_NODE: number; - CDATA_SECTION_NODE: number; - NOTATION_NODE: number; - DOCUMENT_POSITION_FOLLOWING: number; - DOCUMENT_POSITION_PRECEDING: number; -} - -interface MSHTMLLegendElementExtensions { -} - -interface MSCSSStyleDeclarationExtensions { - getAttribute(attributeName: string, flags?: number): any; - setAttribute(attributeName: string, AttributeValue: any, flags?: number): void; - removeAttribute(attributeName: string, flags?: number): bool; -} - -interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { - y: number; - x: number; -} -declare var SVGPathSegCurvetoQuadraticSmoothRel: { - prototype: SVGPathSegCurvetoQuadraticSmoothRel; - new(): SVGPathSegCurvetoQuadraticSmoothRel; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLTableRowElement { - align: string; -} - -interface DOML2DeprecatedBorderStyle_HTMLObjectElement { - border: string; -} - -interface MSHTMLSpanElementExtensions { -} - -interface MSHTMLObjectElementExtensions { - object: Object; - alt: string; - classid: string; - altHtml: string; - BaseHref: string; -} - -interface DOML2DeprecatedListSpaceReduction { - compact: bool; -} - -interface CSS3Properties { - textAlignLast: string; - textUnderlinePosition: string; - wordWrap: string; - borderTopLeftRadius: string; - backgroundClip: string; - msTransformOrigin: string; - opacity: string; - overflowY: string; - boxShadow: string; - backgroundSize: string; - wordBreak: string; - boxSizing: string; - rubyOverhang: string; - rubyAlign: string; - textJustify: string; - borderRadius: string; - overflowX: string; - borderTopRightRadius: string; - msTransform: string; - borderBottomLeftRadius: string; - rubyPosition: string; - borderBottomRightRadius: string; - backgroundOrigin: string; - textOverflow: string; -} - -interface MSScriptHost { -} -declare var MSScriptHost: { - prototype: MSScriptHost; - new(): MSScriptHost; -} - -interface SVGClipPathElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { - clipPathUnits: SVGAnimatedEnumeration; -} -declare var SVGClipPathElement: { - prototype: SVGClipPathElement; - new(): SVGClipPathElement; -} - -interface MouseEvent extends UIEvent, MSMouseEventExtensions { - pageX: number; - offsetY: number; - x: number; - y: number; - altKey: bool; - metaKey: bool; - ctrlKey: bool; - offsetX: number; - screenX: number; - clientY: number; - shiftKey: bool; - screenY: number; - relatedTarget: EventTarget; - button: number; - pageY: number; - buttons: number; - clientX: number; - initMouseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget): void; - getModifierState(keyArg: string): bool; -} -declare var MouseEvent: { - prototype: MouseEvent; - new(): MouseEvent; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLTableElement { - align: string; -} - -interface RangeException { - code: number; - message: string; - toString(): string; - INVALID_NODE_TYPE_ERR: number; - BAD_BOUNDARYPOINTS_ERR: number; -} -declare var RangeException: { - prototype: RangeException; - new(): RangeException; - INVALID_NODE_TYPE_ERR: number; - BAD_BOUNDARYPOINTS_ERR: number; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLHRElement { - align: string; -} - -interface SVGTextPositioningElement extends SVGTextContentElement { - y: SVGAnimatedLengthList; - rotate: SVGAnimatedNumberList; - dy: SVGAnimatedLengthList; - x: SVGAnimatedLengthList; - dx: SVGAnimatedLengthList; -} -declare var SVGTextPositioningElement: { - prototype: SVGTextPositioningElement; - new(): SVGTextPositioningElement; -} - -interface HTMLAppletElement extends HTMLElement, DOML2DeprecatedWidthStyle_HTMLAppletElement, DOML2DeprecatedMarginStyle_HTMLObjectElement, MSHTMLAppletElementExtensions, MSDataBindingExtensions, MSDataBindingRecordSetExtensions, DOML2DeprecatedAlignmentStyle_HTMLObjectElement { - object: string; - archive: string; - codeBase: string; - alt: string; - name: string; - height: string; - code: string; -} -declare var HTMLAppletElement: { - prototype: HTMLAppletElement; - new(): HTMLAppletElement; -} - -interface MSHTMLFieldSetElementExtensions extends DOML2DeprecatedAlignmentStyle_HTMLFieldSetElement { -} - -interface DocumentEvent { - createEvent(eventInterface: string): Event; -} - -interface MSHTMLUnknownElementExtensions { -} - -interface TextMetrics { - width: number; -} -declare var TextMetrics: { - prototype: TextMetrics; - new(): TextMetrics; -} - -interface DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { - noWrap: bool; -} - -interface HTMLOListElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, DOML2DeprecatedListSpaceReduction, MSHTMLOListElementExtensions { - start: number; -} -declare var HTMLOListElement: { - prototype: HTMLOListElement; - new(): HTMLOListElement; -} - -interface MSHTMLTableCaptionElementExtensions { - vAlign: string; -} - -interface SVGAnimatedString { - animVal: string; - baseVal: string; -} -declare var SVGAnimatedString: { - prototype: SVGAnimatedString; - new(): SVGAnimatedString; -} - -interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { - y: number; -} -declare var SVGPathSegLinetoVerticalRel: { - prototype: SVGPathSegLinetoVerticalRel; - new(): SVGPathSegLinetoVerticalRel; -} - -interface CDATASection extends Text { -} -declare var CDATASection: { - prototype: CDATASection; - new(): CDATASection; -} - -interface StyleMedia { - type: string; - matchMedium(mediaquery: string): bool; -} -declare var StyleMedia: { - prototype: StyleMedia; - new(): StyleMedia; -} - -interface TextRange { - boundingLeft: number; - htmlText: string; - offsetLeft: number; - boundingWidth: number; - boundingHeight: number; - boundingTop: number; - text: string; - offsetTop: number; - moveToPoint(x: number, y: number): void; - queryCommandValue(cmdID: string): any; - getBookmark(): string; - move(Unit: string, Count?: number): number; - queryCommandIndeterm(cmdID: string): bool; - scrollIntoView(fStart?: bool): void; - findText(string: string, count?: number, flags?: number): bool; - execCommand(cmdID: string, showUI?: bool, value?: any): bool; - getBoundingClientRect(): ClientRect; - moveToBookmark(Bookmark: string): bool; - isEqual(range: TextRange): bool; - duplicate(): TextRange; - collapse(Start?: bool): void; - queryCommandText(cmdID: string): string; - select(): void; - pasteHTML(html: string): void; - inRange(range: TextRange): bool; - moveEnd(Unit: string, Count?: number): number; - getClientRects(): ClientRectList; - moveStart(Unit: string, Count?: number): number; - parentElement(): Element; - queryCommandState(cmdID: string): bool; - compareEndPoints(how: string, sourceRange: TextRange): number; - execCommandShowHelp(cmdID: string): bool; - moveToElementText(element: Element): void; - expand(Unit: string): bool; - queryCommandSupported(cmdID: string): bool; - setEndPoint(how: string, SourceRange: TextRange): void; - queryCommandEnabled(cmdID: string): bool; -} -declare var TextRange: { - prototype: TextRange; - new(): TextRange; -} - -interface HTMLSelectElement extends HTMLElement, MSHTMLCollectionExtensions, MSDataBindingExtensions, MSHTMLSelectElementExtensions { - options: HTMLSelectElement; - value: string; - form: HTMLFormElement; - name: string; - size: number; - length: number; - selectedIndex: number; - multiple: bool; - type: string; - remove(index?: number): void; - add(element: HTMLElement, before?: any): void; - item(name?: any, index?: any): any; - (name: any, index: any): any; - namedItem(name: string): any; - [name: string]: any; - (name: string): any; -} -declare var HTMLSelectElement: { - prototype: HTMLSelectElement; - new(): HTMLSelectElement; -} - -interface CSSStyleSheet extends StyleSheet, MSCSSStyleSheetExtensions { - ownerRule: CSSRule; - cssRules: CSSRuleList; - insertRule(rule: string, index?: number): number; - deleteRule(index?: number): void; -} -declare var CSSStyleSheet: { - prototype: CSSStyleSheet; - new(): CSSStyleSheet; -} - -interface HTMLBlockElement extends HTMLElement, DOML2DeprecatedTextFlowControl_HTMLBlockElement, DOML2DeprecatedWidthStyle_HTMLBlockElement { - cite: string; -} -declare var HTMLBlockElement: { - prototype: HTMLBlockElement; - new(): HTMLBlockElement; -} - -interface SVGTests { - requiredFeatures: SVGStringList; - requiredExtensions: SVGStringList; - systemLanguage: SVGStringList; - hasExtension(extension: string): bool; -} - -interface MSSelection { - type: string; - typeDetail: string; - createRange(): TextRange; - clear(): void; - createRangeCollection(): TextRangeCollection; - empty(): void; -} -declare var MSSelection: { - prototype: MSSelection; - new(): MSSelection; -} - -interface MSHTMLDListElementExtensions { -} - -interface HTMLMetaElement extends HTMLElement, MSHTMLMetaElementExtensions { - httpEquiv: string; - name: string; - content: string; - scheme: string; -} -declare var HTMLMetaElement: { - prototype: HTMLMetaElement; - new(): HTMLMetaElement; -} - -interface Selection { - isCollapsed: bool; - anchorNode: Node; - focusNode: Node; - anchorOffset: number; - focusOffset: number; - rangeCount: number; - addRange(range: Range): void; - collapseToEnd(): void; - toString(): string; - selectAllChildren(parentNode: Node): void; - getRangeAt(index: number): Range; - collapse(parentNode: Node, offset: number): void; - removeAllRanges(): void; - collapseToStart(): void; - deleteFromDocument(): void; - removeRange(range: Range): void; -} -declare var Selection: { - prototype: Selection; - new(): Selection; -} - -interface SVGAnimatedAngle { - animVal: SVGAngle; - baseVal: SVGAngle; -} -declare var SVGAnimatedAngle: { - prototype: SVGAnimatedAngle; - new(): SVGAnimatedAngle; -} - -interface SVGPatternElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGFitToViewBox, SVGURIReference { - patternUnits: SVGAnimatedEnumeration; - y: SVGAnimatedLength; - width: SVGAnimatedLength; - x: SVGAnimatedLength; - patternContentUnits: SVGAnimatedEnumeration; - patternTransform: SVGAnimatedTransformList; - height: SVGAnimatedLength; -} -declare var SVGPatternElement: { - prototype: SVGPatternElement; - new(): SVGPatternElement; -} - -interface SVGScriptElement extends SVGElement, SVGURIReference { - type: string; -} -declare var SVGScriptElement: { - prototype: SVGScriptElement; - new(): SVGScriptElement; -} - -interface HTMLDDElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDDElement { -} -declare var HTMLDDElement: { - prototype: HTMLDDElement; - new(): HTMLDDElement; -} - -interface NodeIterator { - whatToShow: number; - filter: NodeFilterCallback; - root: Node; - expandEntityReferences: bool; - nextNode(): Node; - detach(): void; - previousNode(): Node; -} -declare var NodeIterator: { - prototype: NodeIterator; - new(): NodeIterator; -} - -interface CSSStyleRule extends CSSRule, MSCSSStyleRuleExtensions { - selectorText: string; - style: MSStyleCSSProperties; -} -declare var CSSStyleRule: { - prototype: CSSStyleRule; - new(): CSSStyleRule; -} - -interface MSDataBindingRecordSetReadonlyExtensions { - recordset: Object; - namedRecordset(dataMember: string, hierarchy?: any): Object; -} - -interface HTMLLinkElement extends HTMLElement, MSLinkStyleExtensions, LinkStyle { - rel: string; - target: string; - href: string; - media: string; - rev: string; - type: string; - charset: string; - hreflang: string; -} -declare var HTMLLinkElement: { - prototype: HTMLLinkElement; - new(): HTMLLinkElement; -} - -interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { - viewTarget: SVGStringList; -} -declare var SVGViewElement: { - prototype: SVGViewElement; - new(): SVGViewElement; -} - -interface MSHTMLAppletElementExtensions extends DOML2DeprecatedBorderStyle_HTMLObjectElement { - codeType: string; - standby: string; - classid: string; - useMap: string; - form: HTMLFormElement; - data: string; - contentDocument: Document; - altHtml: string; - declare: bool; - type: string; - BaseHref: string; -} - -interface SVGLocatable { - farthestViewportElement: SVGElement; - nearestViewportElement: SVGElement; - getBBox(): SVGRect; - getTransformToElement(element: SVGElement): SVGMatrix; - getCTM(): SVGMatrix; - getScreenCTM(): SVGMatrix; -} - -interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, MSHTMLFontElementExtensions, DOML2DeprecatedSizeProperty { - face: string; -} -declare var HTMLFontElement: { - prototype: HTMLFontElement; - new(): HTMLFontElement; -} - -interface MSHTMLTableElementExtensions { - cells: HTMLCollection; - height: any; - cols: number; - moveRow(indexFrom?: number, indexTo?: number): Object; -} - -interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { -} -declare var SVGTitleElement: { - prototype: SVGTitleElement; - new(): SVGTitleElement; -} - -interface ControlRangeCollection { - length: number; - queryCommandValue(cmdID: string): any; - remove(index: number): void; - add(item: Element): void; - queryCommandIndeterm(cmdID: string): bool; - scrollIntoView(varargStart?: any): void; - item(index: number): Element; - [index: number]: Element; - execCommand(cmdID: string, showUI?: bool, value?: any): bool; - addElement(item: Element): void; - queryCommandState(cmdID: string): bool; - queryCommandSupported(cmdID: string): bool; - queryCommandEnabled(cmdID: string): bool; - queryCommandText(cmdID: string): string; - select(): void; -} -declare var ControlRangeCollection: { - prototype: ControlRangeCollection; - new(): ControlRangeCollection; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLImageElement { - align: string; -} - -interface MSHTMLFrameElementExtensions { - width: any; - contentWindow: Window; - onload: (ev: Event) => any; - frameBorder: string; - height: any; - border: string; - frameSpacing: any; -} - -interface MSNamespaceInfo extends MSEventAttachmentTarget { - urn: string; - onreadystatechange: (ev: Event) => any; - name: string; - readyState: string; - doImport(implementationUrl: string): void; -} -declare var MSNamespaceInfo: { - prototype: MSNamespaceInfo; - new(): MSNamespaceInfo; -} - -interface WindowSessionStorage { - sessionStorage: Storage; -} - -interface SVGAnimatedTransformList { - animVal: SVGTransformList; - baseVal: SVGTransformList; -} -declare var SVGAnimatedTransformList: { - prototype: SVGAnimatedTransformList; - new(): SVGAnimatedTransformList; -} - -interface HTMLTableCaptionElement extends HTMLElement, MSHTMLTableCaptionElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableCaptionElement { -} -declare var HTMLTableCaptionElement: { - prototype: HTMLTableCaptionElement; - new(): HTMLTableCaptionElement; -} - -interface HTMLOptionElement extends HTMLElement, MSDataBindingExtensions { - index: number; - defaultSelected: bool; - value: string; - text: string; - form: HTMLFormElement; - label: string; - selected: bool; -} -declare var HTMLOptionElement: { - prototype: HTMLOptionElement; - new(): HTMLOptionElement; -} - -interface HTMLMapElement extends HTMLElement { - name: string; - areas: HTMLAreasCollection; -} -declare var HTMLMapElement: { - prototype: HTMLMapElement; - new(): HTMLMapElement; -} - -interface HTMLMenuElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLMenuElementExtensions { - type: string; -} -declare var HTMLMenuElement: { - prototype: HTMLMenuElement; - new(): HTMLMenuElement; -} - -interface MouseWheelEvent extends MouseEvent { - wheelDelta: number; - initMouseWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; -} -declare var MouseWheelEvent: { - prototype: MouseWheelEvent; - new(): MouseWheelEvent; -} - -interface SVGFitToViewBox { - viewBox: SVGAnimatedRect; - preserveAspectRatio: SVGAnimatedPreserveAspectRatio; -} - -interface MSHTMLAnchorElementExtensions { - nameProp: string; - protocolLong: string; - urn: string; - mimeType: string; - Methods: string; -} - -interface SVGPointList { - numberOfItems: number; - replaceItem(newItem: SVGPoint, index: number): SVGPoint; - getItem(index: number): SVGPoint; - clear(): void; - appendItem(newItem: SVGPoint): SVGPoint; - initialize(newItem: SVGPoint): SVGPoint; - removeItem(index: number): SVGPoint; - insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; -} -declare var SVGPointList: { - prototype: SVGPointList; - new(): SVGPointList; -} - -interface MSElementCSSInlineStyleExtensions { - doScroll(component?: any): void; - componentFromPoint(x: number, y: number): string; -} - -interface SVGAnimatedLengthList { - animVal: SVGLengthList; - baseVal: SVGLengthList; -} -declare var SVGAnimatedLengthList: { - prototype: SVGAnimatedLengthList; - new(): SVGAnimatedLengthList; -} - -interface MSHTMLTableDataCellElementExtensions { -} - -interface Window extends ViewCSS, MSEventAttachmentTarget, MSWindowExtensions, WindowPerformance, ScreenView, EventTarget, WindowLocalStorage, WindowSessionStorage, WindowTimers { - ondragend: (ev: DragEvent) => any; - onkeydown: (ev: KeyboardEvent) => any; - ondragover: (ev: DragEvent) => any; - onkeyup: (ev: KeyboardEvent) => any; - onreset: (ev: Event) => any; - onmouseup: (ev: MouseEvent) => any; - ondragstart: (ev: DragEvent) => any; - ondrag: (ev: DragEvent) => any; - onmouseover: (ev: MouseEvent) => any; - ondragleave: (ev: DragEvent) => any; - history: History; - name: string; - onafterprint: (ev: Event) => any; - onpause: (ev: Event) => any; - onbeforeprint: (ev: Event) => any; - top: Window; - onmousedown: (ev: MouseEvent) => any; - onseeked: (ev: Event) => any; - opener: Window; - onclick: (ev: MouseEvent) => any; - onwaiting: (ev: Event) => any; - ononline: (ev: Event) => any; - ondurationchange: (ev: Event) => any; - frames: Window; - onblur: (ev: FocusEvent) => any; - onemptied: (ev: Event) => any; - onseeking: (ev: Event) => any; - oncanplay: (ev: Event) => any; - onstalled: (ev: Event) => any; - onmousemove: (ev: MouseEvent) => any; - onoffline: (ev: Event) => any; - length: number; - onbeforeunload: (ev: BeforeUnloadEvent) => any; - onratechange: (ev: Event) => any; - onstorage: (ev: StorageEvent) => any; - onloadstart: (ev: Event) => any; - ondragenter: (ev: DragEvent) => any; - onsubmit: (ev: Event) => any; - self: Window; - onprogress: (ev: any) => any; - ondblclick: (ev: MouseEvent) => any; - oncontextmenu: (ev: MouseEvent) => any; - onchange: (ev: Event) => any; - onloadedmetadata: (ev: Event) => any; - onplay: (ev: Event) => any; - onerror: ErrorFunction; - onplaying: (ev: Event) => any; - parent: Window; - location: Location; - oncanplaythrough: (ev: Event) => any; - onabort: (ev: UIEvent) => any; - onreadystatechange: (ev: Event) => any; - onkeypress: (ev: KeyboardEvent) => any; - frameElement: Element; - onloadeddata: (ev: Event) => any; - onsuspend: (ev: Event) => any; - window: Window; - onfocus: (ev: FocusEvent) => any; - onmessage: (ev: MessageEvent) => any; - ontimeupdate: (ev: Event) => any; - onresize: (ev: UIEvent) => any; - navigator: Navigator; - onselect: (ev: UIEvent) => any; - ondrop: (ev: DragEvent) => any; - onmouseout: (ev: MouseEvent) => any; - onended: (ev: Event) => any; - onhashchange: (ev: Event) => any; - onunload: (ev: Event) => any; - onscroll: (ev: UIEvent) => any; - onmousewheel: (ev: MouseWheelEvent) => any; - onload: (ev: Event) => any; - onvolumechange: (ev: Event) => any; - oninput: (ev: Event) => any; - alert(message?: string): void; - focus(): void; - print(): void; - prompt(message?: string, defaul?: string): string; - toString(): string; - open(url?: string, target?: string, features?: string, replace?: bool): Window; - close(): void; - confirm(message?: string): bool; - postMessage(message: any, targetOrigin: string, ports?: any): void; - showModalDialog(url?: string, argument?: any, options?: any): any; - blur(): void; - getSelection(): Selection; -} -declare var Window: { - prototype: Window; - new(): Window; -} - -interface SVGAnimatedPreserveAspectRatio { - animVal: SVGPreserveAspectRatio; - baseVal: SVGPreserveAspectRatio; -} -declare var SVGAnimatedPreserveAspectRatio: { - prototype: SVGAnimatedPreserveAspectRatio; - new(): SVGAnimatedPreserveAspectRatio; -} - -interface MSSiteModeEvent extends Event { - buttonID: number; - actionURL: string; -} -declare var MSSiteModeEvent: { - prototype: MSSiteModeEvent; - new(): MSSiteModeEvent; -} - -interface MSCSSStyleRuleExtensions { - readOnly: bool; -} - -interface StyleSheetPageList { - length: number; - item(index: number): StyleSheetPage; - [index: number]: StyleSheetPage; -} -declare var StyleSheetPageList: { - prototype: StyleSheetPageList; - new(): StyleSheetPageList; -} - -interface HTMLCollection extends MSHTMLCollectionExtensions { - length: number; - item(nameOrIndex?: any, optionalIndex?: any): Element; - (nameOrIndex: any, optionalIndex: any): Element; - namedItem(name: string): Element; - [index: number]: Element; - [name: string]: Element; - (name: string): Element; -} -declare var HTMLCollection: { - prototype: HTMLCollection; - new(): HTMLCollection; -} - -interface MSCSSProperties extends CSSStyleDeclaration, MSCSSStyleDeclarationExtensions { - scrollbarShadowColor: string; - scrollbarHighlightColor: string; - layoutGridChar: string; - layoutGridType: string; - textAutospace: string; - textKashidaSpace: string; - writingMode: string; - scrollbarFaceColor: string; - backgroundPositionY: string; - lineBreak: string; - imeMode: string; - msBlockProgression: string; - layoutGridLine: string; - scrollbarBaseColor: string; - layoutGrid: string; - layoutFlow: string; - textKashida: string; - filter: string; - zoom: string; - scrollbarArrowColor: string; - behavior: string; - backgroundPositionX: string; - accelerator: string; - layoutGridMode: string; - textJustifyTrim: string; - scrollbar3dLightColor: string; - msInterpolationMode: string; - scrollbarTrackColor: string; - scrollbarDarkShadowColor: string; - styleFloat: string; -} -declare var MSCSSProperties: { - prototype: MSCSSProperties; - new(): MSCSSProperties; -} - -interface HTMLImageElement extends HTMLElement, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle_HTMLImageElement, MSImageResourceExtensions, MSHTMLImageElementExtensions, MSDataBindingExtensions, MSResourceMetadata { - width: number; - naturalHeight: number; - alt: string; - src: string; - useMap: string; - naturalWidth: number; - name: string; - height: number; - longDesc: string; - isMap: bool; - complete: bool; -} -declare var HTMLImageElement: { - prototype: HTMLImageElement; - new(): HTMLImageElement; -} - -interface HTMLAreaElement extends HTMLElement, MSHTMLAreaElementExtensions { - protocol: string; - search: string; - alt: string; - coords: string; - hostname: string; - port: string; - pathname: string; - host: string; - hash: string; - target: string; - href: string; - noHref: bool; - shape: string; - toString(): string; -} -declare var HTMLAreaElement: { - prototype: HTMLAreaElement; - new(): HTMLAreaElement; -} - -interface EventTarget { - removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; - addEventListener(type: string, listener: EventListener, useCapture?: bool): void; - dispatchEvent(evt: Event): bool; -} - -interface SVGAngle { - valueAsString: string; - valueInSpecifiedUnits: number; - value: number; - unitType: number; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - convertToSpecifiedUnits(unitType: number): void; - SVG_ANGLETYPE_RAD: number; - SVG_ANGLETYPE_UNKNOWN: number; - SVG_ANGLETYPE_UNSPECIFIED: number; - SVG_ANGLETYPE_DEG: number; - SVG_ANGLETYPE_GRAD: number; -} -declare var SVGAngle: { - prototype: SVGAngle; - new(): SVGAngle; - SVG_ANGLETYPE_RAD: number; - SVG_ANGLETYPE_UNKNOWN: number; - SVG_ANGLETYPE_UNSPECIFIED: number; - SVG_ANGLETYPE_DEG: number; - SVG_ANGLETYPE_GRAD: number; -} - -interface HTMLButtonElement extends HTMLElement, MSHTMLButtonElementExtensions, MSDataBindingExtensions { - value: string; - form: HTMLFormElement; - name: string; - type: string; -} -declare var HTMLButtonElement: { - prototype: HTMLButtonElement; - new(): HTMLButtonElement; -} - -interface MSHTMLLabelElementExtensions { -} - -interface HTMLSourceElement extends HTMLElement { - src: string; - media: string; - type: string; -} -declare var HTMLSourceElement: { - prototype: HTMLSourceElement; - new(): HTMLSourceElement; -} - -interface CanvasGradient { - addColorStop(offset: number, color: string): void; -} -declare var CanvasGradient: { - prototype: CanvasGradient; - new(): CanvasGradient; -} - -interface KeyboardEvent extends UIEvent, KeyboardEventExtensions { - location: number; - shiftKey: bool; - locale: string; - key: string; - altKey: bool; - metaKey: bool; - char: string; - ctrlKey: bool; - repeat: bool; - getModifierState(keyArg: string): bool; - initKeyboardEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, keyArg: string, locationArg: number, modifiersListArg: string, repeat: bool, locale: string): void; - DOM_KEY_LOCATION_RIGHT: number; - DOM_KEY_LOCATION_STANDARD: number; - DOM_KEY_LOCATION_LEFT: number; - DOM_KEY_LOCATION_NUMPAD: number; - DOM_KEY_LOCATION_JOYSTICK: number; - DOM_KEY_LOCATION_MOBILE: number; -} -declare var KeyboardEvent: { - prototype: KeyboardEvent; - new(): KeyboardEvent; - DOM_KEY_LOCATION_RIGHT: number; - DOM_KEY_LOCATION_STANDARD: number; - DOM_KEY_LOCATION_LEFT: number; - DOM_KEY_LOCATION_NUMPAD: number; - DOM_KEY_LOCATION_JOYSTICK: number; - DOM_KEY_LOCATION_MOBILE: number; -} - -interface Document extends Node, DocumentStyle, DocumentRange, HTMLDocument, NodeSelector, DocumentEvent, DocumentTraversal, DocumentView, SVGDocument { - doctype: DocumentType; - xmlVersion: string; - implementation: DOMImplementation; - xmlEncoding: string; - xmlStandalone: bool; - documentElement: HTMLElement; - inputEncoding: string; - createElement(tagName: string): HTMLElement; - adoptNode(source: Node): Node; - createComment(data: string): Comment; - createDocumentFragment(): DocumentFragment; - getElementsByTagName(tagname: string): NodeList; - getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; - createProcessingInstruction(target: string, data: string): ProcessingInstruction; - createElementNS(namespaceURI: string, qualifiedName: string): Element; - createAttribute(name: string): Attr; - createTextNode(data: string): Text; - importNode(importedNode: Node, deep: bool): Node; - createCDATASection(data: string): CDATASection; - createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; - getElementById(elementId: string): HTMLElement; -} -declare var Document: { - prototype: Document; - new(): Document; -} - -interface MessageEvent extends Event { - source: Window; - origin: string; - data: any; - initMessageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; -} -declare var MessageEvent: { - prototype: MessageEvent; - new(): MessageEvent; -} - -interface SVGElement extends Element, SVGElementEventHandlers { - xmlbase: string; - viewportElement: SVGElement; - id: string; - ownerSVGElement: SVGSVGElement; -} -declare var SVGElement: { - prototype: SVGElement; - new(): SVGElement; -} - -interface HTMLScriptElement extends HTMLElement { - defer: bool; - text: string; - src: string; - htmlFor: string; - charset: string; - type: string; - event: string; -} -declare var HTMLScriptElement: { - prototype: HTMLScriptElement; - new(): HTMLScriptElement; -} - -interface MSHTMLBodyElementExtensions extends DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { - scroll: string; - bottomMargin: any; - topMargin: any; - rightMargin: any; - bgProperties: string; - leftMargin: any; - createTextRange(): TextRange; -} - -interface HTMLTableRowElement extends HTMLElement, MSBorderColorHighlightStyle_HTMLTableRowElement, HTMLTableAlignment, MSBorderColorStyle_HTMLTableRowElement, DOML2DeprecatedAlignmentStyle_HTMLTableRowElement, DOML2DeprecatedBackgroundColorStyle, MSHTMLTableRowElementExtensions { - rowIndex: number; - cells: HTMLCollection; - sectionRowIndex: number; - deleteCell(index?: number): void; - insertCell(index?: number): HTMLElement; -} -declare var HTMLTableRowElement: { - prototype: HTMLTableRowElement; - new(): HTMLTableRowElement; -} - -interface MSCommentExtensions { - text: string; -} - -interface DOML2DeprecatedMarginStyle_HTMLMarqueeElement { - vspace: number; - hspace: number; -} - -interface MSCSSRuleList { - length: number; - item(index?: number): CSSStyleRule; - [index: number]: CSSStyleRule; -} -declare var MSCSSRuleList: { - prototype: MSCSSRuleList; - new(): MSCSSRuleList; -} - -interface CanvasRenderingContext2D { - shadowOffsetX: number; - lineWidth: number; - miterLimit: number; - canvas: HTMLCanvasElement; - strokeStyle: any; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - shadowOffsetY: number; - fillStyle: any; - lineCap: string; - shadowBlur: number; - textAlign: string; - textBaseline: string; - shadowColor: string; - lineJoin: string; - restore(): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - save(): void; - arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: bool): void; - measureText(text: string): TextMetrics; - isPointInPath(x: number, y: number): bool; - quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - rotate(angle: number): void; - fillText(text: string, x: number, y: number, maxWidth?: number): void; - translate(x: number, y: number): void; - scale(x: number, y: number): void; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - lineTo(x: number, y: number): void; - fill(): void; - createPattern(image: HTMLElement, repetition: string): CanvasPattern; - closePath(): void; - rect(x: number, y: number, w: number, h: number): void; - clip(): void; - createImageData(imageDataOrSw: any, sh?: number): ImageData; - clearRect(x: number, y: number, w: number, h: number): void; - moveTo(x: number, y: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - fillRect(x: number, y: number, w: number, h: number): void; - bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; - drawImage(image: HTMLElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - beginPath(): void; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; -} -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; -} - -interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { - x: number; -} -declare var SVGPathSegLinetoHorizontalAbs: { - prototype: SVGPathSegLinetoHorizontalAbs; - new(): SVGPathSegLinetoHorizontalAbs; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLObjectElement { - align: string; -} - -interface DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { - border: string; -} - -interface MSHTMLElementRangeExtensions { - createControlRange(): ControlRangeCollection; -} - -interface SVGPathSegArcAbs extends SVGPathSeg { - y: number; - sweepFlag: bool; - r2: number; - x: number; - angle: number; - r1: number; - largeArcFlag: bool; -} -declare var SVGPathSegArcAbs: { - prototype: SVGPathSegArcAbs; - new(): SVGPathSegArcAbs; -} - -interface MSScreenExtensions { - deviceXDPI: number; - fontSmoothingEnabled: bool; - bufferDepth: number; - logicalXDPI: number; - systemXDPI: number; - logicalYDPI: number; - systemYDPI: number; - updateInterval: number; - deviceYDPI: number; -} - -interface HTMLHtmlElement extends HTMLElement, HTMLHtmlElementDOML2Deprecated { -} -declare var HTMLHtmlElement: { - prototype: HTMLHtmlElement; - new(): HTMLHtmlElement; -} - -interface MSBorderColorStyle { - borderColor: any; -} - -interface SVGTransformList { - numberOfItems: number; - getItem(index: number): SVGTransform; - consolidate(): SVGTransform; - clear(): void; - appendItem(newItem: SVGTransform): SVGTransform; - initialize(newItem: SVGTransform): SVGTransform; - removeItem(index: number): SVGTransform; - insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; - replaceItem(newItem: SVGTransform, index: number): SVGTransform; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; -} -declare var SVGTransformList: { - prototype: SVGTransformList; - new(): SVGTransformList; -} - -interface SVGPathSegClosePath extends SVGPathSeg { -} -declare var SVGPathSegClosePath: { - prototype: SVGPathSegClosePath; - new(): SVGPathSegClosePath; -} - -interface DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions { - vspace: number; - hspace: number; -} - -interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSHTMLFrameElementExtensions, MSDataBindingExtensions, MSBorderColorStyle_HTMLFrameElement { - scrolling: string; - marginHeight: string; - src: string; - name: string; - marginWidth: string; - contentDocument: Document; - longDesc: string; - noResize: bool; -} -declare var HTMLFrameElement: { - prototype: HTMLFrameElement; - new(): HTMLFrameElement; -} - -interface SVGAnimatedLength { - animVal: SVGLength; - baseVal: SVGLength; -} -declare var SVGAnimatedLength: { - prototype: SVGAnimatedLength; - new(): SVGAnimatedLength; -} - -interface CSSMediaRule extends CSSRule { - media: MediaList; - cssRules: CSSRuleList; - insertRule(rule: string, index?: number): number; - deleteRule(index?: number): void; -} -declare var CSSMediaRule: { - prototype: CSSMediaRule; - new(): CSSMediaRule; -} - -interface HTMLQuoteElement extends HTMLElement, MSHTMLQuoteElementExtensions { - cite: string; -} -declare var HTMLQuoteElement: { - prototype: HTMLQuoteElement; - new(): HTMLQuoteElement; -} - -interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { -} -declare var SVGDefsElement: { - prototype: SVGDefsElement; - new(): SVGDefsElement; -} - -interface SVGAnimatedPoints { - points: SVGPointList; - animatedPoints: SVGPointList; -} - -interface WindowModal { - dialogArguments: any; - returnValue: any; -} - -interface MSHTMLButtonElementExtensions { - status: any; - createTextRange(): TextRange; -} - -interface XMLHttpRequest extends EventTarget, MSXMLHttpRequestExtensions { - onreadystatechange: (ev: Event) => any; - status: number; - onload: (ev: Event) => any; - readyState: number; - responseText: string; - responseXML: Document; - statusText: string; - open(method: string, url: string, async?: bool, user?: string, password?: string): void; - send(data?: any): void; - abort(): void; - getAllResponseHeaders(): string; - setRequestHeader(header: string, value: string): void; - getResponseHeader(header: string): string; - LOADING: number; - DONE: number; - UNSENT: number; - OPENED: number; - HEADERS_RECEIVED: number; -} -declare var XMLHttpRequest: { - prototype: XMLHttpRequest; - new (): XMLHttpRequest; - LOADING: number; - DONE: number; - UNSENT: number; - OPENED: number; - HEADERS_RECEIVED: number; -} - -interface HTMLTableHeaderCellElement extends HTMLTableCellElement, HTMLTableHeaderCellScope { -} -declare var HTMLTableHeaderCellElement: { - prototype: HTMLTableHeaderCellElement; - new(): HTMLTableHeaderCellElement; -} - -interface HTMLDListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLDListElementExtensions { -} -declare var HTMLDListElement: { - prototype: HTMLDListElement; - new(): HTMLDListElement; -} - -interface MSDataBindingExtensions { - dataSrc: string; - dataFormatAs: string; - dataFld: string; -} - -interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { - ry: SVGAnimatedLength; - cx: SVGAnimatedLength; - rx: SVGAnimatedLength; - cy: SVGAnimatedLength; -} -declare var SVGEllipseElement: { - prototype: SVGEllipseElement; - new(): SVGEllipseElement; -} - -interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { - x: number; -} -declare var SVGPathSegLinetoHorizontalRel: { - prototype: SVGPathSegLinetoHorizontalRel; - new(): SVGPathSegLinetoHorizontalRel; -} - -interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { - target: SVGAnimatedString; -} -declare var SVGAElement: { - prototype: SVGAElement; - new(): SVGAElement; -} - -interface MSHTMLMetaElementExtensions { - url: string; - charset: string; -} - -interface SVGStylable { - className: SVGAnimatedString; - style: CSSStyleDeclaration; -} - -interface MSHTMLTableCellElementExtensions { -} - -interface HTMLFrameSetElement extends HTMLElement, MSHTMLFrameSetElementExtensions, MSBorderColorStyle_HTMLFrameSetElement { - onresize: (ev: UIEvent) => any; - ononline: (ev: Event) => any; - onafterprint: (ev: Event) => any; - onbeforeprint: (ev: Event) => any; - onoffline: (ev: Event) => any; - rows: string; - cols: string; - onblur: (ev: FocusEvent) => any; - onunload: (ev: Event) => any; - onhashchange: (ev: Event) => any; - onfocus: (ev: FocusEvent) => any; - onmessage: (ev: MessageEvent) => any; - onload: (ev: Event) => any; - onerror: (ev: Event) => any; - onbeforeunload: (ev: BeforeUnloadEvent) => any; - onstorage: (ev: StorageEvent) => any; -} -declare var HTMLFrameSetElement: { - prototype: HTMLFrameSetElement; - new(): HTMLFrameSetElement; -} - -interface SVGTransformable extends SVGLocatable { - transform: SVGAnimatedTransformList; -} - -interface Screen extends MSScreenExtensions { - width: number; - colorDepth: number; - availWidth: number; - pixelDepth: number; - availHeight: number; - height: number; -} -declare var Screen: { - prototype: Screen; - new(): Screen; -} - -interface NavigatorGeolocation { - geolocation: Geolocation; -} - -interface Coordinates { - altitudeAccuracy: number; - longitude: number; - latitude: number; - speed: number; - heading: number; - altitude: number; - accuracy: number; -} -declare var Coordinates: { - prototype: Coordinates; - new(): Coordinates; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLTableColElement { - align: string; -} - -interface EventListener { - (evt: Event): void; -} - -interface SVGLangSpace { - xmllang: string; - xmlspace: string; -} - -interface DataTransfer { - effectAllowed: string; - dropEffect: string; - clearData(format?: string): bool; - setData(format: string, data: string): bool; - getData(format: string): string; -} -declare var DataTransfer: { - prototype: DataTransfer; - new(): DataTransfer; -} - -interface FocusEvent extends UIEvent { - relatedTarget: EventTarget; - initFocusEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, relatedTargetArg: EventTarget): void; -} -declare var FocusEvent: { - prototype: FocusEvent; - new(): FocusEvent; -} - -interface Range { - startOffset: number; - collapsed: bool; - endOffset: number; - startContainer: Node; - endContainer: Node; - commonAncestorContainer: Node; - setStart(refNode: Node, offset: number): void; - setEndBefore(refNode: Node): void; - setStartBefore(refNode: Node): void; - selectNode(refNode: Node): void; - detach(): void; - getBoundingClientRect(): ClientRect; - toString(): string; - compareBoundaryPoints(how: number, sourceRange: Range): number; - insertNode(newNode: Node): void; - collapse(toStart: bool): void; - selectNodeContents(refNode: Node): void; - cloneContents(): DocumentFragment; - setEnd(refNode: Node, offset: number): void; - cloneRange(): Range; - getClientRects(): ClientRectList; - surroundContents(newParent: Node): void; - deleteContents(): void; - setStartAfter(refNode: Node): void; - extractContents(): DocumentFragment; - setEndAfter(refNode: Node): void; - END_TO_END: number; - START_TO_START: number; - START_TO_END: number; - END_TO_START: number; -} -declare var Range: { - prototype: Range; - new(): Range; - END_TO_END: number; - START_TO_START: number; - START_TO_END: number; - END_TO_START: number; -} - -interface MSHTMLPreElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { - cite: string; -} - -interface SVGPoint { - y: number; - x: number; - matrixTransform(matrix: SVGMatrix): SVGPoint; -} -declare var SVGPoint: { - prototype: SVGPoint; - new(): SVGPoint; -} - -interface MSPluginsCollection { - length: number; - refresh(reload?: bool): void; -} -declare var MSPluginsCollection: { - prototype: MSPluginsCollection; - new(): MSPluginsCollection; -} - -interface MSHTMLFontElementExtensions { -} - -interface SVGAnimatedNumberList { - animVal: SVGNumberList; - baseVal: SVGNumberList; -} -declare var SVGAnimatedNumberList: { - prototype: SVGAnimatedNumberList; - new(): SVGAnimatedNumberList; -} - -interface SVGSVGElement extends SVGElement, SVGZoomAndPan, SVGLangSpace, SVGLocatable, SVGTests, SVGFitToViewBox, SVGSVGElementEventHandlers, SVGStylable, DocumentEvent, ViewCSS_SVGSVGElement { - width: SVGAnimatedLength; - x: SVGAnimatedLength; - contentStyleType: string; - screenPixelToMillimeterY: number; - height: SVGAnimatedLength; - contentScriptType: string; - pixelUnitToMillimeterX: number; - currentTranslate: SVGPoint; - y: SVGAnimatedLength; - viewport: SVGRect; - currentScale: number; - screenPixelToMillimeterX: number; - pixelUnitToMillimeterY: number; - setCurrentTime(seconds: number): void; - createSVGLength(): SVGLength; - getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; - unpauseAnimations(): void; - createSVGRect(): SVGRect; - checkIntersection(element: SVGElement, rect: SVGRect): bool; - unsuspendRedrawAll(): void; - pauseAnimations(): void; - suspendRedraw(maxWaitMilliseconds: number): number; - deselectAll(): void; - createSVGAngle(): SVGAngle; - getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeList; - createSVGTransform(): SVGTransform; - unsuspendRedraw(suspendHandleID: number): void; - forceRedraw(): void; - getCurrentTime(): number; - checkEnclosure(element: SVGElement, rect: SVGRect): bool; - createSVGMatrix(): SVGMatrix; - createSVGPoint(): SVGPoint; - createSVGNumber(): SVGNumber; - createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; - getElementById(elementId: string): Element; -} -declare var SVGSVGElement: { - prototype: SVGSVGElement; - new(): SVGSVGElement; -} - -interface HTMLLabelElement extends HTMLElement, MSDataBindingExtensions, MSHTMLLabelElementExtensions { - htmlFor: string; - form: HTMLFormElement; -} -declare var HTMLLabelElement: { - prototype: HTMLLabelElement; - new(): HTMLLabelElement; -} - -interface MSResourceMetadata { - protocol: string; - fileSize: string; - fileUpdatedDate: string; - nameProp: string; - fileCreatedDate: string; - fileModifiedDate: string; - mimeType: string; -} - -interface MSHTMLQuoteElementExtensions { - dateTime: string; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLIFrameElement { - align: string; -} - -interface HTMLLegendElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLLegendElement, MSDataBindingExtensions, MSHTMLLegendElementExtensions { - form: HTMLFormElement; -} -declare var HTMLLegendElement: { - prototype: HTMLLegendElement; - new(): HTMLLegendElement; -} - -interface HTMLDirectoryElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLDirectoryElementExtensions { -} -declare var HTMLDirectoryElement: { - prototype: HTMLDirectoryElement; - new(): HTMLDirectoryElement; -} - -interface NavigatorAbilities { -} - -interface MSHTMLImageElementExtensions { - href: string; -} - -interface SVGAnimatedInteger { - animVal: number; - baseVal: number; -} -declare var SVGAnimatedInteger: { - prototype: SVGAnimatedInteger; - new(): SVGAnimatedInteger; -} - -interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { -} -declare var SVGTextElement: { - prototype: SVGTextElement; - new(): SVGTextElement; -} - -interface SVGTSpanElement extends SVGTextPositioningElement { -} -declare var SVGTSpanElement: { - prototype: SVGTSpanElement; - new(): SVGTSpanElement; -} - -interface HTMLLIElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, MSHTMLLIElementExtensions { - value: number; -} -declare var HTMLLIElement: { - prototype: HTMLLIElement; - new(): HTMLLIElement; -} - -interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { - y: number; -} -declare var SVGPathSegLinetoVerticalAbs: { - prototype: SVGPathSegLinetoVerticalAbs; - new(): SVGPathSegLinetoVerticalAbs; -} - -interface ViewCSS { - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -} - -interface MSAttrExtensions { - expando: bool; -} - -interface MSStorageExtensions { - remainingSpace: number; -} - -interface SVGStyleElement extends SVGElement, SVGLangSpace { - media: string; - type: string; - title: string; -} -declare var SVGStyleElement: { - prototype: SVGStyleElement; - new(): SVGStyleElement; -} - -interface MSCurrentStyleCSSProperties extends MSCSSProperties { - blockDirection: string; - clipBottom: string; - clipLeft: string; - clipRight: string; - clipTop: string; - hasLayout: string; -} -declare var MSCurrentStyleCSSProperties: { - prototype: MSCurrentStyleCSSProperties; - new(): MSCurrentStyleCSSProperties; -} - -interface MSLinkStyleExtensions { - styleSheet: StyleSheet; -} - -interface MSHTMLCollectionExtensions { - urns(urn: any): Object; - tags(tagName: any): Object; -} - -interface DOML2DeprecatedWordWrapSuppression_HTMLDivElement { - noWrap: bool; -} - -interface DocumentTraversal { - createNodeIterator(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): NodeIterator; - createTreeWalker(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): TreeWalker; -} - -interface Storage extends MSStorageExtensions { - length: number; - getItem(key: string): any; - [key: string]: any; - setItem(key: string, data: string): void; - clear(): void; - removeItem(key: string): void; - key(index: number): string; - [index: number]: any; -} -declare var Storage: { - prototype: Storage; - new(): Storage; -} - -interface HTMLTableHeaderCellScope { - scope: string; -} - -interface HTMLIFrameElement extends HTMLElement, GetSVGDocument, MSHTMLIFrameElementExtensions, MSDataBindingExtensions, DOML2DeprecatedAlignmentStyle_HTMLIFrameElement { - width: string; - contentWindow: Window; - scrolling: string; - src: string; - marginHeight: string; - name: string; - marginWidth: string; - height: string; - contentDocument: Document; - longDesc: string; - frameBorder: string; -} -declare var HTMLIFrameElement: { - prototype: HTMLIFrameElement; - new(): HTMLIFrameElement; -} - -interface MSNavigatorAbilities { - userLanguage: string; - plugins: MSPluginsCollection; - cookieEnabled: bool; - appCodeName: string; - cpuClass: string; - appMinorVersion: string; - connectionSpeed: number; - browserLanguage: string; - mimeTypes: MSMimeTypesCollection; - product: string; - systemLanguage: string; - javaEnabled(): bool; - taintEnabled(): bool; -} - -interface TextRangeCollection { - length: number; - item(index: number): TextRange; - [index: number]: TextRange; -} -declare var TextRangeCollection: { - prototype: TextRangeCollection; - new(): TextRangeCollection; -} - -interface HTMLBodyElement extends HTMLElement, HTMLBodyElementDOML2Deprecated, MSHTMLBodyElementExtensions, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { - onresize: (ev: UIEvent) => any; - ononline: (ev: Event) => any; - onafterprint: (ev: Event) => any; - onbeforeprint: (ev: Event) => any; - onoffline: (ev: Event) => any; - onblur: (ev: FocusEvent) => any; - onhashchange: (ev: Event) => any; - onunload: (ev: Event) => any; - onfocus: (ev: FocusEvent) => any; - onmessage: (ev: MessageEvent) => any; - onload: (ev: Event) => any; - onerror: (ev: Event) => any; - onbeforeunload: (ev: BeforeUnloadEvent) => any; - onstorage: (ev: StorageEvent) => any; -} -declare var HTMLBodyElement: { - prototype: HTMLBodyElement; - new(): HTMLBodyElement; -} - -interface DocumentType extends Node { - name: string; - notations: NamedNodeMap; - systemId: string; - internalSubset: string; - entities: NamedNodeMap; - publicId: string; -} -declare var DocumentType: { - prototype: DocumentType; - new(): DocumentType; -} - -interface MSHTMLInputElementExtensions extends DOML2DeprecatedMarginStyle_HTMLInputElement, DOML2DeprecatedBorderStyle_HTMLInputElement { - status: bool; - complete: bool; - createTextRange(): TextRange; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLLegendElement { - align: string; -} - -interface SVGRadialGradientElement extends SVGGradientElement { - cx: SVGAnimatedLength; - r: SVGAnimatedLength; - cy: SVGAnimatedLength; - fx: SVGAnimatedLength; - fy: SVGAnimatedLength; -} -declare var SVGRadialGradientElement: { - prototype: SVGRadialGradientElement; - new(): SVGRadialGradientElement; -} - -interface MutationEvent extends Event { - newValue: string; - attrChange: number; - attrName: string; - prevValue: string; - relatedNode: Node; - initMutationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; - MODIFICATION: number; - REMOVAL: number; - ADDITION: number; -} -declare var MutationEvent: { - prototype: MutationEvent; - new(): MutationEvent; - MODIFICATION: number; - REMOVAL: number; - ADDITION: number; -} - -interface DragEvent extends MouseEvent { - dataTransfer: DataTransfer; - initDragEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; -} -declare var DragEvent: { - prototype: DragEvent; - new(): DragEvent; -} - -interface DOML2DeprecatedWidthStyle_HTMLTableCellElement { - width: number; -} - -interface HTMLTableSectionElement extends HTMLElement, MSHTMLTableSectionElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableSectionElement, HTMLTableAlignment { - rows: HTMLCollection; - deleteRow(index?: number): void; - insertRow(index?: number): HTMLElement; -} -declare var HTMLTableSectionElement: { - prototype: HTMLTableSectionElement; - new(): HTMLTableSectionElement; -} - -interface DOML2DeprecatedListNumberingAndBulletStyle { - type: string; -} - -interface HTMLInputElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLInputElement, MSImageResourceExtensions_HTMLInputElement, MSHTMLInputElementExtensions, MSDataBindingExtensions { - width: string; - defaultChecked: bool; - alt: string; - accept: string; - value: string; - src: string; - useMap: string; - name: string; - form: HTMLFormElement; - selectionStart: number; - height: string; - indeterminate: bool; - readOnly: bool; - size: number; - checked: bool; - maxLength: number; - selectionEnd: number; - type: string; - defaultValue: string; - setSelectionRange(start: number, end: number): void; - select(): void; -} -declare var HTMLInputElement: { - prototype: HTMLInputElement; - new(): HTMLInputElement; -} - -interface HTMLAnchorElement extends HTMLElement, MSHTMLAnchorElementExtensions, MSDataBindingExtensions { - rel: string; - protocol: string; - search: string; - coords: string; - hostname: string; - pathname: string; - target: string; - href: string; - name: string; - charset: string; - hreflang: string; - port: string; - host: string; - hash: string; - rev: string; - type: string; - shape: string; - toString(): string; -} -declare var HTMLAnchorElement: { - prototype: HTMLAnchorElement; - new(): HTMLAnchorElement; -} - -interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { - y: SVGAnimatedLength; - width: SVGAnimatedLength; - preserveAspectRatio: SVGAnimatedPreserveAspectRatio; - x: SVGAnimatedLength; - height: SVGAnimatedLength; -} -declare var SVGImageElement: { - prototype: SVGImageElement; - new(): SVGImageElement; -} - -interface MSElementExtensions { - msMatchesSelector(selectors: string): bool; - fireEvent(eventName: string, eventObj?: any): bool; -} - -interface HTMLParamElement extends HTMLElement { - value: string; - name: string; - type: string; - valueType: string; -} -declare var HTMLParamElement: { - prototype: HTMLParamElement; - new(): HTMLParamElement; -} - -interface MSHTMLDocumentViewExtensions { - createStyleSheet(href?: string, index?: number): CSSStyleSheet; -} - -interface SVGAnimatedNumber { - animVal: number; - baseVal: number; -} -declare var SVGAnimatedNumber: { - prototype: SVGAnimatedNumber; - new(): SVGAnimatedNumber; -} - -interface PerformanceTiming { - redirectStart: number; - domainLookupEnd: number; - responseStart: number; - domComplete: number; - domainLookupStart: number; - loadEventStart: number; - msFirstPaint: number; - unloadEventEnd: number; - fetchStart: number; - requestStart: number; - domInteractive: number; - navigationStart: number; - connectEnd: number; - loadEventEnd: number; - connectStart: number; - responseEnd: number; - domLoading: number; - redirectEnd: number; - unloadEventStart: number; - domContentLoadedEventStart: number; - domContentLoadedEventEnd: number; - toJSON(): any; -} -declare var PerformanceTiming: { - prototype: PerformanceTiming; - new(): PerformanceTiming; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLInputElement { - align: string; -} - -interface HTMLPreElement extends HTMLElement, DOML2DeprecatedWidthStyle, MSHTMLPreElementExtensions { -} -declare var HTMLPreElement: { - prototype: HTMLPreElement; - new(): HTMLPreElement; -} - -interface EventException { - code: number; - message: string; - toString(): string; - DISPATCH_REQUEST_ERR: number; - UNSPECIFIED_EVENT_TYPE_ERR: number; -} -declare var EventException: { - prototype: EventException; - new(): EventException; - DISPATCH_REQUEST_ERR: number; - UNSPECIFIED_EVENT_TYPE_ERR: number; -} - -interface MSBorderColorHighlightStyle_HTMLTableCellElement { - borderColorLight: any; - borderColorDark: any; -} - -interface DOMHTMLImplementation { - createHTMLDocument(title: string): Document; -} - -interface NavigatorOnLine { - onLine: bool; -} - -interface SVGElementEventHandlers { - onmouseover: (ev: MouseEvent) => any; - onmousemove: (ev: MouseEvent) => any; - onmouseout: (ev: MouseEvent) => any; - ondblclick: (ev: MouseEvent) => any; - onfocusout: (ev: FocusEvent) => any; - onfocusin: (ev: FocusEvent) => any; - onmousedown: (ev: MouseEvent) => any; - onmouseup: (ev: MouseEvent) => any; - onload: (ev: Event) => any; - onclick: (ev: MouseEvent) => any; -} - -interface WindowLocalStorage { - localStorage: Storage; -} - -interface SVGMetadataElement extends SVGElement { -} -declare var SVGMetadataElement: { - prototype: SVGMetadataElement; - new(): SVGMetadataElement; -} - -interface SVGPathSegArcRel extends SVGPathSeg { - y: number; - sweepFlag: bool; - r2: number; - x: number; - angle: number; - r1: number; - largeArcFlag: bool; -} -declare var SVGPathSegArcRel: { - prototype: SVGPathSegArcRel; - new(): SVGPathSegArcRel; -} - -interface SVGPathSegMovetoAbs extends SVGPathSeg { - y: number; - x: number; -} -declare var SVGPathSegMovetoAbs: { - prototype: SVGPathSegMovetoAbs; - new(): SVGPathSegMovetoAbs; -} - -interface SVGStringList { - numberOfItems: number; - replaceItem(newItem: string, index: number): string; - getItem(index: number): string; - clear(): void; - appendItem(newItem: string): string; - initialize(newItem: string): string; - removeItem(index: number): string; - insertItemBefore(newItem: string, index: number): string; -} -declare var SVGStringList: { - prototype: SVGStringList; - new(): SVGStringList; -} - -interface XDomainRequest { - timeout: number; - onerror: (ev: Event) => any; - onload: (ev: Event) => any; - onprogress: (ev: any) => any; - ontimeout: (ev: Event) => any; - responseText: string; - contentType: string; - open(method: string, url: string): void; - abort(): void; - send(data?: any): void; -} -declare var XDomainRequest: { - prototype: XDomainRequest; - new (): XDomainRequest; -} - -interface DOML2DeprecatedBackgroundColorStyle { - bgColor: any; -} - -interface ElementTraversal { - childElementCount: number; - previousElementSibling: Element; - lastElementChild: Element; - nextElementSibling: Element; - firstElementChild: Element; -} - -interface SVGLength { - valueAsString: string; - valueInSpecifiedUnits: number; - value: number; - unitType: number; - newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; - convertToSpecifiedUnits(unitType: number): void; - SVG_LENGTHTYPE_NUMBER: number; - SVG_LENGTHTYPE_CM: number; - SVG_LENGTHTYPE_PC: number; - SVG_LENGTHTYPE_PERCENTAGE: number; - SVG_LENGTHTYPE_MM: number; - SVG_LENGTHTYPE_PT: number; - SVG_LENGTHTYPE_IN: number; - SVG_LENGTHTYPE_EMS: number; - SVG_LENGTHTYPE_PX: number; - SVG_LENGTHTYPE_UNKNOWN: number; - SVG_LENGTHTYPE_EXS: number; -} -declare var SVGLength: { - prototype: SVGLength; - new(): SVGLength; - SVG_LENGTHTYPE_NUMBER: number; - SVG_LENGTHTYPE_CM: number; - SVG_LENGTHTYPE_PC: number; - SVG_LENGTHTYPE_PERCENTAGE: number; - SVG_LENGTHTYPE_MM: number; - SVG_LENGTHTYPE_PT: number; - SVG_LENGTHTYPE_IN: number; - SVG_LENGTHTYPE_EMS: number; - SVG_LENGTHTYPE_PX: number; - SVG_LENGTHTYPE_UNKNOWN: number; - SVG_LENGTHTYPE_EXS: number; -} - -interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests { -} -declare var SVGPolygonElement: { - prototype: SVGPolygonElement; - new(): SVGPolygonElement; -} - -interface HTMLPhraseElement extends HTMLElement { - dateTime: string; - cite: string; -} -declare var HTMLPhraseElement: { - prototype: HTMLPhraseElement; - new(): HTMLPhraseElement; -} - -interface MSHTMLAreaElementExtensions { -} - -interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { - y: number; - y1: number; - x2: number; - x: number; - x1: number; - y2: number; -} -declare var SVGPathSegCurvetoCubicRel: { - prototype: SVGPathSegCurvetoCubicRel; - new(): SVGPathSegCurvetoCubicRel; -} - -interface MSEventObj { - nextPage: string; - keyCode: number; - toElement: Element; - returnValue: any; - dataFld: string; - y: number; - dataTransfer: DataTransfer; - propertyName: string; - url: string; - offsetX: number; - recordset: Object; - screenX: number; - buttonID: number; - wheelDelta: number; - reason: number; - origin: string; - data: string; - srcFilter: Object; - boundElements: HTMLCollection; - cancelBubble: bool; - altLeft: bool; - behaviorCookie: number; - bookmarks: BookmarkCollection; - type: string; - repeat: bool; - srcElement: Element; - source: Window; - fromElement: Element; - offsetY: number; - x: number; - behaviorPart: number; - qualifier: string; - altKey: bool; - ctrlKey: bool; - clientY: number; - shiftKey: bool; - shiftLeft: bool; - contentOverflow: bool; - screenY: number; - ctrlLeft: bool; - button: number; - srcUrn: string; - clientX: number; - actionURL: string; - getAttribute(strAttributeName: string, lFlags?: number): any; - setAttribute(strAttributeName: string, AttributeValue: any, lFlags?: number): void; - removeAttribute(strAttributeName: string, lFlags?: number): bool; -} -declare var MSEventObj: { - prototype: MSEventObj; - new(): MSEventObj; -} - -interface SVGTextContentElement extends SVGElement, SVGStylable, SVGLangSpace, SVGTests { - textLength: SVGAnimatedLength; - lengthAdjust: SVGAnimatedEnumeration; - getCharNumAtPosition(point: SVGPoint): number; - getStartPositionOfChar(charnum: number): SVGPoint; - getExtentOfChar(charnum: number): SVGRect; - getComputedTextLength(): number; - getSubStringLength(charnum: number, nchars: number): number; - selectSubString(charnum: number, nchars: number): void; - getNumberOfChars(): number; - getRotationOfChar(charnum: number): number; - getEndPositionOfChar(charnum: number): SVGPoint; - LENGTHADJUST_SPACING: number; - LENGTHADJUST_SPACINGANDGLYPHS: number; - LENGTHADJUST_UNKNOWN: number; -} -declare var SVGTextContentElement: { - prototype: SVGTextContentElement; - new(): SVGTextContentElement; - LENGTHADJUST_SPACING: number; - LENGTHADJUST_SPACINGANDGLYPHS: number; - LENGTHADJUST_UNKNOWN: number; -} - -interface DOML2DeprecatedColorProperty { - color: string; -} - -interface MSHTMLLIElementExtensions { -} - -interface HTMLCanvasElement extends HTMLElement { - width: number; - height: number; - toDataURL(): string; - toDataURL(type: string, ...args: any[]): string; - getContext(contextId: string): CanvasRenderingContext2D; -} -declare var HTMLCanvasElement: { - prototype: HTMLCanvasElement; - new(): HTMLCanvasElement; -} - -interface HTMLTitleElement extends HTMLElement { - text: string; -} -declare var HTMLTitleElement: { - prototype: HTMLTitleElement; - new(): HTMLTitleElement; -} - -interface Location { - hash: string; - protocol: string; - search: string; - href: string; - hostname: string; - port: string; - pathname: string; - host: string; - reload(flag?: bool): void; - replace(url: string): void; - assign(url: string): void; - toString(): string; -} -declare var Location: { - prototype: Location; - new(): Location; -} - -interface HTMLStyleElement extends HTMLElement, MSLinkStyleExtensions, LinkStyle { - media: string; - type: string; -} -declare var HTMLStyleElement: { - prototype: HTMLStyleElement; - new(): HTMLStyleElement; -} - -interface MSHTMLOptGroupElementExtensions { - index: number; - defaultSelected: bool; - text: string; - value: string; - form: HTMLFormElement; - selected: bool; -} - -interface MSBorderColorHighlightStyle { - borderColorLight: any; - borderColorDark: any; -} - -interface DOML2DeprecatedSizeProperty_HTMLBaseFontElement { - size: number; -} - -interface SVGTransform { - type: number; - angle: number; - matrix: SVGMatrix; - setTranslate(tx: number, ty: number): void; - setScale(sx: number, sy: number): void; - setMatrix(matrix: SVGMatrix): void; - setSkewY(angle: number): void; - setRotate(angle: number, cx: number, cy: number): void; - setSkewX(angle: number): void; - SVG_TRANSFORM_SKEWX: number; - SVG_TRANSFORM_UNKNOWN: number; - SVG_TRANSFORM_SCALE: number; - SVG_TRANSFORM_TRANSLATE: number; - SVG_TRANSFORM_MATRIX: number; - SVG_TRANSFORM_ROTATE: number; - SVG_TRANSFORM_SKEWY: number; -} -declare var SVGTransform: { - prototype: SVGTransform; - new(): SVGTransform; - SVG_TRANSFORM_SKEWX: number; - SVG_TRANSFORM_UNKNOWN: number; - SVG_TRANSFORM_SCALE: number; - SVG_TRANSFORM_TRANSLATE: number; - SVG_TRANSFORM_MATRIX: number; - SVG_TRANSFORM_ROTATE: number; - SVG_TRANSFORM_SKEWY: number; -} - -interface MSCSSFilter { - Percent: number; - Enabled: bool; - Duration: number; - Play(Duration: number): void; - Apply(): void; - Stop(): void; -} -declare var MSCSSFilter: { - prototype: MSCSSFilter; - new(): MSCSSFilter; -} - -interface UIEvent extends Event { - detail: number; - view: AbstractView; - initUIEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number): void; -} -declare var UIEvent: { - prototype: UIEvent; - new(): UIEvent; -} - -interface ViewCSS_SVGSVGElement { - getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -} - -interface SVGURIReference { - href: SVGAnimatedString; -} - -interface SVGPathSeg { - pathSegType: number; - pathSegTypeAsLetter: string; - PATHSEG_MOVETO_REL: number; - PATHSEG_LINETO_VERTICAL_REL: number; - PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - PATHSEG_CURVETO_QUADRATIC_REL: number; - PATHSEG_CURVETO_CUBIC_ABS: number; - PATHSEG_LINETO_HORIZONTAL_ABS: number; - PATHSEG_CURVETO_QUADRATIC_ABS: number; - PATHSEG_LINETO_ABS: number; - PATHSEG_CLOSEPATH: number; - PATHSEG_LINETO_HORIZONTAL_REL: number; - PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - PATHSEG_LINETO_REL: number; - PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - PATHSEG_ARC_REL: number; - PATHSEG_CURVETO_CUBIC_REL: number; - PATHSEG_UNKNOWN: number; - PATHSEG_LINETO_VERTICAL_ABS: number; - PATHSEG_ARC_ABS: number; - PATHSEG_MOVETO_ABS: number; - PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; -} -declare var SVGPathSeg: { - PATHSEG_MOVETO_REL: number; - PATHSEG_LINETO_VERTICAL_REL: number; - PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; - PATHSEG_CURVETO_QUADRATIC_REL: number; - PATHSEG_CURVETO_CUBIC_ABS: number; - PATHSEG_LINETO_HORIZONTAL_ABS: number; - PATHSEG_CURVETO_QUADRATIC_ABS: number; - PATHSEG_LINETO_ABS: number; - PATHSEG_CLOSEPATH: number; - PATHSEG_LINETO_HORIZONTAL_REL: number; - PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; - PATHSEG_LINETO_REL: number; - PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; - PATHSEG_ARC_REL: number; - PATHSEG_CURVETO_CUBIC_REL: number; - PATHSEG_UNKNOWN: number; - PATHSEG_LINETO_VERTICAL_ABS: number; - PATHSEG_ARC_ABS: number; - PATHSEG_MOVETO_ABS: number; - PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; -} - -interface WheelEvent extends MouseEvent { - deltaZ: number; - deltaX: number; - deltaMode: number; - deltaY: number; - initWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; - DOM_DELTA_PIXEL: number; - DOM_DELTA_LINE: number; - DOM_DELTA_PAGE: number; -} -declare var WheelEvent: { - prototype: WheelEvent; - new(): WheelEvent; - DOM_DELTA_PIXEL: number; - DOM_DELTA_LINE: number; - DOM_DELTA_PAGE: number; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLDivElement { - align: string; -} - -interface MSEventAttachmentTarget { - attachEvent(event: string, listener: EventListener): bool; - detachEvent(event: string, listener: EventListener): void; -} - -interface SVGNumber { - value: number; -} -declare var SVGNumber: { - prototype: SVGNumber; - new(): SVGNumber; -} - -interface SVGPathElement extends SVGElement, SVGStylable, SVGAnimatedPathData, SVGTransformable, SVGLangSpace, SVGTests { - getPathSegAtLength(distance: number): number; - getPointAtLength(distance: number): SVGPoint; - createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; - createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; - createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; - createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; - createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; - createSVGPathSegClosePath(): SVGPathSegClosePath; - createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; - createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; - createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; - createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; - createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; - createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcRel; - createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; - createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; - getTotalLength(): number; - createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; - createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; - createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcAbs; -} -declare var SVGPathElement: { - prototype: SVGPathElement; - new(): SVGPathElement; -} - -interface MSCompatibleInfo { - version: string; - userAgent: string; -} -declare var MSCompatibleInfo: { - prototype: MSCompatibleInfo; - new(): MSCompatibleInfo; -} - -interface MSHTMLDocumentEventExtensions { - createEventObject(eventObj?: any): MSEventObj; - fireEvent(eventName: string, eventObj?: any): bool; -} - -interface Text extends CharacterData, MSNodeExtensions { - wholeText: string; - splitText(offset: number): Text; - replaceWholeText(content: string): Text; -} -declare var Text: { - prototype: Text; - new(): Text; -} - -interface SVGAnimatedRect { - animVal: SVGRect; - baseVal: SVGRect; -} -declare var SVGAnimatedRect: { - prototype: SVGAnimatedRect; - new(): SVGAnimatedRect; -} - -interface CSSNamespaceRule extends CSSRule { - namespaceURI: string; - prefix: string; -} -declare var CSSNamespaceRule: { - prototype: CSSNamespaceRule; - new(): CSSNamespaceRule; -} - -interface HTMLUnknownElement extends HTMLElement, MSDataBindingRecordSetReadonlyExtensions, MSHTMLUnknownElementExtensions { -} -declare var HTMLUnknownElement: { - prototype: HTMLUnknownElement; - new(): HTMLUnknownElement; -} - -interface SVGPathSegList { - numberOfItems: number; - replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; - getItem(index: number): SVGPathSeg; - clear(): void; - appendItem(newItem: SVGPathSeg): SVGPathSeg; - initialize(newItem: SVGPathSeg): SVGPathSeg; - removeItem(index: number): SVGPathSeg; - insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; -} -declare var SVGPathSegList: { - prototype: SVGPathSegList; - new(): SVGPathSegList; -} - -interface HTMLAudioElement extends HTMLMediaElement { -} -declare var HTMLAudioElement: { - prototype: HTMLAudioElement; - new(): HTMLAudioElement; -} - -interface MSImageResourceExtensions { - dynsrc: string; - vrml: string; - lowsrc: string; - start: string; - loop: number; -} - -interface MSBorderColorHighlightStyle_HTMLTableRowElement { - borderColorLight: any; - borderColorDark: any; -} - -interface PositionError { - code: number; - message: string; - toString(): string; - POSITION_UNAVAILABLE: number; - PERMISSION_DENIED: number; - TIMEOUT: number; -} -declare var PositionError: { - POSITION_UNAVAILABLE: number; - PERMISSION_DENIED: number; - TIMEOUT: number; -} - -interface BrowserPublic { -} -declare var BrowserPublic: { - prototype: BrowserPublic; - new(): BrowserPublic; -} - -interface HTMLTableCellElement extends HTMLElement, DOML2DeprecatedTableCellHeight, HTMLTableAlignment, MSBorderColorHighlightStyle_HTMLTableCellElement, DOML2DeprecatedWidthStyle_HTMLTableCellElement, DOML2DeprecatedBackgroundStyle, MSBorderColorStyle_HTMLTableCellElement, MSHTMLTableCellElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableCellElement, HTMLTableHeaderCellScope, DOML2DeprecatedWordWrapSuppression, DOML2DeprecatedBackgroundColorStyle { - headers: string; - abbr: string; - rowSpan: number; - cellIndex: number; - colSpan: number; - axis: string; -} -declare var HTMLTableCellElement: { - prototype: HTMLTableCellElement; - new(): HTMLTableCellElement; -} - -interface MSNamespaceInfoCollection { - length: number; - add(namespace?: string, urn?: string, implementationUrl?: any): Object; - item(index: any): Object; - [index: string]: Object; - (index: any): Object; -} -declare var MSNamespaceInfoCollection: { - prototype: MSNamespaceInfoCollection; - new(): MSNamespaceInfoCollection; -} - -interface SVGElementInstance extends EventTarget { - previousSibling: SVGElementInstance; - parentNode: SVGElementInstance; - lastChild: SVGElementInstance; - nextSibling: SVGElementInstance; - childNodes: SVGElementInstanceList; - correspondingUseElement: SVGUseElement; - correspondingElement: SVGElement; - firstChild: SVGElementInstance; -} -declare var SVGElementInstance: { - prototype: SVGElementInstance; - new(): SVGElementInstance; -} - -interface MSHTMLUListElementExtensions { -} - -interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { - cx: SVGAnimatedLength; - r: SVGAnimatedLength; - cy: SVGAnimatedLength; -} -declare var SVGCircleElement: { - prototype: SVGCircleElement; - new(): SVGCircleElement; -} - -interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedSizeProperty_HTMLBaseFontElement, DOML2DeprecatedColorProperty { - face: string; -} -declare var HTMLBaseFontElement: { - prototype: HTMLBaseFontElement; - new(): HTMLBaseFontElement; -} - -interface CustomEvent extends Event { - detail: Object; - initCustomEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, detailArg: Object): void; -} -declare var CustomEvent: { - prototype: CustomEvent; - new(): CustomEvent; -} - -interface CSSImportRule extends CSSRule { - styleSheet: CSSStyleSheet; - href: string; - media: MediaList; -} -declare var CSSImportRule: { - prototype: CSSImportRule; - new(): CSSImportRule; -} - -interface StyleSheetList { - length: number; - item(index?: number): StyleSheet; - [index: number]: StyleSheet; -} -declare var StyleSheetList: { - prototype: StyleSheetList; - new(): StyleSheetList; -} - -interface HTMLTextAreaElement extends HTMLElement, MSDataBindingExtensions, MSHTMLTextAreaElementExtensions { - value: string; - form: HTMLFormElement; - name: string; - selectionStart: number; - rows: number; - cols: number; - readOnly: bool; - wrap: string; - selectionEnd: number; - type: string; - defaultValue: string; - setSelectionRange(start: number, end: number): void; - select(): void; -} -declare var HTMLTextAreaElement: { - prototype: HTMLTextAreaElement; - new(): HTMLTextAreaElement; -} - -interface MSHTMLFormElementExtensions { - encoding: string; -} - -interface DOML2DeprecatedMarginStyle { - vspace: number; - hspace: number; -} - -interface Geolocation { - clearWatch(watchId: number): void; - getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; - watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; -} -declare var Geolocation: { - prototype: Geolocation; - new(): Geolocation; -} - -interface MSWindowModeless { - dialogTop: any; - dialogLeft: any; - dialogWidth: any; - dialogHeight: any; - menuArguments: any; -} - -interface HTMLMarqueeElement extends HTMLElement, DOML2DeprecatedMarginStyle_HTMLMarqueeElement, MSDataBindingExtensions, MSHTMLMarqueeElementExtensions, DOML2DeprecatedBackgroundColorStyle { - width: string; - onbounce: (ev: Event) => any; - trueSpeed: bool; - scrollAmount: number; - scrollDelay: number; - behavior: string; - height: string; - loop: number; - direction: string; - onstart: (ev: Event) => any; - onfinish: (ev: Event) => any; - stop(): void; - start(): void; -} -declare var HTMLMarqueeElement: { - prototype: HTMLMarqueeElement; - new(): HTMLMarqueeElement; -} - -interface SVGRect { - y: number; - width: number; - x: number; - height: number; -} -declare var SVGRect: { - prototype: SVGRect; - new(): SVGRect; -} - -interface MSNodeExtensions { - swapNode(otherNode: Node): Node; - removeNode(deep?: bool): Node; - replaceNode(replacement: Node): Node; -} - -interface KeyboardEventExtensions { - keyCode: number; - which: number; - charCode: number; -} - -interface History { - length: number; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; -} -declare var History: { - prototype: History; - new(): History; -} - -interface DocumentStyle { - styleSheets: StyleSheetList; -} - -interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { - y: number; - y1: number; - x2: number; - x: number; - x1: number; - y2: number; -} -declare var SVGPathSegCurvetoCubicAbs: { - prototype: SVGPathSegCurvetoCubicAbs; - new(): SVGPathSegCurvetoCubicAbs; -} - -interface TimeRanges { - length: number; - start(index: number): number; - end(index: number): number; -} -declare var TimeRanges: { - prototype: TimeRanges; - new(): TimeRanges; -} - -interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { - y: number; - y1: number; - x: number; - x1: number; -} -declare var SVGPathSegCurvetoQuadraticAbs: { - prototype: SVGPathSegCurvetoQuadraticAbs; - new(): SVGPathSegCurvetoQuadraticAbs; -} - -interface MSHTMLSelectElementExtensions { -} - -interface CSSRule { - cssText: string; - parentStyleSheet: CSSStyleSheet; - parentRule: CSSRule; - type: number; - IMPORT_RULE: number; - MEDIA_RULE: number; - STYLE_RULE: number; - NAMESPACE_RULE: number; - PAGE_RULE: number; - UNKNOWN_RULE: number; - FONT_FACE_RULE: number; - CHARSET_RULE: number; -} -declare var CSSRule: { - prototype: CSSRule; - new(): CSSRule; - IMPORT_RULE: number; - MEDIA_RULE: number; - STYLE_RULE: number; - NAMESPACE_RULE: number; - PAGE_RULE: number; - UNKNOWN_RULE: number; - FONT_FACE_RULE: number; - CHARSET_RULE: number; -} - -interface SVGPathSegLinetoAbs extends SVGPathSeg { - y: number; - x: number; -} -declare var SVGPathSegLinetoAbs: { - prototype: SVGPathSegLinetoAbs; - new(): SVGPathSegLinetoAbs; -} - -interface MSMouseEventExtensions { - toElement: Element; - layerY: number; - fromElement: Element; - which: number; - layerX: number; -} - -interface HTMLModElement extends HTMLElement, MSHTMLModElementExtensions { - dateTime: string; - cite: string; -} -declare var HTMLModElement: { - prototype: HTMLModElement; - new(): HTMLModElement; -} - -interface DOML2DeprecatedWordWrapSuppression { - noWrap: bool; -} - -interface BeforeUnloadEvent extends Event { - returnValue: string; -} -declare var BeforeUnloadEvent: { - prototype: BeforeUnloadEvent; - new(): BeforeUnloadEvent; -} - -interface MSPopupWindow { - document: HTMLDocument; - isOpen: bool; - show(x: number, y: number, w: number, h: number, element?: any): void; - hide(): void; -} -declare var MSPopupWindow: { - prototype: MSPopupWindow; - new(): MSPopupWindow; -} - -interface SVGMatrix { - e: number; - c: number; - a: number; - b: number; - d: number; - f: number; - multiply(secondMatrix: SVGMatrix): SVGMatrix; - flipY(): SVGMatrix; - skewY(angle: number): SVGMatrix; - inverse(): SVGMatrix; - scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; - rotate(angle: number): SVGMatrix; - flipX(): SVGMatrix; - translate(x: number, y: number): SVGMatrix; - scale(scaleFactor: number): SVGMatrix; - rotateFromVector(x: number, y: number): SVGMatrix; - skewX(angle: number): SVGMatrix; -} -declare var SVGMatrix: { - prototype: SVGMatrix; - new(): SVGMatrix; -} - -interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { - y: SVGAnimatedLength; - width: SVGAnimatedLength; - animatedInstanceRoot: SVGElementInstance; - instanceRoot: SVGElementInstance; - x: SVGAnimatedLength; - height: SVGAnimatedLength; -} -declare var SVGUseElement: { - prototype: SVGUseElement; - new(): SVGUseElement; -} - -interface Event extends MSEventExtensions { - timeStamp: number; - defaultPrevented: bool; - isTrusted: bool; - currentTarget: EventTarget; - target: EventTarget; - eventPhase: number; - type: string; - cancelable: bool; - bubbles: bool; - initEvent(eventTypeArg: string, canBubbleArg: bool, cancelableArg: bool): void; - stopPropagation(): void; - stopImmediatePropagation(): void; - preventDefault(): void; - CAPTURING_PHASE: number; - AT_TARGET: number; - BUBBLING_PHASE: number; -} -declare var Event: { - prototype: Event; - new(): Event; - CAPTURING_PHASE: number; - AT_TARGET: number; - BUBBLING_PHASE: number; -} - -interface ImageData { - width: number; - data: number[]; - height: number; -} -declare var ImageData: { - prototype: ImageData; - new(): ImageData; -} - -interface MSHTMLElementExtensions { - onlosecapture: (ev: MSEventObj) => any; - onrowexit: (ev: MSEventObj) => any; - oncontrolselect: (ev: MSEventObj) => any; - onrowsinserted: (ev: MSEventObj) => any; - onmouseleave: (ev: MouseEvent) => any; - document: HTMLDocument; - behaviorUrns: MSBehaviorUrnsCollection; - onpropertychange: (ev: MSEventObj) => any; - children: HTMLCollection; - filters: Object; - onbeforecut: (ev: DragEvent) => any; - scopeName: string; - onbeforepaste: (ev: DragEvent) => any; - onmove: (ev: MSEventObj) => any; - onafterupdate: (ev: MSEventObj) => any; - onbeforecopy: (ev: DragEvent) => any; - onlayoutcomplete: (ev: MSEventObj) => any; - onresizeend: (ev: MSEventObj) => any; - uniqueID: string; - onhelp: (ev: Event) => any; - onbeforeactivate: (ev: UIEvent) => any; - isMultiLine: bool; - uniqueNumber: number; - tagUrn: string; - onfocusout: (ev: FocusEvent) => any; - ondataavailable: (ev: MSEventObj) => any; - hideFocus: bool; - onbeforeupdate: (ev: MSEventObj) => any; - onfilterchange: (ev: MSEventObj) => any; - onfocusin: (ev: FocusEvent) => any; - recordNumber: any; - parentTextEdit: Element; - ondatasetcomplete: (ev: MSEventObj) => any; - onbeforedeactivate: (ev: UIEvent) => any; - outerText: string; - onresizestart: (ev: MSEventObj) => any; - onactivate: (ev: UIEvent) => any; - isTextEdit: bool; - isDisabled: bool; - readyState: string; - all: HTMLCollection; - onmouseenter: (ev: MouseEvent) => any; - onmovestart: (ev: MSEventObj) => any; - onselectstart: (ev: Event) => any; - onpaste: (ev: DragEvent) => any; - canHaveHTML: bool; - innerText: string; - onerrorupdate: (ev: MSEventObj) => any; - ondeactivate: (ev: UIEvent) => any; - oncut: (ev: DragEvent) => any; - onmoveend: (ev: MSEventObj) => any; - onresize: (ev: UIEvent) => any; - language: string; - ondatasetchanged: (ev: MSEventObj) => any; - oncopy: (ev: DragEvent) => any; - onrowsdelete: (ev: MSEventObj) => any; - parentElement: HTMLElement; - onrowenter: (ev: MSEventObj) => any; - onbeforeeditfocus: (ev: MSEventObj) => any; - canHaveChildren: bool; - sourceIndex: number; - oncellchange: (ev: MSEventObj) => any; - dragDrop(): bool; - releaseCapture(): void; - addFilter(filter: Object): void; - setCapture(containerCapture?: bool): void; - removeBehavior(cookie: number): bool; - contains(child: HTMLElement): bool; - applyElement(apply: Element, where?: string): Element; - replaceAdjacentText(where: string, newText: string): string; - mergeAttributes(source: HTMLElement, preserveIdentity?: bool): void; - insertAdjacentElement(position: string, insertedElement: Element): Element; - insertAdjacentText(where: string, text: string): void; - getAdjacentText(where: string): string; - removeFilter(filter: Object): void; - setActive(): void; - addBehavior(bstrUrl: string, factory?: any): number; - clearAttributes(): void; -} - -interface HTMLTableColElement extends HTMLElement, MSHTMLTableColElementExtensions, HTMLTableAlignment, DOML2DeprecatedAlignmentStyle_HTMLTableColElement { - width: any; - span: number; -} -declare var HTMLTableColElement: { - prototype: HTMLTableColElement; - new(): HTMLTableColElement; -} - -interface HTMLDocument extends MSEventAttachmentTarget, MSHTMLDocumentSelection, MSHTMLDocumentExtensions, MSNodeExtensions, MSResourceMetadata, MSHTMLDocumentEventExtensions, MSHTMLDocumentViewExtensions { - ondragend: (ev: DragEvent) => any; - ondragover: (ev: DragEvent) => any; - onkeydown: (ev: KeyboardEvent) => any; - bgColor: string; - onkeyup: (ev: KeyboardEvent) => any; - onreset: (ev: Event) => any; - onmouseup: (ev: MouseEvent) => any; - ondragstart: (ev: DragEvent) => any; - scripts: HTMLCollection; - ondrag: (ev: DragEvent) => any; - linkColor: string; - ondragleave: (ev: DragEvent) => any; - onmouseover: (ev: MouseEvent) => any; - onpause: (ev: Event) => any; - charset: string; - vlinkColor: string; - onmousedown: (ev: MouseEvent) => any; - onseeked: (ev: Event) => any; - title: string; - onclick: (ev: MouseEvent) => any; - onwaiting: (ev: Event) => any; - defaultCharset: string; - embeds: HTMLCollection; - ondurationchange: (ev: Event) => any; - all: HTMLCollection; - applets: HTMLCollection; - forms: HTMLCollection; - onblur: (ev: FocusEvent) => any; - dir: string; - body: HTMLElement; - designMode: string; - onemptied: (ev: Event) => any; - domain: string; - onseeking: (ev: Event) => any; - oncanplay: (ev: Event) => any; - onstalled: (ev: Event) => any; - onmousemove: (ev: MouseEvent) => any; - onratechange: (ev: Event) => any; - onloadstart: (ev: Event) => any; - ondragenter: (ev: DragEvent) => any; - onsubmit: (ev: Event) => any; - onprogress: (ev: any) => any; - ondblclick: (ev: MouseEvent) => any; - oncontextmenu: (ev: MouseEvent) => any; - activeElement: Element; - onchange: (ev: Event) => any; - onloadedmetadata: (ev: Event) => any; - onerror: (ev: Event) => any; - onplay: (ev: Event) => any; - links: HTMLCollection; - onplaying: (ev: Event) => any; - URL: string; - images: HTMLCollection; - head: HTMLHeadElement; - location: Location; - cookie: string; - oncanplaythrough: (ev: Event) => any; - onabort: (ev: UIEvent) => any; - characterSet: string; - anchors: HTMLCollection; - lastModified: string; - onreadystatechange: (ev: Event) => any; - onkeypress: (ev: KeyboardEvent) => any; - onloadeddata: (ev: Event) => any; - plugins: HTMLCollection; - onsuspend: (ev: Event) => any; - referrer: string; - readyState: string; - alinkColor: string; - onfocus: (ev: FocusEvent) => any; - fgColor: string; - ontimeupdate: (ev: Event) => any; - onselect: (ev: UIEvent) => any; - ondrop: (ev: DragEvent) => any; - onmouseout: (ev: MouseEvent) => any; - onended: (ev: Event) => any; - compatMode: string; - onscroll: (ev: UIEvent) => any; - onmousewheel: (ev: MouseWheelEvent) => any; - onload: (ev: Event) => any; - onvolumechange: (ev: Event) => any; - oninput: (ev: Event) => any; - queryCommandValue(commandId: string): string; - queryCommandIndeterm(commandId: string): bool; - execCommand(commandId: string, showUI?: bool, value?: any): bool; - getElementsByName(elementName: string): NodeList; - writeln(...content: string[]): void; - open(url?: string, name?: string, features?: string, replace?: bool): any; - queryCommandState(commandId: string): bool; - close(): void; - hasFocus(): bool; - getElementsByClassName(classNames: string): NodeList; - queryCommandSupported(commandId: string): bool; - getSelection(): Selection; - queryCommandEnabled(commandId: string): bool; - write(...content: string[]): void; - queryCommandText(commandId: string): string; -} - -interface SVGException { - code: number; - message: string; - toString(): string; - SVG_MATRIX_NOT_INVERTABLE: number; - SVG_WRONG_TYPE_ERR: number; - SVG_INVALID_VALUE_ERR: number; -} -declare var SVGException: { - prototype: SVGException; - new(): SVGException; - SVG_MATRIX_NOT_INVERTABLE: number; - SVG_WRONG_TYPE_ERR: number; - SVG_INVALID_VALUE_ERR: number; -} - -interface DOML2DeprecatedTableCellHeight { - height: any; -} - -interface HTMLTableAlignment { - ch: string; - vAlign: string; - chOff: string; -} - -interface SVGAnimatedEnumeration { - animVal: number; - baseVal: number; -} -declare var SVGAnimatedEnumeration: { - prototype: SVGAnimatedEnumeration; - new(): SVGAnimatedEnumeration; -} - -interface SVGLinearGradientElement extends SVGGradientElement { - y1: SVGAnimatedLength; - x2: SVGAnimatedLength; - x1: SVGAnimatedLength; - y2: SVGAnimatedLength; -} -declare var SVGLinearGradientElement: { - prototype: SVGLinearGradientElement; - new(): SVGLinearGradientElement; -} - -interface DOML2DeprecatedSizeProperty { - size: number; -} - -interface MSHTMLHeadingElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { -} - -interface MSBorderColorStyle_HTMLTableCellElement { - borderColor: any; -} - -interface DOML2DeprecatedWidthStyle_HTMLHRElement { - width: number; -} - -interface HTMLUListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle, MSHTMLUListElementExtensions { -} -declare var HTMLUListElement: { - prototype: HTMLUListElement; - new(): HTMLUListElement; -} - -interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { - y: SVGAnimatedLength; - width: SVGAnimatedLength; - ry: SVGAnimatedLength; - rx: SVGAnimatedLength; - x: SVGAnimatedLength; - height: SVGAnimatedLength; -} -declare var SVGRectElement: { - prototype: SVGRectElement; - new(): SVGRectElement; -} - -interface DOML2DeprecatedBorderStyle { - border: string; -} - -interface HTMLDivElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLDivElement, MSHTMLDivElementExtensions, MSDataBindingExtensions { -} -declare var HTMLDivElement: { - prototype: HTMLDivElement; - new(): HTMLDivElement; -} - -interface NavigatorDoNotTrack { - msDoNotTrack: string; -} - -interface SVG1_1Properties { - fillRule: string; - strokeLinecap: string; - stopColor: string; - glyphOrientationHorizontal: string; - kerning: string; - alignmentBaseline: string; - dominantBaseline: string; - fill: string; - strokeMiterlimit: string; - marker: string; - glyphOrientationVertical: string; - markerMid: string; - textAnchor: string; - fillOpacity: string; - strokeDasharray: string; - mask: string; - stopOpacity: string; - stroke: string; - strokeDashoffset: string; - strokeOpacity: string; - markerStart: string; - pointerEvents: string; - baselineShift: string; - markerEnd: string; - clipRule: string; - strokeLinejoin: string; - clipPath: string; - strokeWidth: string; -} - -interface NamedNodeMap { - length: number; - removeNamedItemNS(namespaceURI: string, localName: string): Node; - item(index: number): Node; - [index: number]: Node; - removeNamedItem(name: string): Node; - getNamedItem(name: string): Node; - [name: string]: Node; - setNamedItem(arg: Node): Node; - getNamedItemNS(namespaceURI: string, localName: string): Node; - setNamedItemNS(arg: Node): Node; -} -declare var NamedNodeMap: { - prototype: NamedNodeMap; - new(): NamedNodeMap; -} - -interface MediaList { - length: number; - mediaText: string; - deleteMedium(oldMedium: string): void; - appendMedium(newMedium: string): void; - item(index: number): string; - [index: number]: string; - toString(): string; -} -declare var MediaList: { - prototype: MediaList; - new(): MediaList; -} - -interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { - y: number; - x: number; -} -declare var SVGPathSegCurvetoQuadraticSmoothAbs: { - prototype: SVGPathSegCurvetoQuadraticSmoothAbs; - new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} - -interface SVGLengthList { - numberOfItems: number; - replaceItem(newItem: SVGLength, index: number): SVGLength; - getItem(index: number): SVGLength; - clear(): void; - appendItem(newItem: SVGLength): SVGLength; - initialize(newItem: SVGLength): SVGLength; - removeItem(index: number): SVGLength; - insertItemBefore(newItem: SVGLength, index: number): SVGLength; -} -declare var SVGLengthList: { - prototype: SVGLengthList; - new(): SVGLengthList; -} - -interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { - y: number; - x2: number; - x: number; - y2: number; -} -declare var SVGPathSegCurvetoCubicSmoothRel: { - prototype: SVGPathSegCurvetoCubicSmoothRel; - new(): SVGPathSegCurvetoCubicSmoothRel; -} - -interface MSWindowExtensions { - status: string; - onmouseleave: (ev: MouseEvent) => any; - screenLeft: number; - offscreenBuffering: any; - maxConnectionsPerServer: number; - onmouseenter: (ev: MouseEvent) => any; - clipboardData: DataTransfer; - defaultStatus: string; - clientInformation: Navigator; - closed: bool; - onhelp: (ev: Event) => any; - external: BrowserPublic; - event: MSEventObj; - onfocusout: (ev: FocusEvent) => any; - screenTop: number; - onfocusin: (ev: FocusEvent) => any; - showModelessDialog(url?: string, argument?: any, options?: any): Window; - navigate(url: string): void; - resizeBy(x?: number, y?: number): void; - item(index: any): any; - resizeTo(x?: number, y?: number): void; - createPopup(arguments?: any): MSPopupWindow; - toStaticHTML(html: string): string; - execScript(code: string, language?: string): any; - msWriteProfilerMark(profilerMarkName: string): void; - moveTo(x?: number, y?: number): void; - moveBy(x?: number, y?: number): void; - showHelp(url: string, helpArg?: any, features?: string): void; -} - -interface ProcessingInstruction extends Node { - target: string; - data: string; -} -declare var ProcessingInstruction: { - prototype: ProcessingInstruction; - new(): ProcessingInstruction; -} - -interface MSBehaviorUrnsCollection { - length: number; - item(index: number): string; -} -declare var MSBehaviorUrnsCollection: { - prototype: MSBehaviorUrnsCollection; - new(): MSBehaviorUrnsCollection; -} - -interface CSSFontFaceRule extends CSSRule { - style: CSSStyleDeclaration; -} -declare var CSSFontFaceRule: { - prototype: CSSFontFaceRule; - new(): CSSFontFaceRule; -} - -interface DOML2DeprecatedBackgroundStyle { - background: string; -} - -interface TextEvent extends UIEvent { - inputMethod: number; - data: string; - locale: string; - initTextEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, inputMethod: number, locale: string): void; - DOM_INPUT_METHOD_KEYBOARD: number; - DOM_INPUT_METHOD_DROP: number; - DOM_INPUT_METHOD_IME: number; - DOM_INPUT_METHOD_SCRIPT: number; - DOM_INPUT_METHOD_VOICE: number; - DOM_INPUT_METHOD_UNKNOWN: number; - DOM_INPUT_METHOD_PASTE: number; - DOM_INPUT_METHOD_HANDWRITING: number; - DOM_INPUT_METHOD_OPTION: number; - DOM_INPUT_METHOD_MULTIMODAL: number; -} -declare var TextEvent: { - prototype: TextEvent; - new(): TextEvent; - DOM_INPUT_METHOD_KEYBOARD: number; - DOM_INPUT_METHOD_DROP: number; - DOM_INPUT_METHOD_IME: number; - DOM_INPUT_METHOD_SCRIPT: number; - DOM_INPUT_METHOD_VOICE: number; - DOM_INPUT_METHOD_UNKNOWN: number; - DOM_INPUT_METHOD_PASTE: number; - DOM_INPUT_METHOD_HANDWRITING: number; - DOM_INPUT_METHOD_OPTION: number; - DOM_INPUT_METHOD_MULTIMODAL: number; -} - -interface MSHTMLHRElementExtensions extends DOML2DeprecatedColorProperty { -} - -interface AbstractView { - styleMedia: StyleMedia; - document: Document; -} - -interface DocumentFragment extends Node, NodeSelector, MSEventAttachmentTarget, MSNodeExtensions { -} -declare var DocumentFragment: { - prototype: DocumentFragment; - new(): DocumentFragment; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLFieldSetElement { - align: string; -} - -interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests { -} -declare var SVGPolylineElement: { - prototype: SVGPolylineElement; - new(): SVGPolylineElement; -} - -interface DOML2DeprecatedWidthStyle { - width: number; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLHeadingElement { - align: string; -} - -interface SVGAnimatedPathData { - pathSegList: SVGPathSegList; -} - -interface Position { - timestamp: Date; - coords: Coordinates; -} -declare var Position: { - prototype: Position; - new(): Position; -} - -interface BookmarkCollection { - length: number; - item(index: number): any; - [index: number]: any; -} -declare var BookmarkCollection: { - prototype: BookmarkCollection; - new(): BookmarkCollection; -} - -interface CSSPageRule extends CSSRule, StyleSheetPage { - selectorText: string; - style: CSSStyleDeclaration; -} -declare var CSSPageRule: { - prototype: CSSPageRule; - new(): CSSPageRule; -} - -interface WindowPerformance { - performance: any; -} - -interface HTMLBRElement extends HTMLElement, DOML2DeprecatedTextFlowControl_HTMLBRElement { -} -declare var HTMLBRElement: { - prototype: HTMLBRElement; - new(): HTMLBRElement; -} - -interface MSHTMLDivElementExtensions extends DOML2DeprecatedWordWrapSuppression_HTMLDivElement { -} - -interface DOML2DeprecatedBorderStyle_HTMLInputElement { - border: string; -} - -interface HTMLSpanElement extends HTMLElement, MSHTMLSpanElementExtensions, MSDataBindingExtensions { -} -declare var HTMLSpanElement: { - prototype: HTMLSpanElement; - new(): HTMLSpanElement; -} - -interface HTMLHRElementDOML2Deprecated { - noShade: bool; -} - -interface HTMLHeadElement extends HTMLElement { - profile: string; -} -declare var HTMLHeadElement: { - prototype: HTMLHeadElement; - new(): HTMLHeadElement; -} - -interface NodeFilterCallback { - (...args: any[]): any; -} - -interface HTMLHeadingElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLHeadingElement, MSHTMLHeadingElementExtensions { -} -declare var HTMLHeadingElement: { - prototype: HTMLHeadingElement; - new(): HTMLHeadingElement; -} - -interface HTMLFormElement extends HTMLElement, MSHTMLFormElementExtensions, MSHTMLCollectionExtensions { - length: number; - target: string; - acceptCharset: string; - enctype: string; - elements: HTMLCollection; - action: string; - name: string; - method: string; - reset(): void; - item(name?: any, index?: any): any; - (name: any, index: any): any; - submit(): void; - namedItem(name: string): any; - [name: string]: any; - (name: string): any; -} -declare var HTMLFormElement: { - prototype: HTMLFormElement; - new(): HTMLFormElement; -} - -interface SVGZoomAndPan { - zoomAndPan: number; - SVG_ZOOMANDPAN_MAGNIFY: number; - SVG_ZOOMANDPAN_UNKNOWN: number; - SVG_ZOOMANDPAN_DISABLE: number; -} -declare var SVGZoomAndPan: { - prototype: SVGZoomAndPan; - new(): SVGZoomAndPan; - SVG_ZOOMANDPAN_MAGNIFY: number; - SVG_ZOOMANDPAN_UNKNOWN: number; - SVG_ZOOMANDPAN_DISABLE: number; -} - -interface MSEventExtensions { - cancelBubble: bool; - srcElement: Element; -} - -interface HTMLMediaElement extends HTMLElement { - initialTime: number; - played: TimeRanges; - currentSrc: string; - readyState: string; - autobuffer: bool; - loop: bool; - ended: bool; - buffered: TimeRanges; - error: MediaError; - seekable: TimeRanges; - autoplay: bool; - controls: bool; - volume: number; - src: string; - playbackRate: number; - duration: number; - muted: bool; - defaultPlaybackRate: number; - paused: bool; - seeking: bool; - currentTime: number; - preload: string; - networkState: number; - pause(): void; - play(): void; - load(): void; - canPlayType(type: string): string; - HAVE_METADATA: number; - HAVE_CURRENT_DATA: number; - HAVE_NOTHING: number; - NETWORK_NO_SOURCE: number; - HAVE_ENOUGH_DATA: number; - NETWORK_EMPTY: number; - NETWORK_LOADING: number; - NETWORK_IDLE: number; - HAVE_FUTURE_DATA: number; -} -declare var HTMLMediaElement: { - prototype: HTMLMediaElement; - new(): HTMLMediaElement; - HAVE_METADATA: number; - HAVE_CURRENT_DATA: number; - HAVE_NOTHING: number; - NETWORK_NO_SOURCE: number; - HAVE_ENOUGH_DATA: number; - NETWORK_EMPTY: number; - NETWORK_LOADING: number; - NETWORK_IDLE: number; - HAVE_FUTURE_DATA: number; -} - -interface ElementCSSInlineStyle extends MSElementCSSInlineStyleExtensions { - runtimeStyle: MSStyleCSSProperties; - currentStyle: MSCurrentStyleCSSProperties; -} - -interface DOMParser { - parseFromString(source: string, mimeType: string): Document; -} -declare var DOMParser: { - prototype: DOMParser; - new (): DOMParser; -} - -interface MSMimeTypesCollection { - length: number; -} -declare var MSMimeTypesCollection: { - prototype: MSMimeTypesCollection; - new(): MSMimeTypesCollection; -} - -interface StyleSheet { - disabled: bool; - ownerNode: Node; - parentStyleSheet: StyleSheet; - href: string; - media: MediaList; - type: string; - title: string; -} -declare var StyleSheet: { - prototype: StyleSheet; - new(): StyleSheet; -} - -interface DOML2DeprecatedBorderStyle_HTMLTableElement { - border: string; -} - -interface DOML2DeprecatedWidthStyle_HTMLAppletElement { - width: number; -} - -interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { - startOffset: SVGAnimatedLength; - method: SVGAnimatedEnumeration; - spacing: SVGAnimatedEnumeration; - TEXTPATH_SPACINGTYPE_EXACT: number; - TEXTPATH_METHODTYPE_STRETCH: number; - TEXTPATH_SPACINGTYPE_AUTO: number; - TEXTPATH_SPACINGTYPE_UNKNOWN: number; - TEXTPATH_METHODTYPE_UNKNOWN: number; - TEXTPATH_METHODTYPE_ALIGN: number; -} -declare var SVGTextPathElement: { - prototype: SVGTextPathElement; - new(): SVGTextPathElement; - TEXTPATH_SPACINGTYPE_EXACT: number; - TEXTPATH_METHODTYPE_STRETCH: number; - TEXTPATH_SPACINGTYPE_AUTO: number; - TEXTPATH_SPACINGTYPE_UNKNOWN: number; - TEXTPATH_METHODTYPE_UNKNOWN: number; - TEXTPATH_METHODTYPE_ALIGN: number; -} - -interface NodeList { - length: number; - item(index: number): Node; - [index: number]: Node; -} -declare var NodeList: { - prototype: NodeList; - new(): NodeList; -} - -interface HTMLDTElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDTElement { -} -declare var HTMLDTElement: { - prototype: HTMLDTElement; - new(): HTMLDTElement; -} - -interface XMLSerializer { - serializeToString(target: Node): string; -} -declare var XMLSerializer: { - prototype: XMLSerializer; - new (): XMLSerializer; -} - -interface StyleSheetPage { - pseudoClass: string; - selector: string; -} - -interface DOML2DeprecatedWordWrapSuppression_HTMLDDElement { - noWrap: bool; -} - -interface MSHTMLTableRowElementExtensions { - height: any; -} - -interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGURIReference { - spreadMethod: SVGAnimatedEnumeration; - gradientTransform: SVGAnimatedTransformList; - gradientUnits: SVGAnimatedEnumeration; - SVG_SPREADMETHOD_REFLECT: number; - SVG_SPREADMETHOD_PAD: number; - SVG_SPREADMETHOD_UNKNOWN: number; - SVG_SPREADMETHOD_REPEAT: number; -} -declare var SVGGradientElement: { - prototype: SVGGradientElement; - new(): SVGGradientElement; - SVG_SPREADMETHOD_REFLECT: number; - SVG_SPREADMETHOD_PAD: number; - SVG_SPREADMETHOD_UNKNOWN: number; - SVG_SPREADMETHOD_REPEAT: number; -} - -interface DOML2DeprecatedTextFlowControl_HTMLBRElement { - clear: string; -} - -interface MSHTMLParagraphElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { -} - -interface NodeFilter { - acceptNode(n: Node): number; - SHOW_ENTITY_REFERENCE: number; - SHOW_NOTATION: number; - SHOW_ENTITY: number; - SHOW_DOCUMENT: number; - SHOW_PROCESSING_INSTRUCTION: number; - FILTER_REJECT: number; - SHOW_CDATA_SECTION: number; - FILTER_ACCEPT: number; - SHOW_ALL: number; - SHOW_DOCUMENT_TYPE: number; - SHOW_TEXT: number; - SHOW_ELEMENT: number; - SHOW_COMMENT: number; - FILTER_SKIP: number; - SHOW_ATTRIBUTE: number; - SHOW_DOCUMENT_FRAGMENT: number; -} -declare var NodeFilter: { - prototype: NodeFilter; - new(): NodeFilter; - SHOW_ENTITY_REFERENCE: number; - SHOW_NOTATION: number; - SHOW_ENTITY: number; - SHOW_DOCUMENT: number; - SHOW_PROCESSING_INSTRUCTION: number; - FILTER_REJECT: number; - SHOW_CDATA_SECTION: number; - FILTER_ACCEPT: number; - SHOW_ALL: number; - SHOW_DOCUMENT_TYPE: number; - SHOW_TEXT: number; - SHOW_ELEMENT: number; - SHOW_COMMENT: number; - FILTER_SKIP: number; - SHOW_ATTRIBUTE: number; - SHOW_DOCUMENT_FRAGMENT: number; -} - -interface MSBorderColorStyle_HTMLFrameElement { - borderColor: any; -} - -interface MSHTMLOListElementExtensions { -} - -interface DOML2DeprecatedWordWrapSuppression_HTMLDTElement { - noWrap: bool; -} - -interface ScreenView extends AbstractView { - outerWidth: number; - pageXOffset: number; - innerWidth: number; - pageYOffset: number; - screenY: number; - outerHeight: number; - screen: Screen; - innerHeight: number; - screenX: number; - scroll(x?: number, y?: number): void; - scrollBy(x?: number, y?: number): void; - scrollTo(x?: number, y?: number): void; -} - -interface DOML2DeprecatedMarginStyle_HTMLObjectElement { - vspace: number; - hspace: number; -} - -interface DOML2DeprecatedMarginStyle_HTMLInputElement { - vspace: number; - hspace: number; -} - -interface MSHTMLTableSectionElementExtensions extends DOML2DeprecatedBackgroundColorStyle { - moveRow(indexFrom?: number, indexTo?: number): Object; -} - -interface HTMLFieldSetElement extends HTMLElement, MSHTMLFieldSetElementExtensions { - form: HTMLFormElement; -} -declare var HTMLFieldSetElement: { - prototype: HTMLFieldSetElement; - new(): HTMLFieldSetElement; -} - -interface MediaError { - code: number; - MEDIA_ERR_ABORTED: number; - MEDIA_ERR_NETWORK: number; - MEDIA_ERR_SRC_NOT_SUPPORTED: number; - MEDIA_ERR_DECODE: number; -} -declare var MediaError: { - prototype: MediaError; - new(): MediaError; - MEDIA_ERR_ABORTED: number; - MEDIA_ERR_NETWORK: number; - MEDIA_ERR_SRC_NOT_SUPPORTED: number; - MEDIA_ERR_DECODE: number; -} - -interface SVGNumberList { - numberOfItems: number; - replaceItem(newItem: SVGNumber, index: number): SVGNumber; - getItem(index: number): SVGNumber; - clear(): void; - appendItem(newItem: SVGNumber): SVGNumber; - initialize(newItem: SVGNumber): SVGNumber; - removeItem(index: number): SVGNumber; - insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; -} -declare var SVGNumberList: { - prototype: SVGNumberList; - new(): SVGNumberList; -} - -interface HTMLBGSoundElement extends HTMLElement { - balance: any; - volume: any; - src: string; - loop: number; -} -declare var HTMLBGSoundElement: { - prototype: HTMLBGSoundElement; - new(): HTMLBGSoundElement; -} - -interface HTMLElement extends Element, MSHTMLElementRangeExtensions, ElementCSSInlineStyle, MSEventAttachmentTarget, MSHTMLElementExtensions, MSNodeExtensions { - ondragend: (ev: DragEvent) => any; - onkeydown: (ev: KeyboardEvent) => any; - ondragover: (ev: DragEvent) => any; - onkeyup: (ev: KeyboardEvent) => any; - offsetTop: number; - onreset: (ev: Event) => any; - onmouseup: (ev: MouseEvent) => any; - ondragstart: (ev: DragEvent) => any; - ondrag: (ev: DragEvent) => any; - innerHTML: string; - onmouseover: (ev: MouseEvent) => any; - ondragleave: (ev: DragEvent) => any; - lang: string; - onpause: (ev: Event) => any; - className: string; - onseeked: (ev: Event) => any; - onmousedown: (ev: MouseEvent) => any; - title: string; - onclick: (ev: MouseEvent) => any; - onwaiting: (ev: Event) => any; - outerHTML: string; - offsetLeft: number; - ondurationchange: (ev: Event) => any; - offsetHeight: number; - dir: string; - onblur: (ev: FocusEvent) => any; - onemptied: (ev: Event) => any; - onseeking: (ev: Event) => any; - oncanplay: (ev: Event) => any; - onstalled: (ev: Event) => any; - onmousemove: (ev: MouseEvent) => any; - style: MSStyleCSSProperties; - isContentEditable: bool; - onratechange: (ev: Event) => any; - onloadstart: (ev: Event) => any; - ondragenter: (ev: DragEvent) => any; - contentEditable: string; - onsubmit: (ev: Event) => any; - tabIndex: number; - onprogress: (ev: any) => any; - ondblclick: (ev: MouseEvent) => any; - oncontextmenu: (ev: MouseEvent) => any; - onchange: (ev: Event) => any; - onloadedmetadata: (ev: Event) => any; - onerror: (ev: Event) => any; - onplay: (ev: Event) => any; - id: string; - onplaying: (ev: Event) => any; - oncanplaythrough: (ev: Event) => any; - onabort: (ev: UIEvent) => any; - onreadystatechange: (ev: Event) => any; - onkeypress: (ev: KeyboardEvent) => any; - offsetParent: Element; - onloadeddata: (ev: Event) => any; - disabled: bool; - onsuspend: (ev: Event) => any; - accessKey: string; - onfocus: (ev: FocusEvent) => any; - ontimeupdate: (ev: Event) => any; - onselect: (ev: UIEvent) => any; - ondrop: (ev: DragEvent) => any; - offsetWidth: number; - onmouseout: (ev: MouseEvent) => any; - onended: (ev: Event) => any; - onscroll: (ev: UIEvent) => any; - onmousewheel: (ev: MouseWheelEvent) => any; - onvolumechange: (ev: Event) => any; - onload: (ev: Event) => any; - oninput: (ev: Event) => any; - click(): void; - getElementsByClassName(classNames: string): NodeList; - scrollIntoView(top?: bool): void; - focus(): void; - blur(): void; - insertAdjacentHTML(where: string, html: string): void; -} -declare var HTMLElement: { - prototype: HTMLElement; - new(): HTMLElement; -} - -interface Comment extends CharacterData, MSCommentExtensions { -} -declare var Comment: { - prototype: Comment; - new(): Comment; -} - -interface CanvasPattern { -} -declare var CanvasPattern: { - prototype: CanvasPattern; - new(): CanvasPattern; -} - -interface HTMLHRElement extends HTMLElement, DOML2DeprecatedWidthStyle_HTMLHRElement, MSHTMLHRElementExtensions, HTMLHRElementDOML2Deprecated, DOML2DeprecatedAlignmentStyle_HTMLHRElement, DOML2DeprecatedSizeProperty { -} -declare var HTMLHRElement: { - prototype: HTMLHRElement; - new(): HTMLHRElement; -} - -interface MSHTMLFrameSetElementExtensions { - name: string; - frameBorder: string; - border: string; - frameSpacing: any; -} - -interface DOML2DeprecatedTextFlowControl_HTMLBlockElement { - clear: string; -} - -interface PositionOptions { - enableHighAccuracy?: bool; - timeout?: number; - maximumAge?: number; -} - -interface HTMLObjectElement extends HTMLElement, MSHTMLObjectElementExtensions, GetSVGDocument, DOML2DeprecatedMarginStyle_HTMLObjectElement, MSDataBindingExtensions, MSDataBindingRecordSetExtensions, DOML2DeprecatedAlignmentStyle_HTMLObjectElement, DOML2DeprecatedBorderStyle_HTMLObjectElement { - width: string; - codeType: string; - archive: string; - standby: string; - name: string; - useMap: string; - form: HTMLFormElement; - data: string; - height: string; - contentDocument: Document; - codeBase: string; - declare: bool; - type: string; - code: string; -} -declare var HTMLObjectElement: { - prototype: HTMLObjectElement; - new(): HTMLObjectElement; -} - -interface MSHTMLMenuElementExtensions { -} - -interface DocumentView { - defaultView: AbstractView; - elementFromPoint(x: number, y: number): Element; -} - -interface StorageEvent extends Event { - oldValue: any; - newValue: any; - url: string; - storageArea: Storage; - key: string; - initStorageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; -} -declare var StorageEvent: { - prototype: StorageEvent; - new(): StorageEvent; -} - -interface HTMLEmbedElement extends HTMLElement, GetSVGDocument, MSHTMLEmbedElementExtensions { - width: string; - src: string; - name: string; - height: string; -} -declare var HTMLEmbedElement: { - prototype: HTMLEmbedElement; - new(): HTMLEmbedElement; -} - -interface CharacterData extends Node { - length: number; - data: string; - deleteData(offset: number, count: number): void; - replaceData(offset: number, count: number, arg: string): void; - appendData(arg: string): void; - insertData(offset: number, arg: string): void; - substringData(offset: number, count: number): string; -} -declare var CharacterData: { - prototype: CharacterData; - new(): CharacterData; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLTableSectionElement { - align: string; -} - -interface HTMLOptGroupElement extends HTMLElement, MSDataBindingExtensions, MSHTMLOptGroupElementExtensions { - label: string; -} -declare var HTMLOptGroupElement: { - prototype: HTMLOptGroupElement; - new(): HTMLOptGroupElement; -} - -interface HTMLIsIndexElement extends HTMLElement, MSHTMLIsIndexElementExtensions { - form: HTMLFormElement; - prompt: string; -} -declare var HTMLIsIndexElement: { - prototype: HTMLIsIndexElement; - new(): HTMLIsIndexElement; -} - -interface SVGPathSegLinetoRel extends SVGPathSeg { - y: number; - x: number; -} -declare var SVGPathSegLinetoRel: { - prototype: SVGPathSegLinetoRel; - new(): SVGPathSegLinetoRel; -} - -interface MSHTMLDocumentSelection { - selection: MSSelection; -} - -interface DOMException { - code: number; - message: string; - toString(): string; - HIERARCHY_REQUEST_ERR: number; - NO_MODIFICATION_ALLOWED_ERR: number; - INVALID_MODIFICATION_ERR: number; - NAMESPACE_ERR: number; - INVALID_CHARACTER_ERR: number; - TYPE_MISMATCH_ERR: number; - ABORT_ERR: number; - INVALID_STATE_ERR: number; - SECURITY_ERR: number; - NETWORK_ERR: number; - WRONG_DOCUMENT_ERR: number; - QUOTA_EXCEEDED_ERR: number; - INDEX_SIZE_ERR: number; - DOMSTRING_SIZE_ERR: number; - SYNTAX_ERR: number; - SERIALIZE_ERR: number; - VALIDATION_ERR: number; - NOT_FOUND_ERR: number; - URL_MISMATCH_ERR: number; - PARSE_ERR: number; - NO_DATA_ALLOWED_ERR: number; - NOT_SUPPORTED_ERR: number; - INVALID_ACCESS_ERR: number; - INUSE_ATTRIBUTE_ERR: number; -} -declare var DOMException: { - prototype: DOMException; - new(): DOMException; - HIERARCHY_REQUEST_ERR: number; - NO_MODIFICATION_ALLOWED_ERR: number; - INVALID_MODIFICATION_ERR: number; - NAMESPACE_ERR: number; - INVALID_CHARACTER_ERR: number; - TYPE_MISMATCH_ERR: number; - ABORT_ERR: number; - INVALID_STATE_ERR: number; - SECURITY_ERR: number; - NETWORK_ERR: number; - WRONG_DOCUMENT_ERR: number; - QUOTA_EXCEEDED_ERR: number; - INDEX_SIZE_ERR: number; - DOMSTRING_SIZE_ERR: number; - SYNTAX_ERR: number; - SERIALIZE_ERR: number; - VALIDATION_ERR: number; - NOT_FOUND_ERR: number; - URL_MISMATCH_ERR: number; - PARSE_ERR: number; - NO_DATA_ALLOWED_ERR: number; - NOT_SUPPORTED_ERR: number; - INVALID_ACCESS_ERR: number; - INUSE_ATTRIBUTE_ERR: number; -} - -interface MSCompatibleInfoCollection { - length: number; - item(index: number): MSCompatibleInfo; -} -declare var MSCompatibleInfoCollection: { - prototype: MSCompatibleInfoCollection; - new(): MSCompatibleInfoCollection; -} - -interface MSHTMLIsIndexElementExtensions { - action: string; -} - -interface SVGAnimatedBoolean { - animVal: bool; - baseVal: bool; -} -declare var SVGAnimatedBoolean: { - prototype: SVGAnimatedBoolean; - new(): SVGAnimatedBoolean; -} - -interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { -} -declare var SVGSwitchElement: { - prototype: SVGSwitchElement; - new(): SVGSwitchElement; -} - -interface MSHTMLIFrameElementExtensions extends DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions, DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { - onload: (ev: Event) => any; - frameSpacing: any; - noResize: bool; -} - -interface SVGPreserveAspectRatio { - align: number; - meetOrSlice: number; - SVG_PRESERVEASPECTRATIO_NONE: number; - SVG_PRESERVEASPECTRATIO_XMINYMID: number; - SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - SVG_MEETORSLICE_UNKNOWN: number; - SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - SVG_PRESERVEASPECTRATIO_XMINYMIN: number; - SVG_MEETORSLICE_MEET: number; - SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - SVG_MEETORSLICE_SLICE: number; - SVG_PRESERVEASPECTRATIO_UNKNOWN: number; -} -declare var SVGPreserveAspectRatio: { - prototype: SVGPreserveAspectRatio; - new(): SVGPreserveAspectRatio; - SVG_PRESERVEASPECTRATIO_NONE: number; - SVG_PRESERVEASPECTRATIO_XMINYMID: number; - SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; - SVG_PRESERVEASPECTRATIO_XMINYMAX: number; - SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; - SVG_MEETORSLICE_UNKNOWN: number; - SVG_PRESERVEASPECTRATIO_XMAXYMID: number; - SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; - SVG_PRESERVEASPECTRATIO_XMINYMIN: number; - SVG_MEETORSLICE_MEET: number; - SVG_PRESERVEASPECTRATIO_XMIDYMID: number; - SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; - SVG_MEETORSLICE_SLICE: number; - SVG_PRESERVEASPECTRATIO_UNKNOWN: number; -} - -interface Attr extends Node, MSAttrExtensions { - specified: bool; - ownerElement: Element; - value: string; - name: string; -} -declare var Attr: { - prototype: Attr; - new(): Attr; -} - -interface MSBorderColorStyle_HTMLTableRowElement { - borderColor: any; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLTableCaptionElement { - align: string; -} - -interface PerformanceNavigation { - redirectCount: number; - type: number; - toJSON(): any; - TYPE_RELOAD: number; - TYPE_RESERVED: number; - TYPE_BACK_FORWARD: number; - TYPE_NAVIGATE: number; -} -declare var PerformanceNavigation: { - prototype: PerformanceNavigation; - new(): PerformanceNavigation; - TYPE_RELOAD: number; - TYPE_RESERVED: number; - TYPE_BACK_FORWARD: number; - TYPE_NAVIGATE: number; -} - -interface HTMLBodyElementDOML2Deprecated { - link: any; - aLink: any; - text: any; - vLink: any; -} - -interface SVGStopElement extends SVGElement, SVGStylable { - offset: SVGAnimatedNumber; -} -declare var SVGStopElement: { - prototype: SVGStopElement; - new(): SVGStopElement; -} - -interface PositionCallback { - (position: Position): void; -} - -interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox { -} -declare var SVGSymbolElement: { - prototype: SVGSymbolElement; - new(): SVGSymbolElement; -} - -interface SVGElementInstanceList { - length: number; - item(index: number): SVGElementInstance; -} -declare var SVGElementInstanceList: { - prototype: SVGElementInstanceList; - new(): SVGElementInstanceList; -} - -interface MSDataBindingRecordSetExtensions { - recordset: Object; - namedRecordset(dataMember: string, hierarchy?: any): Object; -} - -interface CSSRuleList { - length: number; - item(index: number): CSSRule; - [index: number]: CSSRule; -} -declare var CSSRuleList: { - prototype: CSSRuleList; - new(): CSSRuleList; -} - -interface MSHTMLTableColElementExtensions { -} - -interface LinkStyle { - sheet: StyleSheet; -} - -interface MSHTMLMarqueeElementExtensions { -} - -interface HTMLVideoElement extends HTMLMediaElement { - width: number; - videoWidth: number; - videoHeight: number; - height: number; - poster: string; -} -declare var HTMLVideoElement: { - prototype: HTMLVideoElement; - new(): HTMLVideoElement; -} - -interface MSXMLHttpRequestExtensions { - responseBody: any; - timeout: number; - ontimeout: (ev: Event) => any; -} - -interface ClientRectList { - length: number; - item(index: number): ClientRect; - [index: number]: ClientRect; -} -declare var ClientRectList: { - prototype: ClientRectList; - new(): ClientRectList; -} - -interface DOML2DeprecatedAlignmentStyle_HTMLTableCellElement { - align: string; -} - -interface SVGMaskElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests { - y: SVGAnimatedLength; - width: SVGAnimatedLength; - maskUnits: SVGAnimatedEnumeration; - maskContentUnits: SVGAnimatedEnumeration; - x: SVGAnimatedLength; - height: SVGAnimatedLength; -} -declare var SVGMaskElement: { - prototype: SVGMaskElement; - new(): SVGMaskElement; -} - -declare var Audio: { new (src?: string): HTMLAudioElement; }; -declare var Option: { new (text?: string, value?: string, defaultSelected?: bool, selected?: bool): HTMLOptionElement; }; -declare var Image: { new (width?: number, height?: number): HTMLImageElement; }; - -declare var ondragend: (ev: DragEvent) => any; -declare var onkeydown: (ev: KeyboardEvent) => any; -declare var ondragover: (ev: DragEvent) => any; -declare var onkeyup: (ev: KeyboardEvent) => any; -declare var onreset: (ev: Event) => any; -declare var onmouseup: (ev: MouseEvent) => any; -declare var ondragstart: (ev: DragEvent) => any; -declare var ondrag: (ev: DragEvent) => any; -declare var onmouseover: (ev: MouseEvent) => any; -declare var ondragleave: (ev: DragEvent) => any; -declare var history: History; -declare var name: string; -declare var onafterprint: (ev: Event) => any; -declare var onpause: (ev: Event) => any; -declare var onbeforeprint: (ev: Event) => any; -declare var top: Window; -declare var onmousedown: (ev: MouseEvent) => any; -declare var onseeked: (ev: Event) => any; -declare var opener: Window; -declare var onclick: (ev: MouseEvent) => any; -declare var onwaiting: (ev: Event) => any; -declare var ononline: (ev: Event) => any; -declare var ondurationchange: (ev: Event) => any; -declare var frames: Window; -declare var onblur: (ev: FocusEvent) => any; -declare var onemptied: (ev: Event) => any; -declare var onseeking: (ev: Event) => any; -declare var oncanplay: (ev: Event) => any; -declare var onstalled: (ev: Event) => any; -declare var onmousemove: (ev: MouseEvent) => any; -declare var onoffline: (ev: Event) => any; -declare var length: number; -declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; -declare var onratechange: (ev: Event) => any; -declare var onstorage: (ev: StorageEvent) => any; -declare var onloadstart: (ev: Event) => any; -declare var ondragenter: (ev: DragEvent) => any; -declare var onsubmit: (ev: Event) => any; -declare var self: Window; -declare var onprogress: (ev: any) => any; -declare var ondblclick: (ev: MouseEvent) => any; -declare var oncontextmenu: (ev: MouseEvent) => any; -declare var onchange: (ev: Event) => any; -declare var onloadedmetadata: (ev: Event) => any; -declare var onplay: (ev: Event) => any; -declare var onerror: ErrorFunction; -declare var onplaying: (ev: Event) => any; -declare var parent: Window; -declare var location: Location; -declare var oncanplaythrough: (ev: Event) => any; -declare var onabort: (ev: UIEvent) => any; -declare var onreadystatechange: (ev: Event) => any; -declare var onkeypress: (ev: KeyboardEvent) => any; -declare var frameElement: Element; -declare var onloadeddata: (ev: Event) => any; -declare var onsuspend: (ev: Event) => any; -declare var window: Window; -declare var onfocus: (ev: FocusEvent) => any; -declare var onmessage: (ev: MessageEvent) => any; -declare var ontimeupdate: (ev: Event) => any; -declare var onresize: (ev: UIEvent) => any; -declare var navigator: Navigator; -declare var onselect: (ev: UIEvent) => any; -declare var ondrop: (ev: DragEvent) => any; -declare var onmouseout: (ev: MouseEvent) => any; -declare var onended: (ev: Event) => any; -declare var onhashchange: (ev: Event) => any; -declare var onunload: (ev: Event) => any; -declare var onscroll: (ev: UIEvent) => any; -declare var onmousewheel: (ev: MouseWheelEvent) => any; -declare var onload: (ev: Event) => any; -declare var onvolumechange: (ev: Event) => any; -declare var oninput: (ev: Event) => any; -declare function alert(message?: string): void; -declare function focus(): void; -declare function print(): void; -declare function prompt(message?: string, defaul?: string): string; -declare function toString(): string; -declare function open(url?: string, target?: string, features?: string, replace?: bool): Window; -declare function close(): void; -declare function confirm(message?: string): bool; -declare function postMessage(message: any, targetOrigin: string, ports?: any): void; -declare function showModalDialog(url?: string, argument?: any, options?: any): any; -declare function blur(): void; -declare function getSelection(): Selection; -declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -declare function attachEvent(event: string, listener: EventListener): bool; -declare function detachEvent(event: string, listener: EventListener): void; -declare var status: string; -declare var onmouseleave: (ev: MouseEvent) => any; -declare var screenLeft: number; -declare var offscreenBuffering: any; -declare var maxConnectionsPerServer: number; -declare var onmouseenter: (ev: MouseEvent) => any; -declare var clipboardData: DataTransfer; -declare var defaultStatus: string; -declare var clientInformation: Navigator; -declare var closed: bool; -declare var onhelp: (ev: Event) => any; -declare var external: BrowserPublic; -declare var event: MSEventObj; -declare var onfocusout: (ev: FocusEvent) => any; -declare var screenTop: number; -declare var onfocusin: (ev: FocusEvent) => any; -declare function showModelessDialog(url?: string, argument?: any, options?: any): Window; -declare function navigate(url: string): void; -declare function resizeBy(x?: number, y?: number): void; -declare function item(index: any): any; -declare function resizeTo(x?: number, y?: number): void; -declare function createPopup(arguments?: any): MSPopupWindow; -declare function toStaticHTML(html: string): string; -declare function execScript(code: string, language?: string): any; -declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function moveTo(x?: number, y?: number): void; -declare function moveBy(x?: number, y?: number): void; -declare function showHelp(url: string, helpArg?: any, features?: string): void; -declare var performance: any; -declare var outerWidth: number; -declare var pageXOffset: number; -declare var innerWidth: number; -declare var pageYOffset: number; -declare var screenY: number; -declare var outerHeight: number; -declare var screen: Screen; -declare var innerHeight: number; -declare var screenX: number; -declare function scroll(x?: number, y?: number): void; -declare function scrollBy(x?: number, y?: number): void; -declare function scrollTo(x?: number, y?: number): void; -declare var styleMedia: StyleMedia; -declare var document: Document; -declare function removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; -declare function addEventListener(type: string, listener: EventListener, useCapture?: bool): void; -declare function dispatchEvent(evt: Event): bool; -declare var localStorage: Storage; -declare var sessionStorage: Storage; -declare function clearTimeout(handle: number): void; -declare function setTimeout(expression: any, msec?: number, language?: any): number; -declare function clearInterval(handle: number): void; -declare function setInterval(expression: any, msec?: number, language?: any): number; - - -///////////////////////////// -/// IE10 DOM APIs -///////////////////////////// - -interface HTMLBodyElement { - onpopstate: (ev: PopStateEvent) => any; -} - -interface MSGestureEvent extends UIEvent { - offsetY: number; - translationY: number; - velocityExpansion: number; - velocityY: number; - velocityAngular: number; - translationX: number; - velocityX: number; - hwTimestamp: number; - offsetX: number; - screenX: number; - rotation: number; - expansion: number; - clientY: number; - screenY: number; - scale: number; - gestureObject: any; - clientX: number; - initGestureEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; - MSGESTURE_FLAG_BEGIN: number; - MSGESTURE_FLAG_END: number; - MSGESTURE_FLAG_CANCEL: number; - MSGESTURE_FLAG_INERTIA: number; - MSGESTURE_FLAG_NONE: number; -} -declare var MSGestureEvent: { - prototype: MSGestureEvent; - new(): MSGestureEvent; - MSGESTURE_FLAG_BEGIN: number; - MSGESTURE_FLAG_END: number; - MSGESTURE_FLAG_CANCEL: number; - MSGESTURE_FLAG_INERTIA: number; - MSGESTURE_FLAG_NONE: number; -} - -interface HTMLAnchorElement { - text: string; -} - -interface HTMLInputElement { - validationMessage: string; - files: FileList; - max: string; - formTarget: string; - willValidate: bool; - step: string; - autofocus: bool; - required: bool; - formEnctype: string; - valueAsNumber: number; - placeholder: string; - formMethod: string; - list: HTMLElement; - autocomplete: string; - min: string; - formAction: string; - pattern: string; - validity: ValidityState; - formNoValidate: string; - multiple: bool; - checkValidity(): bool; - stepDown(n?: number): void; - stepUp(n?: number): void; - setCustomValidity(error: string): void; -} - -interface ErrorEvent extends Event { - colno: number; - filename: string; - lineno: number; - message: string; - initErrorEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, messageArg: string, filenameArg: string, linenoArg: number): void; -} -declare var ErrorEvent: { - prototype: ErrorEvent; - new(): ErrorEvent; -} - -interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference { - y: SVGAnimatedLength; - width: SVGAnimatedLength; - filterResX: SVGAnimatedInteger; - filterUnits: SVGAnimatedEnumeration; - primitiveUnits: SVGAnimatedEnumeration; - x: SVGAnimatedLength; - height: SVGAnimatedLength; - filterResY: SVGAnimatedInteger; - setFilterRes(filterResX: number, filterResY: number): void; -} -declare var SVGFilterElement: { - prototype: SVGFilterElement; - new(): SVGFilterElement; -} - -interface TrackEvent extends Event { - track: any; -} -declare var TrackEvent: { - prototype: TrackEvent; - new(): TrackEvent; -} - -interface SVGFEMergeNodeElement extends SVGElement { - in1: SVGAnimatedString; -} -declare var SVGFEMergeNodeElement: { - prototype: SVGFEMergeNodeElement; - new(): SVGFEMergeNodeElement; -} - -interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { -} -declare var SVGFEFloodElement: { - prototype: SVGFEFloodElement; - new(): SVGFEFloodElement; -} - -interface MSElementExtensions { - msRegionOverflow: string; - onmspointerdown: (ev: any) => any; - onmsgotpointercapture: (ev: any) => any; - onmsgesturedoubletap: (ev: any) => any; - onmspointerhover: (ev: any) => any; - onmsgesturehold: (ev: any) => any; - onmspointermove: (ev: any) => any; - onmsgesturechange: (ev: any) => any; - onmsgesturestart: (ev: any) => any; - onmspointercancel: (ev: any) => any; - onmsgestureend: (ev: any) => any; - onmsgesturetap: (ev: any) => any; - onmspointerout: (ev: any) => any; - onmsinertiastart: (ev: any) => any; - onmslostpointercapture: (ev: any) => any; - onmspointerover: (ev: any) => any; - msContentZoomFactor: number; - onmspointerup: (ev: any) => any; - msGetRegionContent(): MSRangeCollection; - msReleasePointerCapture(pointerId: number): void; - msSetPointerCapture(pointerId: number): void; -} -declare var MSElementExtensions: { - prototype: MSElementExtensions; - new(): MSElementExtensions; -} - -interface MSCSSScrollTranslationProperties { - msScrollTranslation: string; -} - -interface MSGesture { - target: Element; - addPointer(pointerId: number): void; - stop(): void; -} -declare var MSGesture: { - prototype: MSGesture; - new (): MSGesture; -} - -interface TextTrackCue extends EventTarget { - onenter: (ev: Event) => any; - track: TextTrack; - endTime: number; - text: string; - pauseOnExit: bool; - id: string; - startTime: number; - onexit: (ev: Event) => any; - getCueAsHTML(): DocumentFragment; -} -declare var TextTrackCue: { - prototype: TextTrackCue; - new(): TextTrackCue; -} - -interface MSHTMLDocumentViewExtensions { - msCSSOMElementFloatMetrics: bool; - msElementsFromPoint(x: number, y: number): NodeList; - msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; -} -declare var MSHTMLDocumentViewExtensions: { - prototype: MSHTMLDocumentViewExtensions; - new(): MSHTMLDocumentViewExtensions; -} - -interface MSStreamReader extends MSBaseReader { - error: DOMError; - readAsArrayBuffer(stream: MSStream, size?: number): void; - readAsBlob(stream: MSStream, size?: number): void; - readAsDataURL(stream: MSStream, size?: number): void; - readAsText(stream: MSStream, encoding?: string, size?: number): void; -} -declare var MSStreamReader: { - prototype: MSStreamReader; - new (): MSStreamReader; -} - -interface CSSFlexibleBoxProperties { - msFlex: string; - msFlexDirection: string; - msFlexNegative: string; - msFlexPack: string; - msFlexWrap: string; - msFlexItemAlign: string; - msFlexOrder: string; - msFlexPositive: string; - msFlexAlign: string; - msFlexFlow: string; - msFlexPreferredSize: string; - msFlexLinePack: string; -} - -interface DOMTokenList { - length: number; - contains(token: string): bool; - remove(token: string): void; - toggle(token: string): bool; - add(token: string): void; - item(index: number): string; - [index: number]: string; - toString(): string; -} -declare var DOMTokenList: { - prototype: DOMTokenList; - new(): DOMTokenList; -} - -interface EventException { - name: string; -} - -interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { -} -declare var SVGFEFuncAElement: { - prototype: SVGFEFuncAElement; - new(): SVGFEFuncAElement; -} - -interface Performance { - now(): number; -} - -interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - in1: SVGAnimatedString; -} -declare var SVGFETileElement: { - prototype: SVGFETileElement; - new(): SVGFETileElement; -} - -interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - in2: SVGAnimatedString; - mode: SVGAnimatedEnumeration; - in1: SVGAnimatedString; - SVG_FEBLEND_MODE_DARKEN: number; - SVG_FEBLEND_MODE_UNKNOWN: number; - SVG_FEBLEND_MODE_MULTIPLY: number; - SVG_FEBLEND_MODE_NORMAL: number; - SVG_FEBLEND_MODE_SCREEN: number; - SVG_FEBLEND_MODE_LIGHTEN: number; -} -declare var SVGFEBlendElement: { - prototype: SVGFEBlendElement; - new(): SVGFEBlendElement; - SVG_FEBLEND_MODE_DARKEN: number; - SVG_FEBLEND_MODE_UNKNOWN: number; - SVG_FEBLEND_MODE_MULTIPLY: number; - SVG_FEBLEND_MODE_NORMAL: number; - SVG_FEBLEND_MODE_SCREEN: number; - SVG_FEBLEND_MODE_LIGHTEN: number; -} - -interface WindowTimers extends WindowTimersExtension { -} -declare var WindowTimers: { - prototype: WindowTimers; - new(): WindowTimers; -} - -interface CSSStyleDeclaration extends CSS2DTransformsProperties, CSSTransitionsProperties, CSSFontsProperties, MSCSSHighContrastProperties, CSSGridProperties, CSSAnimationsProperties, MSCSSContentZoomProperties, MSCSSScrollTranslationProperties, MSCSSTouchManipulationProperties, CSSFlexibleBoxProperties, MSCSSPositionedFloatsProperties, MSCSSRegionProperties, MSCSSSelectionBoundaryProperties, CSSMultiColumnProperties, CSSTextProperties, CSS3DTransformsProperties { -} - -interface MessageChannel { - port2: MessagePort; - port1: MessagePort; -} -declare var MessageChannel: { - prototype: MessageChannel; - new (): MessageChannel; -} - -interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { -} -declare var SVGFEMergeElement: { - prototype: SVGFEMergeElement; - new(): SVGFEMergeElement; -} - -interface Navigator extends MSFileSaver { -} - -interface TransitionEvent extends Event { - propertyName: string; - elapsedTime: number; - initTransitionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, propertyNameArg: string, elapsedTimeArg: number): void; -} -declare var TransitionEvent: { - prototype: TransitionEvent; - new(): TransitionEvent; -} - -interface MediaQueryList { - matches: bool; - media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; -} -declare var MediaQueryList: { - prototype: MediaQueryList; - new(): MediaQueryList; -} - -interface DOMError { - name: string; - toString(): string; -} -declare var DOMError: { - prototype: DOMError; - new(): DOMError; -} - -interface SVGFEPointLightElement extends SVGElement { - y: SVGAnimatedNumber; - x: SVGAnimatedNumber; - z: SVGAnimatedNumber; -} -declare var SVGFEPointLightElement: { - prototype: SVGFEPointLightElement; - new(): SVGFEPointLightElement; -} - -interface CSSFontsProperties { - msFontFeatureSettings: string; - fontFeatureSettings: string; -} - -interface CloseEvent extends Event { - wasClean: bool; - reason: string; - code: number; - initCloseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, wasCleanArg: bool, codeArg: number, reasonArg: string): void; -} -declare var CloseEvent: { - prototype: CloseEvent; - new(): CloseEvent; -} - -interface WebSocket extends EventTarget { - protocol: string; - readyState: number; - bufferedAmount: number; - onopen: (ev: Event) => any; - extensions: string; - onmessage: (ev: any) => any; - onclose: (ev: CloseEvent) => any; - onerror: (ev: ErrorEvent) => any; - binaryType: string; - url: string; - close(code?: number, reason?: string): void; - send(data: any): void; - OPEN: number; - CLOSING: number; - CONNECTING: number; - CLOSED: number; -} -declare var WebSocket: { - prototype: WebSocket; - new (url: string): WebSocket; - new (url: string, prototcol: string): WebSocket; - new (url: string, prototcol: string[]): WebSocket; - OPEN: number; - CLOSING: number; - CONNECTING: number; - CLOSED: number; -} - -interface ProgressEvent extends Event { - loaded: number; - lengthComputable: bool; - total: number; - initProgressEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, lengthComputableArg: bool, loadedArg: number, totalArg: number): void; -} -declare var ProgressEvent: { - prototype: ProgressEvent; - new(): ProgressEvent; -} - -interface HTMLCanvasElement { - msToBlob(): Blob; -} - -interface IDBObjectStore { - indexNames: DOMStringList; - name: string; - transaction: IDBTransaction; - keyPath: string; - count(key?: any): IDBRequest; - add(value: any, key?: any): IDBRequest; - clear(): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; - put(value: any, key?: any): IDBRequest; - openCursor(range?: any, direction?: string): IDBRequest; - deleteIndex(indexName: string): void; - index(name: string): IDBIndex; - get(key: any): IDBRequest; - delet(key: any): IDBRequest; -} -declare var IDBObjectStore: { - prototype: IDBObjectStore; - new(): IDBObjectStore; -} - -interface ObjectURLOptions { - oneTimeOnly?: bool; -} - -interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - stdDeviationX: SVGAnimatedNumber; - in1: SVGAnimatedString; - stdDeviationY: SVGAnimatedNumber; - setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; -} -declare var SVGFEGaussianBlurElement: { - prototype: SVGFEGaussianBlurElement; - new(): SVGFEGaussianBlurElement; -} - -interface MSHTMLDocumentExtensions { - onmspointerdown: (ev: any) => any; - onmspointercancel: (ev: any) => any; - onmsgesturedoubletap: (ev: any) => any; - onmsgesturetap: (ev: any) => any; - onmsgestureend: (ev: any) => any; - onmspointerout: (ev: any) => any; - onmsmanipulationstatechanged: (ev: any) => any; - onmsinertiastart: (ev: any) => any; - onmspointerhover: (ev: any) => any; - onmscontentzoom: (ev: any) => any; - onmsgesturehold: (ev: any) => any; - onmspointermove: (ev: any) => any; - onmspointerover: (ev: any) => any; - onmsgesturechange: (ev: any) => any; - onmsgesturestart: (ev: any) => any; - onmspointerup: (ev: any) => any; -} -declare var MSHTMLDocumentExtensions: { - prototype: MSHTMLDocumentExtensions; - new(): MSHTMLDocumentExtensions; -} - -interface MSCSSSelectionBoundaryProperties { - msUserSelect: string; -} - -interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { - y: SVGAnimatedLength; - width: SVGAnimatedLength; - x: SVGAnimatedLength; - height: SVGAnimatedLength; - result: SVGAnimatedString; -} - -interface IDBVersionChangeEvent extends Event { - newVersion: number; - oldVersion: number; -} -declare var IDBVersionChangeEvent: { - prototype: IDBVersionChangeEvent; - new(): IDBVersionChangeEvent; -} - -interface IDBIndex { - unique: bool; - name: string; - keyPath: string; - objectStore: IDBObjectStore; - count(key?: any): IDBRequest; - getKey(key: any): IDBRequest; - openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest; - get(key: any): IDBRequest; - openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; -} -declare var IDBIndex: { - prototype: IDBIndex; - new(): IDBIndex; -} - -interface FileList { - length: number; - item(index: number): File; - [index: number]: File; -} -declare var FileList: { - prototype: FileList; - new(): FileList; -} - -interface IDBCursor { - source: any; - direction: string; - key: any; - primaryKey: any; - advance(count: number): void; - delet(): IDBRequest; - continu(key?: any): void; - update(value: any): IDBRequest; -} -declare var IDBCursor: { - prototype: IDBCursor; - new(): IDBCursor; -} - -interface CSSAnimationsProperties { - animationFillMode: string; - msAnimationDirection: string; - msAnimationDelay: string; - msAnimationFillMode: string; - animationIterationCount: string; - msAnimationPlayState: string; - msAnimationIterationCount: string; - animationDelay: string; - animationTimingFunction: string; - msAnimation: string; - animation: string; - animationDirection: string; - animationDuration: string; - animationName: string; - animationPlayState: string; - msAnimationTimingFunction: string; - msAnimationName: string; - msAnimationDuration: string; -} - -interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - kernelUnitLengthY: SVGAnimatedNumber; - surfaceScale: SVGAnimatedNumber; - specularExponent: SVGAnimatedNumber; - in1: SVGAnimatedString; - kernelUnitLengthX: SVGAnimatedNumber; - specularConstant: SVGAnimatedNumber; -} -declare var SVGFESpecularLightingElement: { - prototype: SVGFESpecularLightingElement; - new(): SVGFESpecularLightingElement; -} - -interface File extends Blob { - lastModifiedDate: any; - name: string; -} -declare var File: { - prototype: File; - new(): File; -} - -interface URL { - revokeObjectURL(url: string): void; - createObjectURL(object: any, options?: ObjectURLOptions): string; -} -declare var URL: URL; - -interface RangeException { - name: string; -} - -interface IDBCursorWithValue extends IDBCursor { - value: any; -} -declare var IDBCursorWithValue: { - prototype: IDBCursorWithValue; - new(): IDBCursorWithValue; -} - -interface HTMLTextAreaElement { - validationMessage: string; - autofocus: bool; - validity: ValidityState; - required: bool; - maxLength: number; - willValidate: bool; - placeholder: string; - checkValidity(): bool; - setCustomValidity(error: string): void; -} - -interface XMLHttpRequestEventTarget extends EventTarget { - onprogress: (ev: ProgressEvent) => any; - onerror: (ev: ErrorEvent) => any; - onload: (ev: any) => any; - ontimeout: (ev: any) => any; - onabort: (ev: any) => any; - onloadstart: (ev: any) => any; - onloadend: (ev: ProgressEvent) => any; -} -declare var XMLHttpRequestEventTarget: { - prototype: XMLHttpRequestEventTarget; - new(): XMLHttpRequestEventTarget; -} - -interface IDBEnvironment { - msIndexedDB: IDBFactory; - indexedDB: IDBFactory; -} - -interface AudioTrackList extends EventTarget { - length: number; - onchange: (ev: any) => any; - onaddtrack: (ev: TrackEvent) => any; - getTrackById(id: string): AudioTrack; - item(index: number): AudioTrack; - [index: number]: AudioTrack; -} -declare var AudioTrackList: { - prototype: AudioTrackList; - new(): AudioTrackList; -} - -interface MSBaseReader extends EventTarget { - onprogress: (ev: ProgressEvent) => any; - readyState: number; - onabort: (ev: any) => any; - onloadend: (ev: ProgressEvent) => any; - onerror: (ev: ErrorEvent) => any; - onload: (ev: any) => any; - onloadstart: (ev: any) => any; - result: any; - abort(): void; - LOADING: number; - EMPTY: number; - DONE: number; -} - -interface History { - state: any; - replaceState(statedata: any, title: string, url?: string): void; - pushState(statedata: any, title: string, url?: string): void; -} - -interface MSProtocol { - protocol: string; -} -declare var MSProtocol: { - prototype: MSProtocol; - new(): MSProtocol; -} - -interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - operator: SVGAnimatedEnumeration; - radiusX: SVGAnimatedNumber; - radiusY: SVGAnimatedNumber; - in1: SVGAnimatedString; - SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - SVG_MORPHOLOGY_OPERATOR_ERODE: number; - SVG_MORPHOLOGY_OPERATOR_DILATE: number; -} -declare var SVGFEMorphologyElement: { - prototype: SVGFEMorphologyElement; - new(): SVGFEMorphologyElement; - SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; - SVG_MORPHOLOGY_OPERATOR_ERODE: number; - SVG_MORPHOLOGY_OPERATOR_DILATE: number; -} - -interface HTMLSelectElement { - validationMessage: string; - autofocus: bool; - validity: ValidityState; - required: bool; - willValidate: bool; - checkValidity(): bool; - setCustomValidity(error: string): void; -} - -interface CSSTransitionsProperties { - transition: string; - transitionDelay: string; - transitionDuration: string; - msTransitionTimingFunction: string; - msTransition: string; - msTransitionDuration: string; - transitionTimingFunction: string; - msTransitionDelay: string; - transitionProperty: string; - msTransitionProperty: string; -} - -interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { -} -declare var SVGFEFuncRElement: { - prototype: SVGFEFuncRElement; - new(): SVGFEFuncRElement; -} - -interface CSSRule { - KEYFRAMES_RULE: number; - KEYFRAME_RULE: number; - VIEWPORT_RULE: number; -} -//declare var CSSRule: { -// KEYFRAMES_RULE: number; -// KEYFRAME_RULE: number; -// VIEWPORT_RULE: number; -//} - -interface WindowTimersExtension { - msSetImmediate(expression: any, ...args: any[]): number; - clearImmediate(handle: number): void; - msClearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; -} - -interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - in2: SVGAnimatedString; - xChannelSelector: SVGAnimatedEnumeration; - yChannelSelector: SVGAnimatedEnumeration; - scale: SVGAnimatedNumber; - in1: SVGAnimatedString; - SVG_CHANNEL_B: number; - SVG_CHANNEL_R: number; - SVG_CHANNEL_G: number; - SVG_CHANNEL_UNKNOWN: number; - SVG_CHANNEL_A: number; -} -declare var SVGFEDisplacementMapElement: { - prototype: SVGFEDisplacementMapElement; - new(): SVGFEDisplacementMapElement; - SVG_CHANNEL_B: number; - SVG_CHANNEL_R: number; - SVG_CHANNEL_G: number; - SVG_CHANNEL_UNKNOWN: number; - SVG_CHANNEL_A: number; -} - -interface MSCSSContentZoomProperties { - msContentZoomLimit: string; - msContentZooming: string; - msContentZoomSnapType: string; - msContentZoomLimitMax: any; - msContentZoomSnapPoints: string; - msContentZoomSnap: string; - msContentZoomLimitMin: any; - msContentZoomChaining: string; -} - -interface AnimationEvent extends Event { - animationName: string; - elapsedTime: number; - initAnimationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, animationNameArg: string, elapsedTimeArg: number): void; -} -declare var AnimationEvent: { - prototype: AnimationEvent; - new(): AnimationEvent; -} - -interface SVGComponentTransferFunctionElement extends SVGElement { - tableValues: SVGAnimatedNumberList; - slope: SVGAnimatedNumber; - type: SVGAnimatedEnumeration; - exponent: SVGAnimatedNumber; - amplitude: SVGAnimatedNumber; - intercept: SVGAnimatedNumber; - offset: SVGAnimatedNumber; - SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; -} -declare var SVGComponentTransferFunctionElement: { - prototype: SVGComponentTransferFunctionElement; - new(): SVGComponentTransferFunctionElement; - SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; - SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; - SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; - SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; - SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; - SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; -} - -interface MSRangeCollection { - length: number; - item(index: number): Range; - [index: number]: Range; -} -declare var MSRangeCollection: { - prototype: MSRangeCollection; - new(): MSRangeCollection; -} - -interface MSHTMLElementExtensions { - onmscontentzoom: (ev: any) => any; - onmsmanipulationstatechanged: (ev: any) => any; -} -declare var MSHTMLElementExtensions: { - prototype: MSHTMLElementExtensions; - new(): MSHTMLElementExtensions; -} - -interface MSCSSPositionedFloatsProperties { - msWrapMargin: any; - msWrapFlow: string; -} - -interface SVGException { - name: string; -} - -interface SVGFEDistantLightElement extends SVGElement { - azimuth: SVGAnimatedNumber; - elevation: SVGAnimatedNumber; -} -declare var SVGFEDistantLightElement: { - prototype: SVGFEDistantLightElement; - new(): SVGFEDistantLightElement; -} - -interface MSCSSRegionProperties { - msFlowFrom: string; - msFlowInto: string; - msWrapThrough: string; -} - -interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { -} -declare var SVGFEFuncBElement: { - prototype: SVGFEFuncBElement; - new(): SVGFEFuncBElement; -} - -interface IDBKeyRange { - upper: any; - upperOpen: bool; - lower: any; - lowerOpen: bool; - bound(lower: any, upper: any, lowerOpen?: bool, upperOpen?: bool): IDBKeyRange; - only(value: any): IDBKeyRange; - lowerBound(bound: any, open?: bool): IDBKeyRange; - upperBound(bound: any, open?: bool): IDBKeyRange; -} -declare var IDBKeyRange: { - prototype: IDBKeyRange; - new(): IDBKeyRange; -} - -interface WindowConsole { - console: Console; -} - -interface SVG1_1Properties { - floodOpacity: string; - floodColor: string; - filter: string; - lightingColor: string; - enableBackground: string; - colorInterpolationFilters: string; -} -declare var SVG1_1Properties: { - prototype: SVG1_1Properties; - new(): SVG1_1Properties; -} - -interface IDBTransaction extends EventTarget { - oncomplete: (ev: Event) => any; - db: IDBDatabase; - mode: string; - error: DOMError; - onerror: (ev: ErrorEvent) => any; - onabort: (ev: any) => any; - abort(): void; - objectStore(name: string): IDBObjectStore; -} -declare var IDBTransaction: { - prototype: IDBTransaction; - new(): IDBTransaction; -} - -interface MSWindowExtensions { - onmspointerdown: (ev: any) => any; - onmspointercancel: (ev: any) => any; - onmsgesturedoubletap: (ev: any) => any; - onmsgestureend: (ev: any) => any; - onmsgesturetap: (ev: any) => any; - onmspointerout: (ev: any) => any; - onmspointerhover: (ev: any) => any; - onmsinertiastart: (ev: any) => any; - onmspointermove: (ev: any) => any; - onmsgesturehold: (ev: any) => any; - onmspointerover: (ev: any) => any; - onmsgesturechange: (ev: any) => any; - onmsgesturestart: (ev: any) => any; - onmspointerup: (ev: any) => any; - msIsStaticHTML(html: string): bool; -} -declare var MSWindowExtensions: { - prototype: MSWindowExtensions; - new(): MSWindowExtensions; -} - -interface AudioTrack { - kind: string; - language: string; - id: string; - label: string; - enabled: bool; -} -declare var AudioTrack: { - prototype: AudioTrack; - new(): AudioTrack; -} - -interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - orderY: SVGAnimatedInteger; - kernelUnitLengthY: SVGAnimatedNumber; - orderX: SVGAnimatedInteger; - preserveAlpha: SVGAnimatedBoolean; - kernelMatrix: SVGAnimatedNumberList; - edgeMode: SVGAnimatedEnumeration; - kernelUnitLengthX: SVGAnimatedNumber; - bias: SVGAnimatedNumber; - targetX: SVGAnimatedInteger; - targetY: SVGAnimatedInteger; - divisor: SVGAnimatedNumber; - in1: SVGAnimatedString; - SVG_EDGEMODE_WRAP: number; - SVG_EDGEMODE_DUPLICATE: number; - SVG_EDGEMODE_UNKNOWN: number; - SVG_EDGEMODE_NONE: number; -} -declare var SVGFEConvolveMatrixElement: { - prototype: SVGFEConvolveMatrixElement; - new(): SVGFEConvolveMatrixElement; - SVG_EDGEMODE_WRAP: number; - SVG_EDGEMODE_DUPLICATE: number; - SVG_EDGEMODE_UNKNOWN: number; - SVG_EDGEMODE_NONE: number; -} - -interface TextTrackCueList { - length: number; - item(index: number): TextTrackCue; - [index: number]: TextTrackCue; - getCueById(id: string): TextTrackCue; -} -declare var TextTrackCueList: { - prototype: TextTrackCueList; - new(): TextTrackCueList; -} - -interface CSSKeyframesRule extends CSSRule { - name: string; - cssRules: CSSRuleList; - findRule(rule: string): CSSKeyframeRule; - deleteRule(rule: string): void; - appendRule(rule: string): void; -} -declare var CSSKeyframesRule: { - prototype: CSSKeyframesRule; - new(): CSSKeyframesRule; -} - -interface MSCSSTouchManipulationProperties { - msScrollSnapPointsY: string; - msOverflowStyle: string; - msScrollLimitXMax: any; - msScrollSnapType: string; - msScrollSnapPointsX: string; - msScrollLimitYMax: any; - msScrollSnapY: string; - msScrollLimitXMin: any; - msScrollLimitYMin: any; - msScrollChaining: string; - msTouchAction: string; - msScrollSnapX: string; - msScrollLimit: string; - msScrollRails: string; - msTouchSelect: string; -} - -interface Window extends WindowAnimationTiming, WindowBase64, IDBEnvironment, WindowConsole { - onpopstate: (ev: PopStateEvent) => any; - applicationCache: ApplicationCache; - matchMedia(mediaQuery: string): MediaQueryList; - msMatchMedia(mediaQuery: string): MediaQueryList; -} - -interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - baseFrequencyX: SVGAnimatedNumber; - numOctaves: SVGAnimatedInteger; - type: SVGAnimatedEnumeration; - baseFrequencyY: SVGAnimatedNumber; - stitchTiles: SVGAnimatedEnumeration; - seed: SVGAnimatedNumber; - SVG_STITCHTYPE_UNKNOWN: number; - SVG_STITCHTYPE_NOSTITCH: number; - SVG_TURBULENCE_TYPE_UNKNOWN: number; - SVG_TURBULENCE_TYPE_TURBULENCE: number; - SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - SVG_STITCHTYPE_STITCH: number; -} -declare var SVGFETurbulenceElement: { - prototype: SVGFETurbulenceElement; - new(): SVGFETurbulenceElement; - SVG_STITCHTYPE_UNKNOWN: number; - SVG_STITCHTYPE_NOSTITCH: number; - SVG_TURBULENCE_TYPE_UNKNOWN: number; - SVG_TURBULENCE_TYPE_TURBULENCE: number; - SVG_TURBULENCE_TYPE_FRACTALNOISE: number; - SVG_STITCHTYPE_STITCH: number; -} - -interface TextTrackList { - length: number; - item(index: number): TextTrack; - [index: number]: TextTrack; -} -declare var TextTrackList: { - prototype: TextTrackList; - new(): TextTrackList; -} - -interface WindowAnimationTiming { - animationStartTime: number; - msAnimationStartTime: number; - msCancelRequestAnimationFrame(handle: number): void; - cancelAnimationFrame(handle: number): void; - requestAnimationFrame(callback: FrameRequestCallback): number; - msRequestAnimationFrame(callback: FrameRequestCallback): number; -} - -interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { -} -declare var SVGFEFuncGElement: { - prototype: SVGFEFuncGElement; - new(): SVGFEFuncGElement; -} - -interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - in1: SVGAnimatedString; - type: SVGAnimatedEnumeration; - values: SVGAnimatedNumberList; - SVG_FECOLORMATRIX_TYPE_SATURATE: number; - SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - SVG_FECOLORMATRIX_TYPE_MATRIX: number; - SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; -} -declare var SVGFEColorMatrixElement: { - prototype: SVGFEColorMatrixElement; - new(): SVGFEColorMatrixElement; - SVG_FECOLORMATRIX_TYPE_SATURATE: number; - SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; - SVG_FECOLORMATRIX_TYPE_MATRIX: number; - SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; - SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; -} - -interface Console { - info(): void; - info(message: any, ...optionalParams: any[]): void; - profile(reportName?: string): bool; - assert(): void; - assert(test: bool): void; - assert(test: bool, message: any, ...optionalParams: any[]): void; - msIsIndependentlyComposed(element: Element): bool; - clear(): bool; - dir(): bool; - dir(value: any, ...optionalParams: any[]): bool; - warn(): void; - warn(message: any, ...optionalParams: any[]): void; - error(): void; - error(message: any, ...optionalParams: any[]): void; - log(): void; - log(message: any, ...optionalParams: any[]): void; - profileEnd(): bool; -} -declare var Console: { - prototype: Console; - new(): Console; -} - -interface SVGFESpotLightElement extends SVGElement { - pointsAtY: SVGAnimatedNumber; - y: SVGAnimatedNumber; - limitingConeAngle: SVGAnimatedNumber; - specularExponent: SVGAnimatedNumber; - x: SVGAnimatedNumber; - pointsAtZ: SVGAnimatedNumber; - z: SVGAnimatedNumber; - pointsAtX: SVGAnimatedNumber; -} -declare var SVGFESpotLightElement: { - prototype: SVGFESpotLightElement; - new(): SVGFESpotLightElement; -} - -interface DocumentVisibility { - msHidden: bool; - msVisibilityState: string; - visibilityState: string; - hidden: bool; -} - -interface WindowBase64 { - btoa(rawString: string): string; - atob(encodedString: string): string; -} - -interface IDBDatabase extends EventTarget { - version: string; - name: string; - objectStoreNames: DOMStringList; - onerror: (ev: ErrorEvent) => any; - onabort: (ev: any) => any; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; - close(): void; - transaction(storeNames: any, mode?: string): IDBTransaction; - deleteObjectStore(name: string): void; -} -declare var IDBDatabase: { - prototype: IDBDatabase; - new(): IDBDatabase; -} - -interface MSProtocolsCollection { -} -declare var MSProtocolsCollection: { - prototype: MSProtocolsCollection; - new(): MSProtocolsCollection; -} - -interface DOMStringList { - length: number; - contains(str: string): bool; - item(index: number): string; - [index: number]: string; -} -declare var DOMStringList: { - prototype: DOMStringList; - new(): DOMStringList; -} - -interface CSSMultiColumnProperties { - breakAfter: string; - columnSpan: string; - columnRule: string; - columnFill: string; - columnRuleStyle: string; - breakBefore: string; - columnCount: any; - breakInside: string; - columnWidth: any; - columns: string; - columnRuleColor: any; - columnGap: any; - columnRuleWidth: any; -} - -interface IDBOpenDBRequest extends IDBRequest { - onupgradeneeded: (ev: IDBVersionChangeEvent) => any; - onblocked: (ev: Event) => any; -} -declare var IDBOpenDBRequest: { - prototype: IDBOpenDBRequest; - new(): IDBOpenDBRequest; -} - -interface HTMLButtonElement { - validationMessage: string; - formTarget: string; - willValidate: bool; - formAction: string; - autofocus: bool; - validity: ValidityState; - formNoValidate: string; - formEnctype: string; - formMethod: string; - checkValidity(): bool; - setCustomValidity(error: string): void; -} - -interface HTMLProgressElement extends HTMLElement { - value: number; - max: number; - position: number; - form: HTMLFormElement; -} -declare var HTMLProgressElement: { - prototype: HTMLProgressElement; - new(): HTMLProgressElement; -} - -interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - dy: SVGAnimatedNumber; - in1: SVGAnimatedString; - dx: SVGAnimatedNumber; -} -declare var SVGFEOffsetElement: { - prototype: SVGFEOffsetElement; - new(): SVGFEOffsetElement; -} - -interface HTMLFormElement { - autocomplete: string; - noValidate: bool; - checkValidity(): bool; -} - -interface MSUnsafeFunctionCallback { - (): any; -} - -interface Document extends DocumentVisibility { -} - -interface MessageEvent extends Event { - ports: any; -} - -interface HTMLScriptElement { - async: bool; -} - -interface HTMLMediaElement extends MSHTMLMediaElementExtensions { - textTracks: TextTrackList; - audioTracks: AudioTrackList; -} - -interface TextTrack extends EventTarget { - language: string; - mode: number; - readyState: string; - activeCues: TextTrackCueList; - cues: TextTrackCueList; - oncuechange: (ev: Event) => any; - kind: string; - onload: (ev: any) => any; - onerror: (ev: ErrorEvent) => any; - label: string; - ERROR: number; - SHOWING: number; - LOADING: number; - LOADED: number; - NONE: number; - HIDDEN: number; - DISABLED: number; -} -declare var TextTrack: { - prototype: TextTrack; - new(): TextTrack; - ERROR: number; - SHOWING: number; - LOADING: number; - LOADED: number; - NONE: number; - HIDDEN: number; - DISABLED: number; -} - -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} - -interface IDBRequest extends EventTarget { - source: any; - onsuccess: (ev: Event) => any; - error: DOMError; - transaction: IDBTransaction; - onerror: (ev: ErrorEvent) => any; - readyState: string; - result: any; -} -declare var IDBRequest: { - prototype: IDBRequest; - new(): IDBRequest; -} - -interface MessagePort extends EventTarget { - onmessage: (ev: any) => any; - close(): void; - postMessage(message: any, ports?: any): void; - start(): void; -} -declare var MessagePort: { - prototype: MessagePort; - new(): MessagePort; -} - -interface FileReader extends MSBaseReader { - error: DOMError; - readAsArrayBuffer(blob: Blob): void; - readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, encoding?: string): void; -} -declare var FileReader: { - prototype: FileReader; - new (): FileReader; -} - -interface Blob { - type: string; - size: number; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; - msClose(): void; -} -declare var Blob: { - prototype: Blob; - new (): Blob; -} - -interface ApplicationCache extends EventTarget { - status: number; - ondownloading: (ev: Event) => any; - onprogress: (ev: ProgressEvent) => any; - onupdateready: (ev: Event) => any; - oncached: (ev: Event) => any; - onobsolete: (ev: Event) => any; - onerror: (ev: ErrorEvent) => any; - onchecking: (ev: Event) => any; - onnoupdate: (ev: Event) => any; - swapCache(): void; - abort(): void; - update(): void; - CHECKING: number; - UNCACHED: number; - UPDATEREADY: number; - DOWNLOADING: number; - IDLE: number; - OBSOLETE: number; -} -declare var ApplicationCache: { - prototype: ApplicationCache; - new(): ApplicationCache; - CHECKING: number; - UNCACHED: number; - UPDATEREADY: number; - DOWNLOADING: number; - IDLE: number; - OBSOLETE: number; -} - -interface MSHTMLVideoElementExtensions { - msIsStereo3D: bool; - msStereo3DPackingMode: string; - onMSVideoOptimalLayoutChanged: (ev: any) => any; - onMSVideoFrameStepCompleted: (ev: any) => any; - msStereo3DRenderMode: string; - msIsLayoutOptimalForPlayback: bool; - msHorizontalMirror: bool; - onMSVideoFormatChanged: (ev: any) => any; - msZoom: bool; - msInsertVideoEffect(activatableClassId: string, effectRequired: bool, config?: any): void; - msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; - msFrameStep(forward: bool): void; -} - -interface FrameRequestCallback { - (time: number): void; -} - -interface CSS3DTransformsProperties { - perspective: string; - msBackfaceVisibility: string; - perspectiveOrigin: string; - transformStyle: string; - backfaceVisibility: string; - msPerspectiveOrigin: string; - msTransformStyle: string; - msPerspective: string; -} - -interface XMLHttpRequest { - withCredentials: bool; -} - -interface PopStateEvent extends Event { - state: any; - initPopStateEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, stateArg: any): void; -} -declare var PopStateEvent: { - prototype: PopStateEvent; - new(): PopStateEvent; -} - -interface CSSKeyframeRule extends CSSRule { - keyText: string; - style: CSSStyleDeclaration; -} -declare var CSSKeyframeRule: { - prototype: CSSKeyframeRule; - new(): CSSKeyframeRule; -} - -interface CSSGridProperties { - msGridRows: string; - msGridColumnSpan: any; - msGridRow: any; - msGridRowSpan: any; - msGridColumns: string; - msGridColumnAlign: string; - msGridRowAlign: string; - msGridColumn: any; -} - -interface MSFileSaver { - msSaveBlob(blob: any, defaultName?: string): bool; - msSaveOrOpenBlob(blob: any, defaultName?: string): bool; -} - -interface MSStream { - type: string; - msDetachStream(): any; - msClose(): void; -} -declare var MSStream: { - prototype: MSStream; - new(): MSStream; -} - -interface MediaError extends MSMediaErrorExtensions { -} - -interface HTMLFieldSetElement { - validationMessage: string; - validity: ValidityState; - willValidate: bool; - checkValidity(): bool; - setCustomValidity(error: string): void; -} - -interface MSBlobBuilder { - append(data: any, endings?: string): void; - getBlob(contentType?: string): Blob; -} -declare var MSBlobBuilder: { - prototype: MSBlobBuilder; - new (): MSBlobBuilder; -} - -interface MSRangeExtensions { - createContextualFragment(fragment: string): DocumentFragment; -} - -interface HTMLElement { - oncuechange: (ev: Event) => any; - spellcheck: bool; - classList: DOMTokenList; - draggable: bool; -} - -interface DataTransfer { - types: DOMStringList; - files: FileList; -} - -interface DOMSettableTokenList extends DOMTokenList { - value: string; -} -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new(): DOMSettableTokenList; -} - -interface IDBFactory { - open(name: string, version?: number): IDBOpenDBRequest; - cmp(first: any, second: any): number; - deleteDatabase(name: string): IDBOpenDBRequest; -} -declare var IDBFactory: { - prototype: IDBFactory; - new(): IDBFactory; -} - -interface Range extends MSRangeExtensions { -} - -interface HTMLObjectElement { - validationMessage: string; - validity: ValidityState; - willValidate: bool; - checkValidity(): bool; - setCustomValidity(error: string): void; -} - -interface MSPointerEvent extends MouseEvent { - width: number; - rotation: number; - pressure: number; - pointerType: number; - isPrimary: bool; - tiltY: number; - height: number; - intermediatePoints: any; - currentPoint: any; - tiltX: number; - hwTimestamp: number; - pointerId: number; - initPointerEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: number, hwTimestampArg: number, isPrimary: bool): void; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - MSPOINTER_TYPE_PEN: number; - MSPOINTER_TYPE_MOUSE: number; - MSPOINTER_TYPE_TOUCH: number; -} -declare var MSPointerEvent: { - prototype: MSPointerEvent; - new(): MSPointerEvent; - MSPOINTER_TYPE_PEN: number; - MSPOINTER_TYPE_MOUSE: number; - MSPOINTER_TYPE_TOUCH: number; -} - -interface CSSTextProperties { - textShadow: string; - msHyphenateLimitLines: any; - msHyphens: string; - msHyphenateLimitChars: string; - msHyphenateLimitZone: any; -} - -interface CSS2DTransformsProperties { - transform: string; - transformOrigin: string; -} - -interface DOMException { - name: string; - INVALID_NODE_TYPE_ERR: number; - DATA_CLONE_ERR: number; - TIMEOUT_ERR: number; -} -//declare var DOMException: { -// INVALID_NODE_TYPE_ERR: number; -// DATA_CLONE_ERR: number; -// TIMEOUT_ERR: number; -//} - -interface MSCSSHighContrastProperties { - msHighContrastAdjust: string; -} - -interface MSManipulationEvent extends UIEvent { - lastState: number; - currentState: number; - initMSManipulationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, lastState: number, currentState: number): void; - MS_MANIPULATION_STATE_STOPPED: number; - MS_MANIPULATION_STATE_ACTIVE: number; - MS_MANIPULATION_STATE_INERTIA: number; -} -declare var MSManipulationEvent: { - prototype: MSManipulationEvent; - new(): MSManipulationEvent; - MS_MANIPULATION_STATE_STOPPED: number; - MS_MANIPULATION_STATE_ACTIVE: number; - MS_MANIPULATION_STATE_INERTIA: number; -} - -interface FormData { - append(name: any, value: any, blobName?: string): void; -} -declare var FormData: { - prototype: FormData; - new (): FormData; -} - -interface MSHTMLImageElementExtensions { - msPlayToPrimary: bool; - msPlayToDisabled: bool; - msPlayToSource: any; -} -declare var MSHTMLImageElementExtensions: { - prototype: MSHTMLImageElementExtensions; - new(): MSHTMLImageElementExtensions; -} - -interface MSHTMLMediaElementExtensions { - msAudioCategory: string; - msRealTime: bool; - msPlayToPrimary: bool; - msPlayToDisabled: bool; - msPlayToSource: any; - msAudioDeviceType: string; - msClearEffects(): void; - msSetMediaProtectionManager(mediaProtectionManager?: any): void; - msInsertAudioEffect(activatableClassId: string, effectRequired: bool, config?: any): void; -} - -interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference { - preserveAspectRatio: SVGAnimatedPreserveAspectRatio; -} -declare var SVGFEImageElement: { - prototype: SVGFEImageElement; - new(): SVGFEImageElement; -} - -interface HTMLDataListElement extends HTMLElement { - options: HTMLCollection; -} -declare var HTMLDataListElement: { - prototype: HTMLDataListElement; - new(): HTMLDataListElement; -} - -interface AbstractWorker extends EventTarget { - onerror: (ev: ErrorEvent) => any; -} - -interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - operator: SVGAnimatedEnumeration; - in2: SVGAnimatedString; - k2: SVGAnimatedNumber; - k1: SVGAnimatedNumber; - k3: SVGAnimatedNumber; - in1: SVGAnimatedString; - k4: SVGAnimatedNumber; - SVG_FECOMPOSITE_OPERATOR_OUT: number; - SVG_FECOMPOSITE_OPERATOR_OVER: number; - SVG_FECOMPOSITE_OPERATOR_XOR: number; - SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - SVG_FECOMPOSITE_OPERATOR_IN: number; - SVG_FECOMPOSITE_OPERATOR_ATOP: number; -} -declare var SVGFECompositeElement: { - prototype: SVGFECompositeElement; - new(): SVGFECompositeElement; - SVG_FECOMPOSITE_OPERATOR_OUT: number; - SVG_FECOMPOSITE_OPERATOR_OVER: number; - SVG_FECOMPOSITE_OPERATOR_XOR: number; - SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; - SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; - SVG_FECOMPOSITE_OPERATOR_IN: number; - SVG_FECOMPOSITE_OPERATOR_ATOP: number; -} - -interface ValidityState { - customError: bool; - valueMissing: bool; - stepMismatch: bool; - rangeUnderflow: bool; - rangeOverflow: bool; - typeMismatch: bool; - patternMismatch: bool; - tooLong: bool; - valid: bool; -} -declare var ValidityState: { - prototype: ValidityState; - new(): ValidityState; -} - -interface HTMLVideoElement extends MSHTMLVideoElementExtensions { -} - -interface HTMLTrackElement extends HTMLElement { - kind: string; - src: string; - srclang: string; - track: TextTrack; - label: string; - defaul: bool; -} -declare var HTMLTrackElement: { - prototype: HTMLTrackElement; - new(): HTMLTrackElement; -} - -interface MSApp { - createFileFromStorageFile(storageFile: any): File; - createBlobFromRandomAccessStream(type: string, seeker: any): Blob; - createStreamFromInputStream(type: string, inputStream: any): MSStream; - terminateApp(exceptionObject: any): void; - createDataPackage(object: any): any; - execUnsafeLocalFunction(unsafeFunction: MSUnsafeFunctionCallback): any; - getHtmlPrintDocumentSource(htmlDoc: any, printTemplate?: string): any; - addPublicLocalApplicationUri(uri: string): void; - createDataPackageFromSelection(): any; -} -declare var MSApp: MSApp; - -interface MSXMLHttpRequestExtensions { - response: any; - onprogress: (ev: ProgressEvent) => any; - onabort: (ev: any) => any; - responseType: string; - onloadend: (ev: ProgressEvent) => any; - upload: XMLHttpRequestEventTarget; - onerror: (ev: ErrorEvent) => any; - onloadstart: (ev: any) => any; -} -declare var MSXMLHttpRequestExtensions: { - prototype: MSXMLHttpRequestExtensions; - new(): MSXMLHttpRequestExtensions; -} - -interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - kernelUnitLengthY: SVGAnimatedNumber; - surfaceScale: SVGAnimatedNumber; - in1: SVGAnimatedString; - kernelUnitLengthX: SVGAnimatedNumber; - diffuseConstant: SVGAnimatedNumber; -} -declare var SVGFEDiffuseLightingElement: { - prototype: SVGFEDiffuseLightingElement; - new(): SVGFEDiffuseLightingElement; -} - -interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { - in1: SVGAnimatedString; -} -declare var SVGFEComponentTransferElement: { - prototype: SVGFEComponentTransferElement; - new(): SVGFEComponentTransferElement; -} - -interface MSCSSMatrix { - m24: number; - m34: number; - a: number; - d: number; - m32: number; - m41: number; - m11: number; - f: number; - e: number; - m23: number; - m14: number; - m33: number; - m22: number; - m21: number; - c: number; - m12: number; - b: number; - m42: number; - m31: number; - m43: number; - m13: number; - m44: number; - multiply(secondMatrix: MSCSSMatrix): MSCSSMatrix; - skewY(angle: number): MSCSSMatrix; - setMatrixValue(value: string): void; - inverse(): MSCSSMatrix; - rotateAxisAngle(x: number, y: number, z: number, angle: number): MSCSSMatrix; - toString(): string; - rotate(angleX: number, angleY?: number, angleZ?: number): MSCSSMatrix; - translate(x: number, y: number, z?: number): MSCSSMatrix; - scale(scaleX: number, scaleY?: number, scaleZ?: number): MSCSSMatrix; - skewX(angle: number): MSCSSMatrix; -} -declare var MSCSSMatrix: { - prototype: MSCSSMatrix; - new (text?: string): MSCSSMatrix; -} - -interface Worker extends AbstractWorker { - onmessage: (ev: any) => any; - postMessage(message: any, ports?: any): void; - terminate(): void; -} -declare var Worker: { - prototype: Worker; - new (stringUrl: string): Worker; -} - -interface HTMLIFrameElement { - sandbox: DOMSettableTokenList; -} - -interface MSMediaErrorExtensions { - msExtendedCode: number; -} - -interface MSNavigatorAbilities { - msProtocols: MSProtocolsCollection; - msMaxTouchPoints: number; - msPointerEnabled: bool; - msManipulationViewsEnabled: bool; -} -declare var MSNavigatorAbilities: { - prototype: MSNavigatorAbilities; - new(): MSNavigatorAbilities; -} - -declare var onpopstate: (ev: PopStateEvent) => any; -declare var applicationCache: ApplicationCache; -declare function matchMedia(mediaQuery: string): MediaQueryList; -declare function msMatchMedia(mediaQuery: string): MediaQueryList; -declare var animationStartTime: number; -declare var msAnimationStartTime: number; -declare function msCancelRequestAnimationFrame(handle: number): void; -declare function cancelAnimationFrame(handle: number): void; -declare function requestAnimationFrame(callback: FrameRequestCallback): number; -declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; -declare function btoa(rawString: string): string; -declare function atob(encodedString: string): string; -declare var msIndexedDB: IDBFactory; -declare var indexedDB: IDBFactory; -declare var console: Console; - - -///////////////////////////// -/// WorkerGlobalScope APIs -///////////////////////////// -// TODO: These are only available in a Web Worker - should be in a seperate lib file -declare function importScripts(...urls: string[]): void; - - -///////////////////////////// -/// Windows Script Host APIS -///////////////////////////// -declare var ActiveXObject: { new (s: string): any; }; - -interface ITextWriter { - Write(s: string): void; - WriteLine(s: string): void; - Close(): void; -} - -declare var WScript : { - Echo(s); - StdErr: ITextWriter; - StdOut: ITextWriter; - Arguments: { length: number; Item(n: number): string; }; - ScriptFullName: string; - Quit(exitCode?: number); -} - diff --git a/_infrastructure/tests/typescript_0.8.2/tsc.js b/_infrastructure/tests/typescript_0.8.2/tsc.js deleted file mode 100644 index 371ce6338..000000000 --- a/_infrastructure/tests/typescript_0.8.2/tsc.js +++ /dev/null @@ -1,25756 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -var TypeScript; -(function (TypeScript) { - function hasFlag(val, flag) { - return (val & flag) != 0; - } - TypeScript.hasFlag = hasFlag; - (function (ErrorRecoverySet) { - ErrorRecoverySet._map = []; - ErrorRecoverySet.None = 0; - ErrorRecoverySet.Comma = 1; - ErrorRecoverySet.SColon = 1 << 1; - ErrorRecoverySet.Asg = 1 << 2; - ErrorRecoverySet.BinOp = 1 << 3; - ErrorRecoverySet.RBrack = 1 << 4; - ErrorRecoverySet.RCurly = 1 << 5; - ErrorRecoverySet.RParen = 1 << 6; - ErrorRecoverySet.Dot = 1 << 7; - ErrorRecoverySet.Colon = 1 << 8; - ErrorRecoverySet.PrimType = 1 << 9; - ErrorRecoverySet.AddOp = 1 << 10; - ErrorRecoverySet.LCurly = 1 << 11; - ErrorRecoverySet.PreOp = 1 << 12; - ErrorRecoverySet.RegExp = 1 << 13; - ErrorRecoverySet.LParen = 1 << 14; - ErrorRecoverySet.LBrack = 1 << 15; - ErrorRecoverySet.Scope = 1 << 16; - ErrorRecoverySet.In = 1 << 17; - ErrorRecoverySet.SCase = 1 << 18; - ErrorRecoverySet.Else = 1 << 19; - ErrorRecoverySet.Catch = 1 << 20; - ErrorRecoverySet.Var = 1 << 21; - ErrorRecoverySet.Stmt = 1 << 22; - ErrorRecoverySet.While = 1 << 23; - ErrorRecoverySet.ID = 1 << 24; - ErrorRecoverySet.Prefix = 1 << 25; - ErrorRecoverySet.Literal = 1 << 26; - ErrorRecoverySet.RLit = 1 << 27; - ErrorRecoverySet.Func = 1 << 28; - ErrorRecoverySet.EOF = 1 << 29; - ErrorRecoverySet.TypeScriptS = 1 << 30; - ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; - ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; - ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; - })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); - var ErrorRecoverySet = TypeScript.ErrorRecoverySet; - (function (AllowedElements) { - AllowedElements._map = []; - AllowedElements.None = 0; - AllowedElements.ModuleDeclarations = 1 << 2; - AllowedElements.ClassDeclarations = 1 << 3; - AllowedElements.InterfaceDeclarations = 1 << 4; - AllowedElements.AmbientDeclarations = 1 << 10; - AllowedElements.Properties = 1 << 11; - AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; - AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; - })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); - var AllowedElements = TypeScript.AllowedElements; - (function (Modifiers) { - Modifiers._map = []; - Modifiers.None = 0; - Modifiers.Private = 1; - Modifiers.Public = 1 << 1; - Modifiers.Readonly = 1 << 2; - Modifiers.Ambient = 1 << 3; - Modifiers.Exported = 1 << 4; - Modifiers.Getter = 1 << 5; - Modifiers.Setter = 1 << 6; - Modifiers.Static = 1 << 7; - })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); - var Modifiers = TypeScript.Modifiers; - (function (ASTFlags) { - ASTFlags._map = []; - ASTFlags.None = 0; - ASTFlags.ExplicitSemicolon = 1; - ASTFlags.AutomaticSemicolon = 1 << 1; - ASTFlags.Writeable = 1 << 2; - ASTFlags.Error = 1 << 3; - ASTFlags.DotLHSPartial = 1 << 4; - ASTFlags.DotLHS = 1 << 5; - ASTFlags.IsStatement = 1 << 6; - ASTFlags.StrictMode = 1 << 7; - ASTFlags.PossibleOptionalParameter = 1 << 8; - ASTFlags.ClassBaseConstructorCall = 1 << 9; - ASTFlags.OptionalName = 1 << 10; - ASTFlags.SkipNextRParen = 1 << 11; - })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); - var ASTFlags = TypeScript.ASTFlags; - (function (DeclFlags) { - DeclFlags._map = []; - DeclFlags.None = 0; - DeclFlags.Exported = 1; - DeclFlags.Private = 1 << 1; - DeclFlags.Public = 1 << 2; - DeclFlags.Ambient = 1 << 3; - DeclFlags.Static = 1 << 4; - DeclFlags.LocalStatic = 1 << 5; - DeclFlags.GetAccessor = 1 << 6; - DeclFlags.SetAccessor = 1 << 7; - })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); - var DeclFlags = TypeScript.DeclFlags; - (function (ModuleFlags) { - ModuleFlags._map = []; - ModuleFlags.None = 0; - ModuleFlags.Exported = 1; - ModuleFlags.Private = 1 << 1; - ModuleFlags.Public = 1 << 2; - ModuleFlags.Ambient = 1 << 3; - ModuleFlags.Static = 1 << 4; - ModuleFlags.LocalStatic = 1 << 5; - ModuleFlags.GetAccessor = 1 << 6; - ModuleFlags.SetAccessor = 1 << 7; - ModuleFlags.IsEnum = 1 << 8; - ModuleFlags.ShouldEmitModuleDecl = 1 << 9; - ModuleFlags.IsWholeFile = 1 << 10; - ModuleFlags.IsDynamic = 1 << 11; - ModuleFlags.MustCaptureThis = 1 << 12; - })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); - var ModuleFlags = TypeScript.ModuleFlags; - (function (SymbolFlags) { - SymbolFlags._map = []; - SymbolFlags.None = 0; - SymbolFlags.Exported = 1; - SymbolFlags.Private = 1 << 1; - SymbolFlags.Public = 1 << 2; - SymbolFlags.Ambient = 1 << 3; - SymbolFlags.Static = 1 << 4; - SymbolFlags.LocalStatic = 1 << 5; - SymbolFlags.GetAccessor = 1 << 6; - SymbolFlags.SetAccessor = 1 << 7; - SymbolFlags.Property = 1 << 8; - SymbolFlags.Readonly = 1 << 9; - SymbolFlags.ModuleMember = 1 << 10; - SymbolFlags.InterfaceMember = 1 << 11; - SymbolFlags.ClassMember = 1 << 12; - SymbolFlags.BuiltIn = 1 << 13; - SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; - SymbolFlags.Constant = 1 << 15; - SymbolFlags.Optional = 1 << 16; - SymbolFlags.RecursivelyReferenced = 1 << 17; - SymbolFlags.Bound = 1 << 18; - SymbolFlags.CompilerGenerated = 1 << 19; - })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); - var SymbolFlags = TypeScript.SymbolFlags; - (function (VarFlags) { - VarFlags._map = []; - VarFlags.None = 0; - VarFlags.Exported = 1; - VarFlags.Private = 1 << 1; - VarFlags.Public = 1 << 2; - VarFlags.Ambient = 1 << 3; - VarFlags.Static = 1 << 4; - VarFlags.LocalStatic = 1 << 5; - VarFlags.GetAccessor = 1 << 6; - VarFlags.SetAccessor = 1 << 7; - VarFlags.AutoInit = 1 << 8; - VarFlags.Property = 1 << 9; - VarFlags.Readonly = 1 << 10; - VarFlags.Class = 1 << 11; - VarFlags.ClassProperty = 1 << 12; - VarFlags.ClassBodyProperty = 1 << 13; - VarFlags.ClassConstructorProperty = 1 << 14; - VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; - VarFlags.Constant = 1 << 16; - VarFlags.MustCaptureThis = 1 << 17; - })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); - var VarFlags = TypeScript.VarFlags; - (function (FncFlags) { - FncFlags._map = []; - FncFlags.None = 0; - FncFlags.Exported = 1; - FncFlags.Private = 1 << 1; - FncFlags.Public = 1 << 2; - FncFlags.Ambient = 1 << 3; - FncFlags.Static = 1 << 4; - FncFlags.LocalStatic = 1 << 5; - FncFlags.GetAccessor = 1 << 6; - FncFlags.SetAccessor = 1 << 7; - FncFlags.Definition = 1 << 8; - FncFlags.Signature = 1 << 9; - FncFlags.Method = 1 << 10; - FncFlags.HasReturnExpression = 1 << 11; - FncFlags.CallMember = 1 << 12; - FncFlags.ConstructMember = 1 << 13; - FncFlags.HasSelfReference = 1 << 14; - FncFlags.IsFatArrowFunction = 1 << 15; - FncFlags.IndexerMember = 1 << 16; - FncFlags.IsFunctionExpression = 1 << 17; - FncFlags.ClassMethod = 1 << 18; - FncFlags.ClassPropertyMethodExported = 1 << 19; - FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; - FncFlags.IsPropertyBound = 1 << 21; - })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); - var FncFlags = TypeScript.FncFlags; - (function (SignatureFlags) { - SignatureFlags._map = []; - SignatureFlags.None = 0; - SignatureFlags.IsIndexer = 1; - SignatureFlags.IsStringIndexer = 1 << 1; - SignatureFlags.IsNumberIndexer = 1 << 2; - })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); - var SignatureFlags = TypeScript.SignatureFlags; - function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { - return fncOrVarOrSymbolOrModuleFlags; - } - TypeScript.ToDeclFlags = ToDeclFlags; - (function (TypeFlags) { - TypeFlags._map = []; - TypeFlags.None = 0; - TypeFlags.HasImplementation = 1; - TypeFlags.HasSelfReference = 1 << 1; - TypeFlags.MergeResult = 1 << 2; - TypeFlags.IsEnum = 1 << 3; - TypeFlags.BuildingName = 1 << 4; - TypeFlags.HasBaseType = 1 << 5; - TypeFlags.HasBaseTypeOfObject = 1 << 6; - TypeFlags.IsClass = 1 << 7; - })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); - var TypeFlags = TypeScript.TypeFlags; - (function (TypeRelationshipFlags) { - TypeRelationshipFlags._map = []; - TypeRelationshipFlags.SuccessfulComparison = 0; - TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; - TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; - TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; - TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; - TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; - TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; - TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; - })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); - var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; - (function (CodeGenTarget) { - CodeGenTarget._map = []; - CodeGenTarget.ES3 = 0; - CodeGenTarget.ES5 = 1; - })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); - var CodeGenTarget = TypeScript.CodeGenTarget; - (function (ModuleGenTarget) { - ModuleGenTarget._map = []; - ModuleGenTarget.Synchronous = 0; - ModuleGenTarget.Asynchronous = 1; - ModuleGenTarget.Local = 1 << 1; - })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); - var ModuleGenTarget = TypeScript.ModuleGenTarget; - TypeScript.codeGenTarget = CodeGenTarget.ES3; - TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; - TypeScript.optimizeModuleCodeGen = true; - function flagsToString(e, flags) { - var builder = ""; - for(var i = 1; i < (1 << 31); i = i << 1) { - if((flags & i) != 0) { - for(var k in e) { - if(e[k] == i) { - if(builder.length > 0) { - builder += "|"; - } - builder += k; - break; - } - } - } - } - return builder; - } - TypeScript.flagsToString = flagsToString; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (NodeType) { - NodeType._map = []; - NodeType._map[0] = "None"; - NodeType.None = 0; - NodeType._map[1] = "Empty"; - NodeType.Empty = 1; - NodeType._map[2] = "EmptyExpr"; - NodeType.EmptyExpr = 2; - NodeType._map[3] = "True"; - NodeType.True = 3; - NodeType._map[4] = "False"; - NodeType.False = 4; - NodeType._map[5] = "This"; - NodeType.This = 5; - NodeType._map[6] = "Super"; - NodeType.Super = 6; - NodeType._map[7] = "QString"; - NodeType.QString = 7; - NodeType._map[8] = "Regex"; - NodeType.Regex = 8; - NodeType._map[9] = "Null"; - NodeType.Null = 9; - NodeType._map[10] = "ArrayLit"; - NodeType.ArrayLit = 10; - NodeType._map[11] = "ObjectLit"; - NodeType.ObjectLit = 11; - NodeType._map[12] = "Void"; - NodeType.Void = 12; - NodeType._map[13] = "Comma"; - NodeType.Comma = 13; - NodeType._map[14] = "Pos"; - NodeType.Pos = 14; - NodeType._map[15] = "Neg"; - NodeType.Neg = 15; - NodeType._map[16] = "Delete"; - NodeType.Delete = 16; - NodeType._map[17] = "Await"; - NodeType.Await = 17; - NodeType._map[18] = "In"; - NodeType.In = 18; - NodeType._map[19] = "Dot"; - NodeType.Dot = 19; - NodeType._map[20] = "From"; - NodeType.From = 20; - NodeType._map[21] = "Is"; - NodeType.Is = 21; - NodeType._map[22] = "InstOf"; - NodeType.InstOf = 22; - NodeType._map[23] = "Typeof"; - NodeType.Typeof = 23; - NodeType._map[24] = "NumberLit"; - NodeType.NumberLit = 24; - NodeType._map[25] = "Name"; - NodeType.Name = 25; - NodeType._map[26] = "TypeRef"; - NodeType.TypeRef = 26; - NodeType._map[27] = "Index"; - NodeType.Index = 27; - NodeType._map[28] = "Call"; - NodeType.Call = 28; - NodeType._map[29] = "New"; - NodeType.New = 29; - NodeType._map[30] = "Asg"; - NodeType.Asg = 30; - NodeType._map[31] = "AsgAdd"; - NodeType.AsgAdd = 31; - NodeType._map[32] = "AsgSub"; - NodeType.AsgSub = 32; - NodeType._map[33] = "AsgDiv"; - NodeType.AsgDiv = 33; - NodeType._map[34] = "AsgMul"; - NodeType.AsgMul = 34; - NodeType._map[35] = "AsgMod"; - NodeType.AsgMod = 35; - NodeType._map[36] = "AsgAnd"; - NodeType.AsgAnd = 36; - NodeType._map[37] = "AsgXor"; - NodeType.AsgXor = 37; - NodeType._map[38] = "AsgOr"; - NodeType.AsgOr = 38; - NodeType._map[39] = "AsgLsh"; - NodeType.AsgLsh = 39; - NodeType._map[40] = "AsgRsh"; - NodeType.AsgRsh = 40; - NodeType._map[41] = "AsgRs2"; - NodeType.AsgRs2 = 41; - NodeType._map[42] = "ConditionalExpression"; - NodeType.ConditionalExpression = 42; - NodeType._map[43] = "LogOr"; - NodeType.LogOr = 43; - NodeType._map[44] = "LogAnd"; - NodeType.LogAnd = 44; - NodeType._map[45] = "Or"; - NodeType.Or = 45; - NodeType._map[46] = "Xor"; - NodeType.Xor = 46; - NodeType._map[47] = "And"; - NodeType.And = 47; - NodeType._map[48] = "Eq"; - NodeType.Eq = 48; - NodeType._map[49] = "Ne"; - NodeType.Ne = 49; - NodeType._map[50] = "Eqv"; - NodeType.Eqv = 50; - NodeType._map[51] = "NEqv"; - NodeType.NEqv = 51; - NodeType._map[52] = "Lt"; - NodeType.Lt = 52; - NodeType._map[53] = "Le"; - NodeType.Le = 53; - NodeType._map[54] = "Gt"; - NodeType.Gt = 54; - NodeType._map[55] = "Ge"; - NodeType.Ge = 55; - NodeType._map[56] = "Add"; - NodeType.Add = 56; - NodeType._map[57] = "Sub"; - NodeType.Sub = 57; - NodeType._map[58] = "Mul"; - NodeType.Mul = 58; - NodeType._map[59] = "Div"; - NodeType.Div = 59; - NodeType._map[60] = "Mod"; - NodeType.Mod = 60; - NodeType._map[61] = "Lsh"; - NodeType.Lsh = 61; - NodeType._map[62] = "Rsh"; - NodeType.Rsh = 62; - NodeType._map[63] = "Rs2"; - NodeType.Rs2 = 63; - NodeType._map[64] = "Not"; - NodeType.Not = 64; - NodeType._map[65] = "LogNot"; - NodeType.LogNot = 65; - NodeType._map[66] = "IncPre"; - NodeType.IncPre = 66; - NodeType._map[67] = "DecPre"; - NodeType.DecPre = 67; - NodeType._map[68] = "IncPost"; - NodeType.IncPost = 68; - NodeType._map[69] = "DecPost"; - NodeType.DecPost = 69; - NodeType._map[70] = "TypeAssertion"; - NodeType.TypeAssertion = 70; - NodeType._map[71] = "FuncDecl"; - NodeType.FuncDecl = 71; - NodeType._map[72] = "Member"; - NodeType.Member = 72; - NodeType._map[73] = "VarDecl"; - NodeType.VarDecl = 73; - NodeType._map[74] = "ArgDecl"; - NodeType.ArgDecl = 74; - NodeType._map[75] = "Return"; - NodeType.Return = 75; - NodeType._map[76] = "Break"; - NodeType.Break = 76; - NodeType._map[77] = "Continue"; - NodeType.Continue = 77; - NodeType._map[78] = "Throw"; - NodeType.Throw = 78; - NodeType._map[79] = "For"; - NodeType.For = 79; - NodeType._map[80] = "ForIn"; - NodeType.ForIn = 80; - NodeType._map[81] = "If"; - NodeType.If = 81; - NodeType._map[82] = "While"; - NodeType.While = 82; - NodeType._map[83] = "DoWhile"; - NodeType.DoWhile = 83; - NodeType._map[84] = "Block"; - NodeType.Block = 84; - NodeType._map[85] = "Case"; - NodeType.Case = 85; - NodeType._map[86] = "Switch"; - NodeType.Switch = 86; - NodeType._map[87] = "Try"; - NodeType.Try = 87; - NodeType._map[88] = "TryCatch"; - NodeType.TryCatch = 88; - NodeType._map[89] = "TryFinally"; - NodeType.TryFinally = 89; - NodeType._map[90] = "Finally"; - NodeType.Finally = 90; - NodeType._map[91] = "Catch"; - NodeType.Catch = 91; - NodeType._map[92] = "List"; - NodeType.List = 92; - NodeType._map[93] = "Script"; - NodeType.Script = 93; - NodeType._map[94] = "ClassDeclaration"; - NodeType.ClassDeclaration = 94; - NodeType._map[95] = "InterfaceDeclaration"; - NodeType.InterfaceDeclaration = 95; - NodeType._map[96] = "ModuleDeclaration"; - NodeType.ModuleDeclaration = 96; - NodeType._map[97] = "ImportDeclaration"; - NodeType.ImportDeclaration = 97; - NodeType._map[98] = "With"; - NodeType.With = 98; - NodeType._map[99] = "Label"; - NodeType.Label = 99; - NodeType._map[100] = "LabeledStatement"; - NodeType.LabeledStatement = 100; - NodeType._map[101] = "EBStart"; - NodeType.EBStart = 101; - NodeType._map[102] = "GotoEB"; - NodeType.GotoEB = 102; - NodeType._map[103] = "EndCode"; - NodeType.EndCode = 103; - NodeType._map[104] = "Error"; - NodeType.Error = 104; - NodeType._map[105] = "Comment"; - NodeType.Comment = 105; - NodeType._map[106] = "Debugger"; - NodeType.Debugger = 106; - NodeType.GeneralNode = NodeType.FuncDecl; - NodeType.LastAsg = NodeType.AsgRs2; - })(TypeScript.NodeType || (TypeScript.NodeType = {})); - var NodeType = TypeScript.NodeType; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var BlockIntrinsics = (function () { - function BlockIntrinsics() { - this.prototype = undefined; - this.toString = undefined; - this.toLocaleString = undefined; - this.valueOf = undefined; - this.hasOwnProperty = undefined; - this.propertyIsEnumerable = undefined; - this.isPrototypeOf = undefined; - this["constructor"] = undefined; - } - return BlockIntrinsics; - })(); - TypeScript.BlockIntrinsics = BlockIntrinsics; - var StringHashTable = (function () { - function StringHashTable() { - this.itemCount = 0; - this.table = (new BlockIntrinsics()); - } - StringHashTable.prototype.getAllKeys = function () { - var result = []; - for(var k in this.table) { - if(this.table[k] != undefined) { - result[result.length] = k; - } - } - return result; - }; - StringHashTable.prototype.add = function (key, data) { - if(this.table[key] != undefined) { - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.table[key] != undefined) { - this.table[key] = data; - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.map = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - fn(k, this.table[k], context); - } - } - }; - StringHashTable.prototype.every = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(!fn(k, this.table[k], context)) { - return false; - } - } - } - return true; - }; - StringHashTable.prototype.some = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(fn(k, this.table[k], context)) { - return true; - } - } - } - return false; - }; - StringHashTable.prototype.count = function () { - return this.itemCount; - }; - StringHashTable.prototype.lookup = function (key) { - var data = this.table[key]; - if(data != undefined) { - return data; - } else { - return (null); - } - }; - return StringHashTable; - })(); - TypeScript.StringHashTable = StringHashTable; - var DualStringHashTable = (function () { - function DualStringHashTable(primaryTable, secondaryTable) { - this.primaryTable = primaryTable; - this.secondaryTable = secondaryTable; - this.insertPrimary = true; - } - DualStringHashTable.prototype.getAllKeys = function () { - return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); - }; - DualStringHashTable.prototype.add = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.add(key, data); - } else { - return this.secondaryTable.add(key, data); - } - }; - DualStringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.addOrUpdate(key, data); - } else { - return this.secondaryTable.addOrUpdate(key, data); - } - }; - DualStringHashTable.prototype.map = function (fn, context) { - this.primaryTable.map(fn, context); - this.secondaryTable.map(fn, context); - }; - DualStringHashTable.prototype.every = function (fn, context) { - return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); - }; - DualStringHashTable.prototype.some = function (fn, context) { - return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); - }; - DualStringHashTable.prototype.count = function () { - return this.primaryTable.count() + this.secondaryTable.count(); - }; - DualStringHashTable.prototype.lookup = function (key) { - var data = this.primaryTable.lookup(key); - if(data != undefined) { - return data; - } else { - return this.secondaryTable.lookup(key); - } - }; - return DualStringHashTable; - })(); - TypeScript.DualStringHashTable = DualStringHashTable; - function numberHashFn(key) { - var c2 = 668265261; - key = (key ^ 61) ^ (key >>> 16); - key = key + (key << 3); - key = key ^ (key >>> 4); - key = key * c2; - key = key ^ (key >>> 15); - return key; - } - TypeScript.numberHashFn = numberHashFn; - function combineHashes(key1, key2) { - return key2 ^ ((key1 >> 5) + key1); - } - TypeScript.combineHashes = combineHashes; - var HashEntry = (function () { - function HashEntry(key, data) { - this.key = key; - this.data = data; - } - return HashEntry; - })(); - TypeScript.HashEntry = HashEntry; - var HashTable = (function () { - function HashTable(size, hashFn, equalsFn) { - this.size = size; - this.hashFn = hashFn; - this.equalsFn = equalsFn; - this.itemCount = 0; - this.table = new Array(); - for(var i = 0; i < this.size; i++) { - this.table[i] = null; - } - } - HashTable.prototype.add = function (key, data) { - var current; - var entry = new HashEntry(key, data); - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return false; - } - } - entry.next = this.table[val]; - this.table[val] = entry; - this.itemCount++; - return true; - }; - HashTable.prototype.remove = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - var result = null; - var prevEntry = null; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - result = current.data; - this.itemCount--; - if(prevEntry) { - prevEntry.next = current.next; - } else { - this.table[val] = current.next; - } - break; - } - prevEntry = current; - } - return result; - }; - HashTable.prototype.count = function () { - return this.itemCount; - }; - HashTable.prototype.lookup = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return (current.data); - } - } - return (null); - }; - return HashTable; - })(); - TypeScript.HashTable = HashTable; - var SimpleHashTable = (function () { - function SimpleHashTable() { - this.keys = []; - this.values = []; - } - SimpleHashTable.prototype.lookup = function (key, findValue) { - var searchArray = this.keys; - if(findValue) { - searchArray = this.values; - } - for(var i = 0; i < searchArray.length; i++) { - if(searchArray[i] == key) { - return { - key: this.keys[i], - data: this.values[i] - }; - } - } - return null; - }; - SimpleHashTable.prototype.add = function (key, data) { - var lookupData = this.lookup(key); - if(lookupData) { - return false; - } - this.keys[this.keys.length] = key; - this.values[this.values.length] = data; - return true; - }; - return SimpleHashTable; - })(); - TypeScript.SimpleHashTable = SimpleHashTable; -})(TypeScript || (TypeScript = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -var TypeScript; -(function (TypeScript) { - var ASTSpan = (function () { - function ASTSpan() { - this.minChar = -1; - this.limChar = -1; - } - return ASTSpan; - })(); - TypeScript.ASTSpan = ASTSpan; - var AST = (function (_super) { - __extends(AST, _super); - function AST(nodeType) { - _super.call(this); - this.nodeType = nodeType; - this.type = null; - this.flags = TypeScript.ASTFlags.Writeable; - this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.preComments = null; - this.postComments = null; - this.docComments = null; - this.isParenthesized = false; - } - AST.prototype.isExpression = function () { - return false; - }; - AST.prototype.isStatementOrExpression = function () { - return false; - }; - AST.prototype.isCompoundStatement = function () { - return false; - }; - AST.prototype.isLeaf = function () { - return this.isStatementOrExpression() && (!this.isCompoundStatement()); - }; - AST.prototype.isDeclaration = function () { - return false; - }; - AST.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: { - this.type = typeFlow.anyType; - break; - - } - case TypeScript.NodeType.This: { - return typeFlow.typeCheckThis(this); - - } - case TypeScript.NodeType.Null: { - this.type = typeFlow.nullType; - break; - - } - case TypeScript.NodeType.False: - case TypeScript.NodeType.True: { - this.type = typeFlow.booleanType; - break; - - } - case TypeScript.NodeType.Super: { - return typeFlow.typeCheckSuper(this); - - } - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Empty: - case TypeScript.NodeType.Void: { - this.type = typeFlow.voidType; - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - return this; - }; - AST.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - switch(this.nodeType) { - case TypeScript.NodeType.This: { - emitter.recordSourceMappingStart(this); - if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - emitter.writeToOutput("_this"); - } else { - emitter.writeToOutput("this"); - } - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.Null: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("null"); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.False: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("false"); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.True: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("true"); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.Super: { - emitter.recordSourceMappingStart(this); - emitter.emitSuperReference(); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: { - break; - - } - case TypeScript.NodeType.Empty: { - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.Void: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("void "); - emitter.recordSourceMappingEnd(this); - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - emitter.emitParensAndCommentsInPlace(this, false); - }; - AST.prototype.print = function (context) { - context.startLine(); - var lineCol = { - line: -1, - col: -1 - }; - var limLineCol = { - line: -1, - col: -1 - }; - if(context.parser !== null) { - context.parser.getSourceLineCol(lineCol, this.minChar); - context.parser.getSourceLineCol(limLineCol, this.limChar); - context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); - } - var lab = this.printLabel(); - if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { - lab += " (Error)"; - } - context.writeLine(lab); - }; - AST.prototype.printLabel = function () { - if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { - return TypeScript.nodeTypeTable[this.nodeType]; - } else { - return (TypeScript.NodeType)._map[this.nodeType]; - } - }; - AST.prototype.addToControlFlow = function (context) { - context.walker.options.goChildren = false; - context.addContent(this); - }; - AST.prototype.netFreeUses = function (container, freeUses) { - }; - AST.prototype.treeViewLabel = function () { - return (TypeScript.NodeType)._map[this.nodeType]; - }; - AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { - if(!name) { - return ""; - } - var resolved = ""; - var start = 0; - var i = 0; - while(i <= name.length - 6) { - if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { - var charCode = parseInt(name.substr(i + 2, 4), 16); - resolved += name.substr(start, i - start); - resolved += String.fromCharCode(charCode); - i += 6; - start = i; - continue; - } - i++; - } - resolved += name.substring(start); - return resolved; - } - AST.prototype.getDocComments = function () { - if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { - return []; - } - if(!this.docComments) { - var preCommentsLength = this.preComments.length; - var docComments = []; - for(var i = preCommentsLength - 1; i >= 0; i--) { - if(this.preComments[i].isDocComment()) { - var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; - if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { - docComments.push(this.preComments[i]); - continue; - } - } - break; - } - this.docComments = docComments.reverse(); - } - return this.docComments; - }; - return AST; - })(ASTSpan); - TypeScript.AST = AST; - var IncompleteAST = (function (_super) { - __extends(IncompleteAST, _super); - function IncompleteAST(min, lim) { - _super.call(this, TypeScript.NodeType.Error); - this.minChar = min; - this.limChar = lim; - } - return IncompleteAST; - })(AST); - TypeScript.IncompleteAST = IncompleteAST; - var ASTList = (function (_super) { - __extends(ASTList, _super); - function ASTList() { - _super.call(this, TypeScript.NodeType.List); - this.enclosingScope = null; - this.members = new Array(); - } - ASTList.prototype.addToControlFlow = function (context) { - var len = this.members.length; - for(var i = 0; i < len; i++) { - if(context.noContinuation) { - context.addUnreachable(this.members[i]); - break; - } else { - this.members[i] = context.walk(this.members[i], this); - } - } - context.walker.options.goChildren = false; - }; - ASTList.prototype.append = function (ast) { - this.members[this.members.length] = ast; - return this; - }; - ASTList.prototype.appendAll = function (ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - for(var i = 0, len = list.members.length; i < len; i++) { - this.append(list.members[i]); - } - } else { - this.append(ast); - } - return this; - }; - ASTList.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); - emitter.recordSourceMappingEnd(this); - }; - ASTList.prototype.typeCheck = function (typeFlow) { - var len = this.members.length; - typeFlow.nestingLevel++; - for(var i = 0; i < len; i++) { - if(this.members[i]) { - this.members[i] = this.members[i].typeCheck(typeFlow); - } - } - typeFlow.nestingLevel--; - return this; - }; - return ASTList; - })(AST); - TypeScript.ASTList = ASTList; - var Identifier = (function (_super) { - __extends(Identifier, _super); - function Identifier(actualText, hasEscapeSequence) { - _super.call(this, TypeScript.NodeType.Name); - this.actualText = actualText; - this.hasEscapeSequence = hasEscapeSequence; - this.sym = null; - this.cloId = -1; - this.setText(actualText, hasEscapeSequence); - } - Identifier.prototype.setText = function (actualText, hasEscapeSequence) { - this.actualText = actualText; - if(hasEscapeSequence) { - this.text = AST.getResolvedIdentifierName(actualText); - } else { - this.text = actualText; - } - }; - Identifier.prototype.isMissing = function () { - return false; - }; - Identifier.prototype.isLeaf = function () { - return true; - }; - Identifier.prototype.treeViewLabel = function () { - return "id: " + this.actualText; - }; - Identifier.prototype.printLabel = function () { - if(this.actualText) { - return "id: " + this.actualText; - } else { - return "name node"; - } - }; - Identifier.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckName(this); - }; - Identifier.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptName(this, true); - }; - Identifier.fromToken = function fromToken(token) { - return new Identifier(token.getText(), (token).hasEscapeSequence); - } - return Identifier; - })(AST); - TypeScript.Identifier = Identifier; - var MissingIdentifier = (function (_super) { - __extends(MissingIdentifier, _super); - function MissingIdentifier() { - _super.call(this, "__missing"); - } - MissingIdentifier.prototype.isMissing = function () { - return true; - }; - MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { - }; - return MissingIdentifier; - })(Identifier); - TypeScript.MissingIdentifier = MissingIdentifier; - var Label = (function (_super) { - __extends(Label, _super); - function Label(id) { - _super.call(this, TypeScript.NodeType.Label); - this.id = id; - } - Label.prototype.printLabel = function () { - return this.id.actualText + ":"; - }; - Label.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - Label.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingStart(this.id); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this.id); - emitter.writeLineToOutput(":"); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Label; - })(AST); - TypeScript.Label = Label; - var Expression = (function (_super) { - __extends(Expression, _super); - function Expression(nodeType) { - _super.call(this, nodeType); - } - Expression.prototype.isExpression = function () { - return true; - }; - Expression.prototype.isStatementOrExpression = function () { - return true; - }; - return Expression; - })(AST); - TypeScript.Expression = Expression; - var UnaryExpression = (function (_super) { - __extends(UnaryExpression, _super); - function UnaryExpression(nodeType, operand) { - _super.call(this, nodeType); - this.operand = operand; - this.targetType = null; - this.castTerm = null; - } - UnaryExpression.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - if(this.nodeType == TypeScript.NodeType.Throw) { - context.returnStmt(); - } - }; - UnaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Not: { - return typeFlow.typeCheckBitNot(this); - - } - case TypeScript.NodeType.LogNot: { - return typeFlow.typeCheckLogNot(this); - - } - case TypeScript.NodeType.Pos: - case TypeScript.NodeType.Neg: { - return typeFlow.typeCheckUnaryNumberOperator(this); - - } - case TypeScript.NodeType.IncPost: - case TypeScript.NodeType.IncPre: - case TypeScript.NodeType.DecPost: - case TypeScript.NodeType.DecPre: { - return typeFlow.typeCheckIncOrDec(this); - - } - case TypeScript.NodeType.ArrayLit: { - typeFlow.typeCheckArrayLit(this); - return this; - - } - case TypeScript.NodeType.ObjectLit: { - typeFlow.typeCheckObjectLit(this); - return this; - - } - case TypeScript.NodeType.Throw: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.voidType; - return this; - - } - case TypeScript.NodeType.Typeof: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.stringType; - return this; - - } - case TypeScript.NodeType.Delete: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.booleanType; - break; - - } - case TypeScript.NodeType.TypeAssertion: { - this.castTerm = typeFlow.typeCheck(this.castTerm); - var applyTargetType = !this.operand.isParenthesized; - var targetType = applyTargetType ? this.castTerm.type : null; - typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); - typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); - this.type = this.castTerm.type; - return this; - - } - case TypeScript.NodeType.Void: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.checker.undefinedType; - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - return this; - }; - UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - switch(this.nodeType) { - case TypeScript.NodeType.IncPost: { - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - emitter.writeToOutput("++"); - break; - - } - case TypeScript.NodeType.LogNot: { - emitter.writeToOutput("!"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); - break; - - } - case TypeScript.NodeType.DecPost: { - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - emitter.writeToOutput("--"); - break; - - } - case TypeScript.NodeType.ObjectLit: { - emitter.emitObjectLiteral(this.operand); - break; - - } - case TypeScript.NodeType.ArrayLit: { - emitter.emitArrayLiteral(this.operand); - break; - - } - case TypeScript.NodeType.Not: { - emitter.writeToOutput("~"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.Neg: { - emitter.writeToOutput("-"); - if(this.operand.nodeType == TypeScript.NodeType.Neg) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); - break; - - } - case TypeScript.NodeType.Pos: { - emitter.writeToOutput("+"); - if(this.operand.nodeType == TypeScript.NodeType.Pos) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); - break; - - } - case TypeScript.NodeType.IncPre: { - emitter.writeToOutput("++"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - break; - - } - case TypeScript.NodeType.DecPre: { - emitter.writeToOutput("--"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - break; - - } - case TypeScript.NodeType.Throw: { - emitter.writeToOutput("throw "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - emitter.writeToOutput(";"); - break; - - } - case TypeScript.NodeType.Typeof: { - emitter.writeToOutput("typeof "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.Delete: { - emitter.writeToOutput("delete "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.Void: { - emitter.writeToOutput("void "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.TypeAssertion: { - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return UnaryExpression; - })(Expression); - TypeScript.UnaryExpression = UnaryExpression; - var CallExpression = (function (_super) { - __extends(CallExpression, _super); - function CallExpression(nodeType, target, arguments) { - _super.call(this, nodeType); - this.target = target; - this.arguments = arguments; - this.signature = null; - this.minChar = this.target.minChar; - } - CallExpression.prototype.typeCheck = function (typeFlow) { - if(this.nodeType == TypeScript.NodeType.New) { - return typeFlow.typeCheckNew(this); - } else { - return typeFlow.typeCheckCall(this); - } - }; - CallExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.New) { - emitter.emitNew(this.target, this.arguments); - } else { - emitter.emitCall(this, this.target, this.arguments); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return CallExpression; - })(Expression); - TypeScript.CallExpression = CallExpression; - var BinaryExpression = (function (_super) { - __extends(BinaryExpression, _super); - function BinaryExpression(nodeType, operand1, operand2) { - _super.call(this, nodeType); - this.operand1 = operand1; - this.operand2 = operand2; - } - BinaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: { - return typeFlow.typeCheckDotOperator(this); - - } - case TypeScript.NodeType.Asg: { - return typeFlow.typeCheckAsgOperator(this); - - } - case TypeScript.NodeType.Add: - case TypeScript.NodeType.Sub: - case TypeScript.NodeType.Mul: - case TypeScript.NodeType.Div: - case TypeScript.NodeType.Mod: - case TypeScript.NodeType.Or: - case TypeScript.NodeType.And: { - return typeFlow.typeCheckArithmeticOperator(this, false); - - } - case TypeScript.NodeType.Xor: { - return typeFlow.typeCheckBitwiseOperator(this, false); - - } - case TypeScript.NodeType.Ne: - case TypeScript.NodeType.Eq: { - var text; - if(typeFlow.checker.styleSettings.eqeqeq) { - text = TypeScript.nodeTypeTable[this.nodeType]; - typeFlow.checker.errorReporter.styleError(this, "use of " + text); - } else { - if(typeFlow.checker.styleSettings.eqnull) { - text = TypeScript.nodeTypeTable[this.nodeType]; - if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { - typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); - } - } - } - - } - case TypeScript.NodeType.Eqv: - case TypeScript.NodeType.NEqv: - case TypeScript.NodeType.Lt: - case TypeScript.NodeType.Le: - case TypeScript.NodeType.Ge: - case TypeScript.NodeType.Gt: { - return typeFlow.typeCheckBooleanOperator(this); - - } - case TypeScript.NodeType.Index: { - return typeFlow.typeCheckIndex(this); - - } - case TypeScript.NodeType.Member: { - this.type = typeFlow.voidType; - return this; - - } - case TypeScript.NodeType.LogOr: { - return typeFlow.typeCheckLogOr(this); - - } - case TypeScript.NodeType.LogAnd: { - return typeFlow.typeCheckLogAnd(this); - - } - case TypeScript.NodeType.AsgAdd: - case TypeScript.NodeType.AsgSub: - case TypeScript.NodeType.AsgMul: - case TypeScript.NodeType.AsgDiv: - case TypeScript.NodeType.AsgMod: - case TypeScript.NodeType.AsgOr: - case TypeScript.NodeType.AsgAnd: { - return typeFlow.typeCheckArithmeticOperator(this, true); - - } - case TypeScript.NodeType.AsgXor: { - return typeFlow.typeCheckBitwiseOperator(this, true); - - } - case TypeScript.NodeType.Lsh: - case TypeScript.NodeType.Rsh: - case TypeScript.NodeType.Rs2: { - return typeFlow.typeCheckShift(this, false); - - } - case TypeScript.NodeType.AsgLsh: - case TypeScript.NodeType.AsgRsh: - case TypeScript.NodeType.AsgRs2: { - return typeFlow.typeCheckShift(this, true); - - } - case TypeScript.NodeType.Comma: { - return typeFlow.typeCheckCommaOperator(this); - - } - case TypeScript.NodeType.InstOf: { - return typeFlow.typeCheckInstOf(this); - - } - case TypeScript.NodeType.In: { - return typeFlow.typeCheckInOperator(this); - - } - case TypeScript.NodeType.From: { - typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - return this; - }; - BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(binTokenId != undefined) { - emitter.emitJavascript(this.operand1, binTokenId, false); - if(TypeScript.tokenTable[binTokenId].text == "instanceof") { - emitter.writeToOutput(" instanceof "); - } else { - if(TypeScript.tokenTable[binTokenId].text == "in") { - emitter.writeToOutput(" in "); - } else { - emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); - } - } - emitter.emitJavascript(this.operand2, binTokenId, false); - } else { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: { - if(!emitter.tryEmitConstant(this)) { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); - emitter.writeToOutput("."); - emitter.emitJavascriptName(this.operand2, false); - } - break; - - } - case TypeScript.NodeType.Index: { - emitter.emitIndex(this.operand1, this.operand2); - break; - - } - case TypeScript.NodeType.Member: { - if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { - var funcDecl = this.operand2; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - emitter.writeToOutput("get "); - } else { - emitter.writeToOutput("set "); - } - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - } else { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - emitter.writeToOutputTrimmable(": "); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - - } - case TypeScript.NodeType.Comma: { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); - if(emitter.emitState.inObjectLiteral) { - emitter.writeLineToOutput(", "); - } else { - emitter.writeToOutput(","); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - - } - case TypeScript.NodeType.Is: { - throw new Error("should be de-sugared during type check"); - - } - default: { - throw new Error("please implement in derived class"); - - } - } - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return BinaryExpression; - })(Expression); - TypeScript.BinaryExpression = BinaryExpression; - var ConditionalExpression = (function (_super) { - __extends(ConditionalExpression, _super); - function ConditionalExpression(operand1, operand2, operand3) { - _super.call(this, TypeScript.NodeType.ConditionalExpression); - this.operand1 = operand1; - this.operand2 = operand2; - this.operand3 = operand3; - } - ConditionalExpression.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckQMark(this); - }; - ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" ? "); - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" : "); - emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ConditionalExpression; - })(Expression); - TypeScript.ConditionalExpression = ConditionalExpression; - var NumberLiteral = (function (_super) { - __extends(NumberLiteral, _super); - function NumberLiteral(value, hasEmptyFraction) { - _super.call(this, TypeScript.NodeType.NumberLit); - this.value = value; - this.hasEmptyFraction = hasEmptyFraction; - this.isNegativeZero = false; - } - NumberLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.doubleType; - return this; - }; - NumberLiteral.prototype.treeViewLabel = function () { - return "num: " + this.printLabel(); - }; - NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.isNegativeZero) { - emitter.writeToOutput("-"); - } - emitter.writeToOutput(this.value.toString()); - if(this.hasEmptyFraction) { - emitter.writeToOutput(".0"); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - NumberLiteral.prototype.printLabel = function () { - if(Math.floor(this.value) != this.value) { - return this.value.toFixed(2).toString(); - } else { - if(this.hasEmptyFraction) { - return this.value.toString() + ".0"; - } else { - return this.value.toString(); - } - } - }; - return NumberLiteral; - })(Expression); - TypeScript.NumberLiteral = NumberLiteral; - var RegexLiteral = (function (_super) { - __extends(RegexLiteral, _super); - function RegexLiteral(regex) { - _super.call(this, TypeScript.NodeType.Regex); - this.regex = regex; - } - RegexLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.regexType; - return this; - }; - RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.regex.toString()); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return RegexLiteral; - })(Expression); - TypeScript.RegexLiteral = RegexLiteral; - var StringLiteral = (function (_super) { - __extends(StringLiteral, _super); - function StringLiteral(text) { - _super.call(this, TypeScript.NodeType.QString); - this.text = text; - } - StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitStringLiteral(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - StringLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.stringType; - return this; - }; - StringLiteral.prototype.treeViewLabel = function () { - return "st: " + this.text; - }; - StringLiteral.prototype.printLabel = function () { - return this.text; - }; - return StringLiteral; - })(Expression); - TypeScript.StringLiteral = StringLiteral; - var ModuleElement = (function (_super) { - __extends(ModuleElement, _super); - function ModuleElement(nodeType) { - _super.call(this, nodeType); - } - return ModuleElement; - })(AST); - TypeScript.ModuleElement = ModuleElement; - var ImportDeclaration = (function (_super) { - __extends(ImportDeclaration, _super); - function ImportDeclaration(id, alias) { - _super.call(this, TypeScript.NodeType.ImportDeclaration); - this.id = id; - this.alias = alias; - this.varFlags = TypeScript.VarFlags.None; - this.isDynamicImport = false; - } - ImportDeclaration.prototype.isStatementOrExpression = function () { - return true; - }; - ImportDeclaration.prototype.isDeclaration = function () { - return true; - }; - ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - var mod = this.alias.type; - if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { - var prevModAliasId = emitter.modAliasId; - var prevFirstModAlias = emitter.firstModAlias; - emitter.recordSourceMappingStart(this); - emitter.emitParensAndCommentsInPlace(this, true); - emitter.writeToOutput("var " + this.id.actualText + " = "); - emitter.modAliasId = this.id.actualText; - emitter.firstModAlias = this.firstAliasedModToString(); - emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); - if(!this.isDynamicImport) { - emitter.writeToOutput(";"); - } - emitter.emitParensAndCommentsInPlace(this, false); - emitter.recordSourceMappingEnd(this); - emitter.modAliasId = prevModAliasId; - emitter.firstModAlias = prevFirstModAlias; - } - }; - ImportDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckImportDecl(this); - }; - ImportDeclaration.prototype.getAliasName = function (aliasAST) { - if (typeof aliasAST === "undefined") { aliasAST = this.alias; } - if(aliasAST.nodeType == TypeScript.NodeType.Name) { - return (aliasAST).actualText; - } else { - var dotExpr = aliasAST; - return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); - } - }; - ImportDeclaration.prototype.firstAliasedModToString = function () { - if(this.alias.nodeType == TypeScript.NodeType.Name) { - return (this.alias).actualText; - } else { - var dotExpr = this.alias; - var firstMod = dotExpr.operand1; - return firstMod.actualText; - } - }; - return ImportDeclaration; - })(ModuleElement); - TypeScript.ImportDeclaration = ImportDeclaration; - var BoundDecl = (function (_super) { - __extends(BoundDecl, _super); - function BoundDecl(id, nodeType, nestingLevel) { - _super.call(this, nodeType); - this.id = id; - this.nestingLevel = nestingLevel; - this.init = null; - this.typeExpr = null; - this.varFlags = TypeScript.VarFlags.None; - this.sym = null; - } - BoundDecl.prototype.isDeclaration = function () { - return true; - }; - BoundDecl.prototype.isStatementOrExpression = function () { - return true; - }; - BoundDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); - }; - BoundDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); - }; - BoundDecl.prototype.isProperty = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); - }; - BoundDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckBoundDecl(this); - }; - BoundDecl.prototype.printLabel = function () { - return this.treeViewLabel(); - }; - return BoundDecl; - })(AST); - TypeScript.BoundDecl = BoundDecl; - var VarDecl = (function (_super) { - __extends(VarDecl, _super); - function VarDecl(id, nest) { - _super.call(this, id, TypeScript.NodeType.VarDecl, nest); - } - VarDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - VarDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - VarDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); - }; - VarDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptVarDecl(this, tokenId); - }; - VarDecl.prototype.treeViewLabel = function () { - return "var " + this.id.actualText; - }; - return VarDecl; - })(BoundDecl); - TypeScript.VarDecl = VarDecl; - var ArgDecl = (function (_super) { - __extends(ArgDecl, _super); - function ArgDecl(id) { - _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); - this.isOptional = false; - this.parameterPropertySym = null; - } - ArgDecl.prototype.isOptionalArg = function () { - return this.isOptional || this.init; - }; - ArgDecl.prototype.treeViewLabel = function () { - return "arg: " + this.id.actualText; - }; - ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ArgDecl; - })(BoundDecl); - TypeScript.ArgDecl = ArgDecl; - var internalId = 0; - var FuncDecl = (function (_super) { - __extends(FuncDecl, _super); - function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { - _super.call(this, nodeType); - this.name = name; - this.bod = bod; - this.isConstructor = isConstructor; - this.arguments = arguments; - this.vars = vars; - this.scopes = scopes; - this.statics = statics; - this.hint = null; - this.fncFlags = TypeScript.FncFlags.None; - this.returnTypeAnnotation = null; - this.variableArgList = false; - this.jumpRefs = null; - this.internalNameCache = null; - this.tmp1Declared = false; - this.enclosingFnc = null; - this.freeVariables = []; - this.unitIndex = -1; - this.classDecl = null; - this.boundToProperty = null; - this.isOverload = false; - this.innerStaticFuncs = []; - this.isTargetTypedAsMethod = false; - this.isInlineCallLiteral = false; - this.accessorSymbol = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.returnStatementsWithExpressions = []; - this.scopeType = null; - this.endingToken = null; - } - FuncDecl.prototype.isDeclaration = function () { - return true; - }; - FuncDecl.prototype.internalName = function () { - if(this.internalNameCache == null) { - var extName = this.getNameText(); - if(extName) { - this.internalNameCache = "_internal_" + extName; - } else { - this.internalNameCache = "_internal_" + internalId++; - } - } - return this.internalNameCache; - }; - FuncDecl.prototype.hasSelfReference = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); - }; - FuncDecl.prototype.setHasSelfReference = function () { - this.fncFlags |= TypeScript.FncFlags.HasSelfReference; - }; - FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); - }; - FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { - this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; - }; - FuncDecl.prototype.addCloRef = function (id, sym) { - if(this.envids == null) { - this.envids = new Array(); - } - this.envids[this.envids.length] = id; - var outerFnc = this.enclosingFnc; - if(sym) { - while(outerFnc && (outerFnc.type.symbol != sym.container)) { - outerFnc.addJumpRef(sym); - outerFnc = outerFnc.enclosingFnc; - } - } - return this.envids.length - 1; - }; - FuncDecl.prototype.addJumpRef = function (sym) { - if(this.jumpRefs == null) { - this.jumpRefs = new Array(); - } - var id = new Identifier(sym.name); - this.jumpRefs[this.jumpRefs.length] = id; - id.sym = sym; - id.cloId = this.addCloRef(id, null); - }; - FuncDecl.prototype.buildControlFlow = function () { - var entry = new TypeScript.BasicBlock(); - var exit = new TypeScript.BasicBlock(); - var context = new TypeScript.ControlFlowContext(entry, exit); - var controlFlowPrefix = function (ast, parent, walker) { - ast.addToControlFlow(walker.state); - return ast; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); - context.walker = walker; - walker.walk(this.bod, this); - return context; - }; - FuncDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFunction(this); - }; - FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptFunction(this); - }; - FuncDecl.prototype.getNameText = function () { - if(this.name) { - return this.name.actualText; - } else { - return this.hint; - } - }; - FuncDecl.prototype.isMethod = function () { - return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isCallMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); - }; - FuncDecl.prototype.isConstructMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); - }; - FuncDecl.prototype.isIndexerMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); - }; - FuncDecl.prototype.isSpecialFn = function () { - return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); - }; - FuncDecl.prototype.isAnonymousFn = function () { - return this.name === null; - }; - FuncDecl.prototype.isAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isGetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); - }; - FuncDecl.prototype.isSetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); - }; - FuncDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); - }; - FuncDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); - }; - FuncDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); - }; - FuncDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); - }; - FuncDecl.prototype.treeViewLabel = function () { - if(this.name == null) { - return "funcExpr"; - } else { - return "func: " + this.name.actualText; - } - }; - FuncDecl.prototype.ClearFlags = function () { - this.fncFlags = TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isSignature = function () { - return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; - }; - return FuncDecl; - })(AST); - TypeScript.FuncDecl = FuncDecl; - var LocationInfo = (function () { - function LocationInfo(filename, lineMap, unitIndex) { - this.filename = filename; - this.lineMap = lineMap; - this.unitIndex = unitIndex; - } - return LocationInfo; - })(); - TypeScript.LocationInfo = LocationInfo; - TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); - var Script = (function (_super) { - __extends(Script, _super); - function Script(vars, scopes) { - _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); - this.locationInfo = null; - this.referencedFiles = []; - this.requiresGlobal = false; - this.requiresExtendsBlock = false; - this.isResident = false; - this.isDeclareFile = false; - this.hasBeenTypeChecked = false; - this.topLevelMod = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.externallyVisibleImportedSymbols = []; - this.vars = vars; - this.scopes = scopes; - } - Script.prototype.setCachedEmitRequired = function (value) { - this.cachedEmitRequired = value; - return this.cachedEmitRequired; - }; - Script.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckScript(this); - }; - Script.prototype.treeViewLabel = function () { - return "Script"; - }; - Script.prototype.emitRequired = function (emitOptions) { - if(this.cachedEmitRequired != undefined) { - return this.cachedEmitRequired; - } - if(!this.isDeclareFile && !this.isResident && this.bod) { - for(var i = 0, len = this.bod.members.length; i < len; i++) { - var stmt = this.bod.members[i]; - if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { - if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType == TypeScript.NodeType.VarDecl) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { - if(!(stmt).isSignature()) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { - return this.setCachedEmitRequired(true); - } - } - } - } - } - } - if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { - return this.setCachedEmitRequired(true); - } - } - return this.setCachedEmitRequired(false); - }; - Script.prototype.emit = function (emitter, tokenId, startLine) { - if(this.emitRequired(emitter.emitOptions)) { - emitter.emitParensAndCommentsInPlace(this.bod, true); - emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); - emitter.emitParensAndCommentsInPlace(this.bod, false); - } - }; - Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { - if(this.isExternallyVisibleSymbol(symbol)) { - return; - } - if(!symbol.getType().symbol.isExternallyVisible(checker)) { - var quotes = ""; - var moduleName = symbol.getType().symbol.prettyName; - if(!TypeScript.isQuoted(moduleName)) { - quotes = "'"; - } - checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); - } - this.externallyVisibleImportedSymbols.push(symbol); - }; - Script.prototype.isExternallyVisibleSymbol = function (symbol) { - for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { - if(this.externallyVisibleImportedSymbols[i] == symbol) { - return true; - } - } - return false; - }; - return Script; - })(FuncDecl); - TypeScript.Script = Script; - var NamedDeclaration = (function (_super) { - __extends(NamedDeclaration, _super); - function NamedDeclaration(nodeType, name, members) { - _super.call(this, nodeType); - this.name = name; - this.members = members; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - } - NamedDeclaration.prototype.isDeclaration = function () { - return true; - }; - return NamedDeclaration; - })(ModuleElement); - TypeScript.NamedDeclaration = NamedDeclaration; - var ModuleDeclaration = (function (_super) { - __extends(ModuleDeclaration, _super); - function ModuleDeclaration(name, members, vars, scopes, endingToken) { - _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); - this.endingToken = endingToken; - this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; - this.amdDependencies = []; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.vars = vars; - this.scopes = scopes; - this.prettyName = this.name.actualText; - } - ModuleDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); - }; - ModuleDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); - }; - ModuleDeclaration.prototype.isEnum = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); - }; - ModuleDeclaration.prototype.recordNonInterface = function () { - this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - }; - ModuleDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckModule(this); - }; - ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascriptModule(this); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - } - }; - return ModuleDeclaration; - })(NamedDeclaration); - TypeScript.ModuleDeclaration = ModuleDeclaration; - var TypeDeclaration = (function (_super) { - __extends(TypeDeclaration, _super); - function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { - _super.call(this, nodeType, name, members); - this.extendsList = extendsList; - this.implementsList = implementsList; - this.varFlags = TypeScript.VarFlags.None; - } - TypeDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - TypeDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - return TypeDeclaration; - })(NamedDeclaration); - TypeScript.TypeDeclaration = TypeDeclaration; - var ClassDeclaration = (function (_super) { - __extends(ClassDeclaration, _super); - function ClassDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); - this.knownMemberNames = { - }; - this.constructorDecl = null; - this.constructorNestingLevel = 0; - this.endingToken = null; - } - ClassDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckClass(this); - }; - ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptClass(this); - }; - return ClassDeclaration; - })(TypeDeclaration); - TypeScript.ClassDeclaration = ClassDeclaration; - var InterfaceDeclaration = (function (_super) { - __extends(InterfaceDeclaration, _super); - function InterfaceDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); - } - InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckInterface(this); - }; - InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - }; - return InterfaceDeclaration; - })(TypeDeclaration); - TypeScript.InterfaceDeclaration = InterfaceDeclaration; - var Statement = (function (_super) { - __extends(Statement, _super); - function Statement(nodeType) { - _super.call(this, nodeType); - this.flags |= TypeScript.ASTFlags.IsStatement; - } - Statement.prototype.isLoop = function () { - return false; - }; - Statement.prototype.isStatementOrExpression = function () { - return true; - }; - Statement.prototype.isCompoundStatement = function () { - return this.isLoop(); - }; - Statement.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - return Statement; - })(ModuleElement); - TypeScript.Statement = Statement; - var LabeledStatement = (function (_super) { - __extends(LabeledStatement, _super); - function LabeledStatement(labels, stmt) { - _super.call(this, TypeScript.NodeType.LabeledStatement); - this.labels = labels; - this.stmt = stmt; - } - LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.labels) { - var labelsLen = this.labels.members.length; - for(var i = 0; i < labelsLen; i++) { - this.labels.members[i].emit(emitter, tokenId, startLine); - } - } - this.stmt.emit(emitter, tokenId, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - LabeledStatement.prototype.typeCheck = function (typeFlow) { - typeFlow.typeCheck(this.labels); - this.stmt = this.stmt.typeCheck(typeFlow); - return this; - }; - LabeledStatement.prototype.addToControlFlow = function (context) { - var beforeBB = context.current; - var bb = new TypeScript.BasicBlock(); - context.current = bb; - beforeBB.addSuccessor(bb); - }; - return LabeledStatement; - })(Statement); - TypeScript.LabeledStatement = LabeledStatement; - var Block = (function (_super) { - __extends(Block, _super); - function Block(statements, isStatementBlock) { - _super.call(this, TypeScript.NodeType.Block); - this.statements = statements; - this.isStatementBlock = isStatementBlock; - } - Block.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.isStatementBlock) { - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - } else { - emitter.setInVarBlock(this.statements.members.length); - } - var temp = emitter.setInObjectLiteral(false); - if(this.statements) { - emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); - } - if(this.isStatementBlock) { - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Block.prototype.addToControlFlow = function (context) { - var afterIfNeeded = new TypeScript.BasicBlock(); - context.pushStatement(this, context.current, afterIfNeeded); - if(this.statements) { - context.walk(this.statements, this); - } - context.walker.options.goChildren = false; - context.popStatement(); - if(afterIfNeeded.predecessors.length > 0) { - context.current.addSuccessor(afterIfNeeded); - context.current = afterIfNeeded; - } - }; - Block.prototype.typeCheck = function (typeFlow) { - if(!typeFlow.checker.styleSettings.emptyBlocks) { - if((this.statements === null) || (this.statements.members.length == 0)) { - typeFlow.checker.errorReporter.styleError(this, "empty block"); - } - } - typeFlow.typeCheck(this.statements); - return this; - }; - return Block; - })(Statement); - TypeScript.Block = Block; - var Jump = (function (_super) { - __extends(Jump, _super); - function Jump(nodeType) { - _super.call(this, nodeType); - this.target = null; - this.resolvedTarget = null; - } - Jump.prototype.hasExplicitTarget = function () { - return (this.target); - }; - Jump.prototype.setResolvedTarget = function (parser, stmt) { - if(stmt.isLoop()) { - this.resolvedTarget = stmt; - return true; - } - if(this.nodeType === TypeScript.NodeType.Continue) { - parser.reportParseError("continue statement applies only to loops"); - return false; - } else { - if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { - this.resolvedTarget = stmt; - return true; - } else { - parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); - return false; - } - } - }; - Jump.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); - }; - Jump.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.Break) { - emitter.writeToOutput("break"); - } else { - emitter.writeToOutput("continue"); - } - if(this.hasExplicitTarget()) { - emitter.writeToOutput(" " + this.target); - } - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Jump; - })(Statement); - TypeScript.Jump = Jump; - var WhileStatement = (function (_super) { - __extends(WhileStatement, _super); - function WhileStatement(cond) { - _super.call(this, TypeScript.NodeType.While); - this.cond = cond; - this.body = null; - } - WhileStatement.prototype.isLoop = function () { - return true; - }; - WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("while("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, false); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWhile(this); - }; - WhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - context.addContent(this.cond); - var condBlock = context.current; - var targetInfo = null; - if(this.body) { - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return WhileStatement; - })(Statement); - TypeScript.WhileStatement = WhileStatement; - var DoWhileStatement = (function (_super) { - __extends(DoWhileStatement, _super); - function DoWhileStatement() { - _super.call(this, TypeScript.NodeType.DoWhile); - this.body = null; - this.whileAST = null; - this.cond = null; - } - DoWhileStatement.prototype.isLoop = function () { - return true; - }; - DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("do"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingStart(this.whileAST); - emitter.writeToOutput("while"); - emitter.recordSourceMappingEnd(this.whileAST); - emitter.writeToOutput('('); - emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); - emitter.writeToOutput(")"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - DoWhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckDoWhile(this); - }; - DoWhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var targetInfo = null; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - context.addContent(this.cond); - context.current = afterLoop; - loopEnd.addSuccessor(afterLoop); - } else { - context.addUnreachable(this.cond); - } - context.walker.options.goChildren = false; - }; - return DoWhileStatement; - })(Statement); - TypeScript.DoWhileStatement = DoWhileStatement; - var IfStatement = (function (_super) { - __extends(IfStatement, _super); - function IfStatement(cond) { - _super.call(this, TypeScript.NodeType.If); - this.cond = cond; - this.elseBod = null; - this.statement = new ASTSpan(); - } - IfStatement.prototype.isCompoundStatement = function () { - return true; - }; - IfStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("if("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.thenBod, true); - if(this.elseBod) { - if(this.elseBod.nodeType === TypeScript.NodeType.If) { - emitter.writeToOutput(" else "); - this.elseBod.emit(emitter, tokenId, false); - } else { - emitter.writeToOutput(" else"); - emitter.emitJavascriptStatements(this.elseBod, true); - } - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - IfStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckIf(this); - }; - IfStatement.prototype.addToControlFlow = function (context) { - this.cond.addToControlFlow(context); - var afterIf = new TypeScript.BasicBlock(); - var beforeIf = context.current; - context.pushStatement(this, beforeIf, afterIf); - var hasContinuation = false; - context.current = new TypeScript.BasicBlock(); - beforeIf.addSuccessor(context.current); - context.walk(this.thenBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } - if(this.elseBod) { - context.current = new TypeScript.BasicBlock(); - context.noContinuation = false; - beforeIf.addSuccessor(context.current); - context.walk(this.elseBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } else { - if(hasContinuation) { - context.noContinuation = false; - } - } - } else { - beforeIf.addSuccessor(afterIf); - context.noContinuation = false; - hasContinuation = true; - } - var targetInfo = context.popStatement(); - if(afterIf.predecessors.length > 0) { - context.noContinuation = false; - hasContinuation = true; - } - if(hasContinuation) { - context.current = afterIf; - } - context.walker.options.goChildren = false; - }; - return IfStatement; - })(Statement); - TypeScript.IfStatement = IfStatement; - var ReturnStatement = (function (_super) { - __extends(ReturnStatement, _super); - function ReturnStatement() { - _super.call(this, TypeScript.NodeType.Return); - this.returnExpression = null; - } - ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - if(this.returnExpression) { - emitter.writeToOutput("return "); - emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); - if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { - emitter.writeToOutput(";"); - } - } else { - emitter.writeToOutput("return;"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ReturnStatement.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.returnStmt(); - }; - ReturnStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckReturn(this); - }; - return ReturnStatement; - })(Statement); - TypeScript.ReturnStatement = ReturnStatement; - var EndCode = (function (_super) { - __extends(EndCode, _super); - function EndCode() { - _super.call(this, TypeScript.NodeType.EndCode); - } - return EndCode; - })(AST); - TypeScript.EndCode = EndCode; - var ForInStatement = (function (_super) { - __extends(ForInStatement, _super); - function ForInStatement(lval, obj) { - _super.call(this, TypeScript.NodeType.ForIn); - this.lval = lval; - this.obj = obj; - this.statement = new ASTSpan(); - if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { - (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; - } - } - ForInStatement.prototype.isLoop = function () { - return true; - }; - ForInStatement.prototype.isFiltered = function () { - if(this.body) { - var singleItem = null; - if(this.body.nodeType == TypeScript.NodeType.List) { - var stmts = this.body; - if(stmts.members.length == 1) { - singleItem = stmts.members[0]; - } - } else { - singleItem = this.body; - } - if(singleItem !== null) { - if(singleItem.nodeType == TypeScript.NodeType.Block) { - var block = singleItem; - if((block.statements !== null) && (block.statements.members.length == 1)) { - singleItem = block.statements.members[0]; - } - } - if(singleItem.nodeType == TypeScript.NodeType.If) { - var cond = (singleItem).cond; - if(cond.nodeType == TypeScript.NodeType.Call) { - var target = (cond).target; - if(target.nodeType == TypeScript.NodeType.Dot) { - var binex = target; - if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { - var prop = binex.operand2; - if(prop.actualText == "hasOwnProperty") { - var args = (cond).arguments; - if((args !== null) && (args.members.length == 1)) { - var arg = args.members[0]; - if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { - if(((this.lval).actualText) == (arg).actualText) { - return true; - } - } - } - } - } - } - } - } - } - } - return false; - }; - ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("for("); - emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); - emitter.writeToOutput(" in "); - emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForInStatement.prototype.typeCheck = function (typeFlow) { - if(typeFlow.checker.styleSettings.forin) { - if(!this.isFiltered()) { - typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); - } - } - return typeFlow.typeCheckForIn(this); - }; - ForInStatement.prototype.addToControlFlow = function (context) { - if(this.lval) { - context.addContent(this.lval); - } - if(this.obj) { - context.addContent(this.obj); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - context.noContinuation = false; - loopHeader.addSuccessor(afterLoop); - context.walker.options.goChildren = false; - }; - return ForInStatement; - })(Statement); - TypeScript.ForInStatement = ForInStatement; - var ForStatement = (function (_super) { - __extends(ForStatement, _super); - function ForStatement(init) { - _super.call(this, TypeScript.NodeType.For); - this.init = init; - } - ForStatement.prototype.isLoop = function () { - return true; - }; - ForStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("for("); - if(this.init) { - if(this.init.nodeType != TypeScript.NodeType.List) { - emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); - } else { - emitter.setInVarBlock((this.init).members.length); - emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); - } - } - emitter.writeToOutput("; "); - emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); - emitter.writeToOutput("; "); - emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFor(this); - }; - ForStatement.prototype.addToControlFlow = function (context) { - if(this.init) { - context.addContent(this.init); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var condBlock = null; - var continueTarget = loopStart; - var incrBB = null; - if(this.incr) { - incrBB = new TypeScript.BasicBlock(); - continueTarget = incrBB; - } - if(this.cond) { - condBlock = context.current; - context.addContent(this.cond); - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - } - var targetInfo = null; - if(this.body) { - context.pushStatement(this, continueTarget, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(this.incr) { - if(context.noContinuation) { - if(incrBB.predecessors.length == 0) { - context.addUnreachable(this.incr); - } - } else { - context.current.addSuccessor(incrBB); - context.current = incrBB; - context.addContent(this.incr); - } - } - var loopEnd = context.current; - if(!(context.noContinuation)) { - loopEnd.addSuccessor(loopStart); - } - if(condBlock) { - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - } - if(afterLoop.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterLoop; - } - context.walker.options.goChildren = false; - }; - return ForStatement; - })(Statement); - TypeScript.ForStatement = ForStatement; - var WithStatement = (function (_super) { - __extends(WithStatement, _super); - function WithStatement(expr) { - _super.call(this, TypeScript.NodeType.With); - this.expr = expr; - this.withSym = null; - } - WithStatement.prototype.isCompoundStatement = function () { - return true; - }; - WithStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("with ("); - if(this.expr) { - emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); - } - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WithStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWith(this); - }; - return WithStatement; - })(Statement); - TypeScript.WithStatement = WithStatement; - var SwitchStatement = (function (_super) { - __extends(SwitchStatement, _super); - function SwitchStatement(val) { - _super.call(this, TypeScript.NodeType.Switch); - this.val = val; - this.defaultCase = null; - this.statement = new ASTSpan(); - } - SwitchStatement.prototype.isCompoundStatement = function () { - return true; - }; - SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("switch("); - emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - var casesLen = this.caseList.members.length; - for(var i = 0; i < casesLen; i++) { - var caseExpr = this.caseList.members[i]; - emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); - } - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - SwitchStatement.prototype.typeCheck = function (typeFlow) { - var len = this.caseList.members.length; - this.val = typeFlow.typeCheck(this.val); - for(var i = 0; i < len; i++) { - this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); - } - this.defaultCase = typeFlow.typeCheck(this.defaultCase); - this.type = typeFlow.voidType; - return this; - }; - SwitchStatement.prototype.addToControlFlow = function (context) { - var condBlock = context.current; - context.addContent(this.val); - var execBlock = new TypeScript.BasicBlock(); - var afterSwitch = new TypeScript.BasicBlock(); - condBlock.addSuccessor(execBlock); - context.pushSwitch(execBlock); - context.current = execBlock; - context.pushStatement(this, execBlock, afterSwitch); - context.walk(this.caseList, this); - context.popSwitch(); - var targetInfo = context.popStatement(); - var hasCondContinuation = (this.defaultCase == null); - if(this.defaultCase == null) { - condBlock.addSuccessor(afterSwitch); - } - if(afterSwitch.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterSwitch; - } else { - context.noContinuation = true; - } - context.walker.options.goChildren = false; - }; - return SwitchStatement; - })(Statement); - TypeScript.SwitchStatement = SwitchStatement; - var CaseStatement = (function (_super) { - __extends(CaseStatement, _super); - function CaseStatement() { - _super.call(this, TypeScript.NodeType.Case); - this.expr = null; - } - CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.expr) { - emitter.writeToOutput("case "); - emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); - } else { - emitter.writeToOutput("default"); - } - emitter.writeToOutput(":"); - if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { - emitter.emitJavascriptStatements(this.body, false); - } else { - emitter.writeLineToOutput(""); - emitter.indenter.increaseIndent(); - emitter.emitBareJavascriptStatements(this.body); - emitter.indenter.decreaseIndent(); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - CaseStatement.prototype.typeCheck = function (typeFlow) { - this.expr = typeFlow.typeCheck(this.expr); - typeFlow.typeCheck(this.body); - this.type = typeFlow.voidType; - return this; - }; - CaseStatement.prototype.addToControlFlow = function (context) { - var execBlock = new TypeScript.BasicBlock(); - var sw = context.currentSwitch[context.currentSwitch.length - 1]; - if(this.expr) { - var exprBlock = new TypeScript.BasicBlock(); - context.current = exprBlock; - sw.addSuccessor(exprBlock); - context.addContent(this.expr); - exprBlock.addSuccessor(execBlock); - } else { - sw.addSuccessor(execBlock); - } - context.current = execBlock; - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return CaseStatement; - })(Statement); - TypeScript.CaseStatement = CaseStatement; - var TypeReference = (function (_super) { - __extends(TypeReference, _super); - function TypeReference(term, arrayCount) { - _super.call(this, TypeScript.NodeType.TypeRef); - this.term = term; - this.arrayCount = arrayCount; - } - TypeReference.prototype.emit = function (emitter, tokenId, startLine) { - throw new Error("should not emit a type ref"); - }; - TypeReference.prototype.typeCheck = function (typeFlow) { - var prevInTCTR = typeFlow.inTypeRefTypeCheck; - typeFlow.inTypeRefTypeCheck = true; - var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); - typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); - if(this.term) { - typeFlow.typeCheck(this.term); - } - typeFlow.checkForVoidConstructor(typeLink.type, this); - this.type = typeLink.type; - if(this.term) { - this.term.type = this.type; - } - typeFlow.inTypeRefTypeCheck = prevInTCTR; - return this; - }; - return TypeReference; - })(AST); - TypeScript.TypeReference = TypeReference; - var TryFinally = (function (_super) { - __extends(TryFinally, _super); - function TryFinally(tryNode, finallyNode) { - _super.call(this, TypeScript.NodeType.TryFinally); - this.tryNode = tryNode; - this.finallyNode = finallyNode; - } - TryFinally.prototype.isCompoundStatement = function () { - return true; - }; - TryFinally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - }; - TryFinally.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.finallyNode = typeFlow.typeCheck(this.finallyNode); - this.type = typeFlow.voidType; - return this; - }; - TryFinally.prototype.addToControlFlow = function (context) { - var afterFinally = new TypeScript.BasicBlock(); - context.walk(this.tryNode, this); - var finBlock = new TypeScript.BasicBlock(); - if(context.current) { - context.current.addSuccessor(finBlock); - } - context.current = finBlock; - context.pushStatement(this, null, afterFinally); - context.walk(this.finallyNode, this); - if(!context.noContinuation && context.current) { - context.current.addSuccessor(afterFinally); - } - if(afterFinally.predecessors.length > 0) { - context.current = afterFinally; - } else { - context.noContinuation = true; - } - context.popStatement(); - context.walker.options.goChildren = false; - }; - return TryFinally; - })(Statement); - TypeScript.TryFinally = TryFinally; - var TryCatch = (function (_super) { - __extends(TryCatch, _super); - function TryCatch(tryNode, catchNode) { - _super.call(this, TypeScript.NodeType.TryCatch); - this.tryNode = tryNode; - this.catchNode = catchNode; - } - TryCatch.prototype.isCompoundStatement = function () { - return true; - }; - TryCatch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - TryCatch.prototype.addToControlFlow = function (context) { - var beforeTry = context.current; - var tryBlock = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(tryBlock); - context.current = tryBlock; - var afterTryCatch = new TypeScript.BasicBlock(); - context.pushStatement(this, null, afterTryCatch); - context.walk(this.tryNode, this); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(context.current); - context.walk(this.catchNode, this); - context.popStatement(); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = afterTryCatch; - context.walker.options.goChildren = false; - }; - TryCatch.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.catchNode = typeFlow.typeCheck(this.catchNode); - this.type = typeFlow.voidType; - return this; - }; - return TryCatch; - })(Statement); - TypeScript.TryCatch = TryCatch; - var Try = (function (_super) { - __extends(Try, _super); - function Try(body) { - _super.call(this, TypeScript.NodeType.Try); - this.body = body; - } - Try.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("try "); - emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Try.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - Try.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - return Try; - })(Statement); - TypeScript.Try = Try; - var Catch = (function (_super) { - __extends(Catch, _super); - function Catch(param, body) { - _super.call(this, TypeScript.NodeType.Catch); - this.param = param; - this.body = body; - this.statement = new ASTSpan(); - this.containedScope = null; - if(this.param) { - this.param.varFlags |= TypeScript.VarFlags.AutoInit; - } - } - Catch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(" "); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("catch ("); - emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Catch.prototype.addToControlFlow = function (context) { - if(this.param) { - context.addContent(this.param); - var bodBlock = new TypeScript.BasicBlock(); - context.current.addSuccessor(bodBlock); - context.current = bodBlock; - } - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - Catch.prototype.typeCheck = function (typeFlow) { - var prevScope = typeFlow.scope; - typeFlow.scope = this.containedScope; - this.param = typeFlow.typeCheck(this.param); - var exceptVar = new TypeScript.ValueLocation(); - var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); - exceptVar.symbol = varSym; - exceptVar.typeLink = new TypeScript.TypeLink(); - exceptVar.typeLink.type = typeFlow.anyType; - var thisFnc = typeFlow.thisFnc; - if(thisFnc && thisFnc.type) { - exceptVar.symbol.container = thisFnc.type.symbol; - } else { - exceptVar.symbol.container = null; - } - this.param.sym = exceptVar.symbol; - typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); - this.body = typeFlow.typeCheck(this.body); - if(typeFlow.checker.inProvisionalTypecheckMode()) { - var table = typeFlow.scope.getTable(); - (table).secondaryTable.table[exceptVar.symbol.name] = undefined; - } - this.type = typeFlow.voidType; - typeFlow.scope = prevScope; - return this; - }; - return Catch; - })(Statement); - TypeScript.Catch = Catch; - var Finally = (function (_super) { - __extends(Finally, _super); - function Finally(body) { - _super.call(this, TypeScript.NodeType.Finally); - this.body = body; - } - Finally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("finally"); - emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Finally.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - Finally.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - return Finally; - })(Statement); - TypeScript.Finally = Finally; - var Comment = (function (_super) { - __extends(Comment, _super); - function Comment(content, isBlockComment, endsLine) { - _super.call(this, TypeScript.NodeType.Comment); - this.content = content; - this.isBlockComment = isBlockComment; - this.endsLine = endsLine; - this.text = null; - this.docCommentText = null; - } - Comment.prototype.getText = function () { - if(this.text == null) { - if(this.isBlockComment) { - this.text = this.content.split("\n"); - for(var i = 0; i < this.text.length; i++) { - this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); - } - } else { - this.text = [ - (this.content.replace(/^\s+|\s+$/g, '')) - ]; - } - } - return this.text; - }; - Comment.prototype.isDocComment = function () { - if(this.isBlockComment) { - return this.content.charAt(2) == "*"; - } - return false; - }; - Comment.prototype.getDocCommentText = function () { - if(this.docCommentText == null) { - this.docCommentText = Comment.cleanJSDocComment(this.content); - } - return this.docCommentText; - }; - Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { - var endIndex = line.length; - if(maxSpacesToRemove != undefined) { - endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); - } - for(; startIndex < endIndex; startIndex++) { - var charCode = line.charCodeAt(startIndex); - if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { - return startIndex; - } - } - if(endIndex != line.length) { - return endIndex; - } - return -1; - } - Comment.isSpaceChar = function isSpaceChar(line, index) { - var length = line.length; - if(index < length) { - var charCode = line.charCodeAt(index); - return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; - } - return index == length; - } - Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { - var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); - if(nonSpaceIndex != -1) { - var jsDocSpacesRemoved = nonSpaceIndex; - if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { - var startIndex = nonSpaceIndex + 1; - nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); - if(nonSpaceIndex != -1) { - jsDocSpacesRemoved = nonSpaceIndex - startIndex; - } else { - return null; - } - } - return { - minChar: nonSpaceIndex, - limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, - jsDocSpacesRemoved: jsDocSpacesRemoved - }; - } - return null; - } - Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { - var docCommentLines = []; - content = content.replace("/**", ""); - if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { - content = content.substring(0, content.length - 2); - } - var lines = content.split("\n"); - var inParamTag = false; - for(var l = 0; l < lines.length; l++) { - var line = lines[l]; - var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); - if(!cleanLinePos) { - continue; - } - var docCommentText = ""; - var prevPos = cleanLinePos.minChar; - for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { - var wasInParamtag = inParamTag; - if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { - if(!wasInParamtag) { - docCommentText += line.substring(prevPos, i); - } - prevPos = i; - inParamTag = true; - } else { - if(wasInParamtag) { - prevPos = i; - inParamTag = false; - } - } - } - if(!inParamTag) { - docCommentText += line.substring(prevPos, cleanLinePos.limChar); - } - var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); - if(newCleanPos) { - if(spacesToRemove == undefined) { - spacesToRemove = cleanLinePos.jsDocSpacesRemoved; - } - docCommentLines.push(docCommentText); - } - } - return docCommentLines.join("\n"); - } - Comment.getDocCommentText = function getDocCommentText(comments) { - var docCommentText = []; - for(var c = 0; c < comments.length; c++) { - var commentText = comments[c].getDocCommentText(); - if(commentText != "") { - docCommentText.push(commentText); - } - } - return docCommentText.join("\n"); - } - Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { - if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { - return ""; - } - for(var i = 0; i < fncDocComments.length; i++) { - var commentContents = fncDocComments[i].content; - for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { - j += 6; - if(!Comment.isSpaceChar(commentContents, j)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j); - if(j == -1) { - break; - } - if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { - j++; - var charCode = 0; - for(var curlies = 1; j < commentContents.length; j++) { - charCode = commentContents.charCodeAt(j); - if(charCode == TypeScript.LexCodeLC) { - curlies++; - continue; - } - if(charCode == TypeScript.LexCodeRC) { - curlies--; - if(curlies == 0) { - break; - } else { - continue; - } - } - if(charCode == TypeScript.LexCodeAtSign) { - break; - } - } - if(j == commentContents.length) { - break; - } - if(charCode == TypeScript.LexCodeAtSign) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + 1); - if(j == -1) { - break; - } - } - if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + param.length); - if(j == -1) { - return ""; - } - var endOfParam = commentContents.indexOf("@", j); - var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); - var paramSpacesToRemove = undefined; - var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; - if(paramLineIndex != 0) { - if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { - paramLineIndex++; - } - } - var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); - if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { - paramSpacesToRemove = j - startSpaceRemovalIndex - 1; - } - return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); - } - } - return ""; - } - Comment.getDocCommentTextOfSignatures = function getDocCommentTextOfSignatures(signatures) { - var comments = []; - for(var i = 0; i < signatures.length; i++) { - var signatureDocComment = TypeScript.Comment.getDocCommentText(signatures[i].declAST.getDocComments()); - if(signatureDocComment != "") { - comments.push(signatureDocComment); - } - } - return comments.join("\n"); - } - return Comment; - })(AST); - TypeScript.Comment = Comment; - var DebuggerStatement = (function (_super) { - __extends(DebuggerStatement, _super); - function DebuggerStatement() { - _super.call(this, TypeScript.NodeType.Debugger); - } - DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeLineToOutput("debugger;"); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return DebuggerStatement; - })(Statement); - TypeScript.DebuggerStatement = DebuggerStatement; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstWalkOptions = (function () { - function AstWalkOptions() { - this.goChildren = true; - this.goNextSibling = true; - this.reverseSiblings = false; - } - AstWalkOptions.prototype.stopWalk = function (stop) { - if (typeof stop === "undefined") { stop = true; } - this.goChildren = !stop; - this.goNextSibling = !stop; - }; - return AstWalkOptions; - })(); - TypeScript.AstWalkOptions = AstWalkOptions; - var AstWalker = (function () { - function AstWalker(childrenWalkers, pre, post, options, state) { - this.childrenWalkers = childrenWalkers; - this.pre = pre; - this.post = post; - this.options = options; - this.state = state; - } - AstWalker.prototype.walk = function (ast, parent) { - var preAst = this.pre(ast, parent, this); - if(preAst === undefined) { - preAst = ast; - } - if(this.options.goChildren) { - var svGoSib = this.options.goNextSibling; - this.options.goNextSibling = true; - this.childrenWalkers[ast.nodeType](ast, parent, this); - this.options.goNextSibling = svGoSib; - } else { - this.options.goChildren = true; - } - if(this.post) { - var postAst = this.post(preAst, parent, this); - if(postAst === undefined) { - postAst = preAst; - } - return postAst; - } else { - return preAst; - } - }; - return AstWalker; - })(); - var AstWalkerFactory = (function () { - function AstWalkerFactory() { - this.childrenWalkers = []; - this.initChildrenWalkers(); - } - AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { - return this.getWalker(pre, post, options, state).walk(ast, null); - }; - AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { - return this.getSlowWalker(pre, post, options, state); - }; - AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { - if(!options) { - options = new AstWalkOptions(); - } - return new AstWalker(this.childrenWalkers, pre, post, options, state); - }; - AstWalkerFactory.prototype.initChildrenWalkers = function () { - this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; - this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; - this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; - this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; - this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; - this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; - this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; - this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; - this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; - this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; - this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; - this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; - this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; - this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; - this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; - for(var e in (TypeScript.NodeType)._map) { - if((this.childrenWalkers)[e] === undefined) { - throw new Error("initWalkers function is not up to date with enum content!"); - } - } - }; - return AstWalkerFactory; - })(); - TypeScript.AstWalkerFactory = AstWalkerFactory; - var globalAstWalkerFactory; - function getAstWalkerFactory() { - if(!globalAstWalkerFactory) { - globalAstWalkerFactory = new AstWalkerFactory(); - } - return globalAstWalkerFactory; - } - TypeScript.getAstWalkerFactory = getAstWalkerFactory; - var ChildrenWalkers; - (function (ChildrenWalkers) { - function walkNone(preAst, parent, walker) { - } - ChildrenWalkers.walkNone = walkNone; - function walkListChildren(preAst, parent, walker) { - var len = preAst.members.length; - if(walker.options.reverseSiblings) { - for(var i = len - 1; i >= 0; i--) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } else { - for(var i = 0; i < len; i++) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } - } - ChildrenWalkers.walkListChildren = walkListChildren; - function walkUnaryExpressionChildren(preAst, parent, walker) { - if(preAst.castTerm) { - preAst.castTerm = walker.walk(preAst.castTerm, preAst); - } - if(preAst.operand) { - preAst.operand = walker.walk(preAst.operand, preAst); - } - } - ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; - function walkBinaryExpressionChildren(preAst, parent, walker) { - if(walker.options.reverseSiblings) { - if(preAst.operand2) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if((preAst.operand1) && (walker.options.goNextSibling)) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - } else { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if((preAst.operand2) && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - } - } - ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; - function walkTypeReferenceChildren(preAst, parent, walker) { - if(preAst.term) { - preAst.term = walker.walk(preAst.term, preAst); - } - } - ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; - function walkCallExpressionChildren(preAst, parent, walker) { - if(!walker.options.reverseSiblings) { - preAst.target = walker.walk(preAst.target, preAst); - } - if(preAst.arguments && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { - preAst.target = walker.walk(preAst.target, preAst); - } - } - ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; - function walkTrinaryExpressionChildren(preAst, parent, walker) { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if(preAst.operand2 && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if(preAst.operand3 && (walker.options.goNextSibling)) { - preAst.operand3 = walker.walk(preAst.operand3, preAst); - } - } - ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; - function walkFuncDeclChildren(preAst, parent, walker) { - if(preAst.name) { - preAst.name = walker.walk(preAst.name, preAst); - } - if(preAst.arguments && (preAst.arguments.members.length > 0) && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { - preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); - } - if(preAst.bod && (preAst.bod.members.length > 0) && (walker.options.goNextSibling)) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; - function walkBoundDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if((preAst.typeExpr) && (walker.options.goNextSibling)) { - preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); - } - } - ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; - function walkReturnStatementChildren(preAst, parent, walker) { - if(preAst.returnExpression) { - preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); - } - } - ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; - function walkForStatementChildren(preAst, parent, walker) { - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if(preAst.cond && walker.options.goNextSibling) { - preAst.cond = walker.walk(preAst.cond, preAst); - } - if(preAst.incr && walker.options.goNextSibling) { - preAst.incr = walker.walk(preAst.incr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; - function walkForInStatementChildren(preAst, parent, walker) { - preAst.lval = walker.walk(preAst.lval, preAst); - if(walker.options.goNextSibling) { - preAst.obj = walker.walk(preAst.obj, preAst); - } - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; - function walkIfStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.thenBod && (walker.options.goNextSibling)) { - preAst.thenBod = walker.walk(preAst.thenBod, preAst); - } - if(preAst.elseBod && (walker.options.goNextSibling)) { - preAst.elseBod = walker.walk(preAst.elseBod, preAst); - } - } - ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; - function walkWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; - function walkDoWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; - function walkBlockChildren(preAst, parent, walker) { - if(preAst.statements) { - preAst.statements = walker.walk(preAst.statements, preAst); - } - } - ChildrenWalkers.walkBlockChildren = walkBlockChildren; - function walkCaseStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; - function walkSwitchStatementChildren(preAst, parent, walker) { - if(preAst.val) { - preAst.val = walker.walk(preAst.val, preAst); - } - if((preAst.caseList) && walker.options.goNextSibling) { - preAst.caseList = walker.walk(preAst.caseList, preAst); - } - } - ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; - function walkTryChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkTryChildren = walkTryChildren; - function walkTryCatchChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if((preAst.catchNode) && walker.options.goNextSibling) { - preAst.catchNode = walker.walk(preAst.catchNode, preAst); - } - } - ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; - function walkTryFinallyChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if(preAst.finallyNode && walker.options.goNextSibling) { - preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); - } - } - ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; - function walkFinallyChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; - function walkCatchChildren(preAst, parent, walker) { - if(preAst.param) { - preAst.param = walker.walk(preAst.param, preAst); - } - if((preAst.body) && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCatchChildren = walkCatchChildren; - function walkRecordChildren(preAst, parent, walker) { - preAst.name = walker.walk(preAst.name, preAst); - if(walker.options.goNextSibling && preAst.members) { - preAst.members = walker.walk(preAst.members, preAst); - } - } - ChildrenWalkers.walkRecordChildren = walkRecordChildren; - function walkNamedTypeChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; - function walkClassDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; - function walkScriptChildren(preAst, parent, walker) { - if(preAst.bod) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkScriptChildren = walkScriptChildren; - function walkTypeDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; - function walkModuleDeclChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; - function walkImportDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.alias) { - preAst.alias = walker.walk(preAst.alias, preAst); - } - } - ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; - function walkWithStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; - function walkLabelChildren(preAst, parent, walker) { - } - ChildrenWalkers.walkLabelChildren = walkLabelChildren; - function walkLabeledStatementChildren(preAst, parent, walker) { - preAst.labels = walker.walk(preAst.labels, preAst); - if(walker.options.goNextSibling) { - preAst.stmt = walker.walk(preAst.stmt, preAst); - } - } - ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; - })(ChildrenWalkers || (ChildrenWalkers = {})); -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (AstWalkerWithDetailCallback) { - function walk(script, callback) { - var pre = function (cur, parent) { - walker.options.goChildren = AstWalkerCallback(true, cur, callback); - return cur; - }; - var post = function (cur, parent) { - AstWalkerCallback(false, cur, callback); - return cur; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); - walker.walk(script, null); - } - AstWalkerWithDetailCallback.walk = walk; - function AstWalkerCallback(pre, ast, callback) { - var nodeType = ast.nodeType; - var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; - if(callback[callbackString]) { - return callback[callbackString](pre, ast); - } - if(callback.DefaultCallback) { - return callback.DefaultCallback(pre, ast); - } - return true; - } - })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); - var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function lastOf(items) { - return (items === null || items.length === 0) ? null : items[items.length - 1]; - } - TypeScript.lastOf = lastOf; - function max(a, b) { - return a >= b ? a : b; - } - TypeScript.max = max; - function min(a, b) { - return a <= b ? a : b; - } - TypeScript.min = min; - var AstPath = (function () { - function AstPath() { - this.asts = []; - this.top = -1; - } - AstPath.reverseIndexOf = function reverseIndexOf(items, index) { - return (items === null || items.length <= index) ? null : items[items.length - index - 1]; - } - AstPath.prototype.clone = function () { - var clone = new AstPath(); - clone.asts = this.asts.map(function (value) { - return value; - }); - clone.top = this.top; - return clone; - }; - AstPath.prototype.pop = function () { - var head = this.ast(); - this.up(); - while(this.asts.length > this.count()) { - this.asts.pop(); - } - return head; - }; - AstPath.prototype.push = function (ast) { - while(this.asts.length > this.count()) { - this.asts.pop(); - } - this.top = this.asts.length; - this.asts.push(ast); - }; - AstPath.prototype.up = function () { - if(this.top <= -1) { - throw new Error("Invalid call to 'up'"); - } - this.top--; - }; - AstPath.prototype.down = function () { - if(this.top == this.ast.length - 1) { - throw new Error("Invalid call to 'down'"); - } - this.top++; - }; - AstPath.prototype.nodeType = function () { - if(this.ast() == null) { - return TypeScript.NodeType.None; - } - return this.ast().nodeType; - }; - AstPath.prototype.ast = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); - }; - AstPath.prototype.parent = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); - }; - AstPath.prototype.count = function () { - return this.top + 1; - }; - AstPath.prototype.get = function (index) { - return this.asts[index]; - }; - AstPath.prototype.isNameOfClass = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfInterface = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfArgument = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfVariable = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfModule = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfFunction = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isChildOfScript = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; - }; - AstPath.prototype.isChildOfModule = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; - }; - AstPath.prototype.isChildOfClass = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; - }; - AstPath.prototype.isArgumentOfClassConstructor = function () { - var ast = lastOf(this.asts); - return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); - }; - AstPath.prototype.isChildOfInterface = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; - }; - AstPath.prototype.isTopLevelImplicitModule = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfScript = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfSwitch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfModule = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfClass = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfInterface = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfBlock = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFor = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCase = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfTry = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCatch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDoWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfForIn = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWith = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFinally = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; - }; - AstPath.prototype.isDefaultCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; - }; - AstPath.prototype.isListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfObjectLit = function () { - return this.isListOfObjectLit(); - }; - AstPath.prototype.isEmptyListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; - }; - AstPath.prototype.isMemberOfObjectLit = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; - }; - AstPath.prototype.isNameOfMemberOfObjectLit = function () { - return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; - }; - AstPath.prototype.isListOfArrayLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isTargetOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; - }; - AstPath.prototype.isMemberOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; - }; - AstPath.prototype.isItemOfList = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; - }; - AstPath.prototype.isThenOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isElseOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDefaultCase = function () { - return this.isBodyOfCase(); - }; - AstPath.prototype.isSingleStatementList = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; - }; - AstPath.prototype.isArgumentListOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentOfFunction = function () { - return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; - }; - AstPath.prototype.isArgumentListOfCall = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentListOfNew = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isSynthesizedBlock = function () { - return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; - }; - return AstPath; - })(); - TypeScript.AstPath = AstPath; - function isValidAstNode(ast) { - if(ast === null) { - return false; - } - if(ast.minChar === -1 || ast.limChar === -1) { - return false; - } - return true; - } - TypeScript.isValidAstNode = isValidAstNode; - var AstPathContext = (function () { - function AstPathContext() { - this.path = new TypeScript.AstPath(); - } - return AstPathContext; - })(); - TypeScript.AstPathContext = AstPathContext; - (function (GetAstPathOptions) { - GetAstPathOptions._map = []; - GetAstPathOptions.Default = 0; - GetAstPathOptions.EdgeInclusive = 1; - GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; - })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); - var GetAstPathOptions = TypeScript.GetAstPathOptions; - function getAstPathToPosition(script, pos, options) { - if (typeof options === "undefined") { options = GetAstPathOptions.Default; } - var lookInComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - var minChar = comments[i].minChar; - var limChar = comments[i].limChar; - if(!comments[i].isBlockComment) { - limChar++; - } - if(pos >= minChar && pos < limChar) { - ctx.path.push(comments[i]); - } - } - } - }; - var pre = function (cur, parent, walker) { - if(isValidAstNode(cur)) { - var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; - var minChar = cur.minChar; - var limChar = cur.limChar + (inclusive ? 1 : 0); - if(pos >= minChar && pos < limChar) { - var previous = ctx.path.ast(); - if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { - ctx.path.push(cur); - } else { - } - } - if(pos < limChar) { - lookInComments(cur.preComments); - } - if(pos >= minChar) { - lookInComments(cur.postComments); - } - if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { - walker.options.goChildren = (minChar <= pos && pos <= limChar); - } - } - return cur; - }; - var ctx = new AstPathContext(); - TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); - return ctx.path; - } - TypeScript.getAstPathToPosition = getAstPathToPosition; - function getTokenizationOffset(script, position) { - var bestOffset = 0; - var pre = function (cur, parent, walker) { - if(TypeScript.isValidAstNode(cur)) { - if(cur.minChar <= position) { - bestOffset = max(bestOffset, cur.minChar); - } - if(cur.minChar > position || cur.limChar < bestOffset) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return bestOffset; - } - TypeScript.getTokenizationOffset = getTokenizationOffset; - function walkAST(ast, callback) { - var pre = function (cur, parent, walker) { - var path = walker.state; - path.push(cur); - callback(path, walker); - return cur; - }; - var post = function (cur, parent, walker) { - var path = walker.state; - path.pop(); - return cur; - }; - var path = new AstPath(); - TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); - } - TypeScript.walkAST = walkAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstLogger = (function () { - function AstLogger(logger) { - this.logger = logger; - } - AstLogger.prototype.logScript = function (script) { - var _this = this; - this.logLinemap(script.locationInfo.lineMap); - var stack = []; - var pre = function (cur, parent) { - stack.push(cur); - var indent = (stack.length - 1) * 2; - _this.logComments(script, cur.preComments, indent); - _this.logNode(script, cur, indent); - _this.logComments(script, cur.postComments, indent); - return cur; - }; - var post = function (cur, parent) { - stack.pop(); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre, post); - }; - AstLogger.prototype.logNode = function (script, cur, indent) { - var msg = this.addPadding("", indent, "| ", true); - msg = msg.concat("+ " + cur.treeViewLabel()); - msg = this.addPadding(msg, 70, " ", false); - msg = msg + this.addLineColumn(script, cur.minChar); - msg = this.addPadding(msg, 80, " ", false); - msg = msg + "=> "; - msg = msg + this.addLineColumn(script, cur.limChar); - msg = this.addPadding(msg, 102, " ", false); - msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); - msg = this.addPadding(msg, 115, " ", false); - msg = msg.concat("sym=" + (cur).sym); - msg = this.addPadding(msg, 135, " ", false); - msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); - this.logger.log(msg); - }; - AstLogger.prototype.logComments = function (script, comments, indent) { - if(comments == null) { - return; - } - for(var i = 0; i < comments.length; i++) { - this.logNode(script, comments[i], indent); - } - }; - AstLogger.prototype.logLinemap = function (linemap) { - var result = "["; - for(var i = 0; i < linemap.length; i++) { - if(i > 0) { - result += ","; - } - result += linemap[i]; - } - result += "]"; - this.logger.log("linemap: " + result); - }; - AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { - var result = (leftPadding ? "" : s); - for(var i = s.length; i < targetLength; i++) { - result = result + paddingString; - } - result = result + (leftPadding ? s : ""); - return result; - }; - AstLogger.prototype.addLineColumn = function (script, position) { - var lineInfo = { - line: -1, - col: -1 - }; - TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); - if(lineInfo.col !== -1) { - lineInfo.col++; - } - return "(" + lineInfo.line + ", " + lineInfo.col + ")"; - }; - return AstLogger; - })(); - TypeScript.AstLogger = AstLogger; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Binder = (function () { - function Binder(checker) { - this.checker = checker; - } - Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { - var extendsList = null; - if(typeLinks) { - extendsList = new Array(); - for(var i = 0, len = typeLinks.length; i < len; i++) { - extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); - } - } - return extendsList; - }; - Binder.prototype.resolveBases = function (scope, type) { - type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); - var i = 0, len = type.extendsList.length; - var derivedIsClass = type.isClassInstance(); - for(; i < len; i++) { - var baseIsClass = type.extendsList[i].isClassInstance(); - if(type.extendsList[i] != this.checker.anyType) { - var baseRef = type.extendsTypeLinks[i].ast; - if(derivedIsClass) { - if(!baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); - } - } else { - if(baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); - } - } - } - } - type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); - if(type.implementsList) { - for(i = 0 , len = type.implementsList.length; i < len; i++) { - var iface = type.implementsList[i]; - var baseRef = type.implementsTypeLinks[i].ast; - if(iface.isClassInstance()) { - if(derivedIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); - } - } - } - } - }; - Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { - var supplyVar = !(signatureGroup.hasImplementation); - for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { - var signature = signatureGroup.signatures[i]; - if(instanceType) { - signature.returnType.type = instanceType; - } else { - this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - this.bindSymbol(scope, signature.parameters[j]); - } - if(signature.hasVariableArgList) { - var lastParam = signature.parameters[paramLen - 1]; - lastParam.argsOffset = paramLen - 1; - if(!lastParam.getType().isArray()) { - this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); - lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); - } - } - } - }; - Binder.prototype.bindType = function (scope, type, instanceType) { - if(instanceType) { - this.bindType(scope, instanceType, null); - } - if(type.hasMembers()) { - var members = type.members; - var ambientMembers = type.ambientMembers; - var typeMembers = type.getAllEnclosedTypes(); - var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); - var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); - var agg = new TypeScript.SymbolAggregateScope(type.symbol); - var prevCurrentModDecl = this.checker.currentModDecl; - var prevBindStatus = this.checker.inBind; - agg.addParentScope(memberScope); - agg.addParentScope(scope); - if(type.isModuleType()) { - this.checker.currentModDecl = type.symbol.declAST; - this.checker.inBind = true; - } - if(members) { - this.bind(agg, type.members.allMembers); - } - if(typeMembers) { - this.bind(agg, typeMembers.allMembers); - } - if(ambientMembers) { - this.bind(agg, ambientMembers.allMembers); - } - if(ambientTypeMembers) { - this.bind(agg, ambientTypeMembers.allMembers); - } - this.checker.currentModDecl = prevCurrentModDecl; - this.checker.inBind = prevBindStatus; - } - if(type.extendsTypeLinks) { - this.resolveBases(scope, type); - } - if(type.construct) { - this.resolveSignatureGroup(type.construct, scope, instanceType); - } - if(type.call) { - this.resolveSignatureGroup(type.call, scope, null); - } - if(type.index) { - this.resolveSignatureGroup(type.index, scope, null); - } - if(type.elementType) { - this.bindType(scope, type.elementType, null); - } - }; - Binder.prototype.bindSymbol = function (scope, symbol) { - if(!symbol.bound) { - var prevLocationInfo = this.checker.locationInfo; - if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[symbol.unitIndex]; - } - switch(symbol.kind()) { - case TypeScript.SymbolKind.Type: { - if(symbol.flags & TypeScript.SymbolFlags.Bound) { - break; - } - var typeSymbol = symbol; - typeSymbol.flags |= TypeScript.SymbolFlags.Bound; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { - this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); - if(typeSymbol.type.isModuleType()) { - for(var i = 0; i < typeSymbol.expansions.length; i++) { - this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); - } - } - } - break; - - } - case TypeScript.SymbolKind.Field: { - this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); - break; - - } - case TypeScript.SymbolKind.Parameter: { - this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); - break; - - } - } - this.checker.locationInfo = prevLocationInfo; - } - symbol.bound = true; - }; - Binder.prototype.bind = function (scope, table) { - table.map(function (key, sym, binder) { - binder.bindSymbol(scope, sym); - }, this); - }; - return Binder; - })(); - TypeScript.Binder = Binder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Base64Format = (function () { - function Base64Format() { } - Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - Base64Format.encode = function encode(inValue) { - if(inValue < 64) { - return Base64Format.encodedValues.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - Base64Format.decodeChar = function decodeChar(inChar) { - if(inChar.length === 1) { - return Base64Format.encodedValues.indexOf(inChar); - } else { - throw TypeError('"' + inChar + '" must have length 1'); - } - } - return Base64Format; - })(); - var Base64VLQFormat = (function () { - function Base64VLQFormat() { } - Base64VLQFormat.encode = function encode(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 + Base64Format.encode(currentDigit); - }while(inValue > 0) - return encodedStr; - } - Base64VLQFormat.decode = function decode(inString) { - var result = 0; - var negative = false; - var shift = 0; - for(var i = 0; i < inString.length; i++) { - var byte = Base64Format.decodeChar(inString[i]); - if(i === 0) { - if((byte & 1) === 1) { - negative = true; - } - result = (byte >> 1) & 15; - } else { - result = result | ((byte & 31) << shift); - } - shift += (i == 0) ? 4 : 5; - if((byte & 32) === 32) { - } else { - return { - value: negative ? -(result) : result, - rest: inString.substr(i + 1) - }; - } - } - throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); - } - return Base64VLQFormat; - })(); - TypeScript.Base64VLQFormat = Base64VLQFormat; -})(TypeScript || (TypeScript = {})); -var JSON2 = { -}; -((function () { - 'use strict'; - function f(n) { - return n < 10 ? '0' + n : n; - } - if(typeof Date.prototype.toJSON !== 'function') { - Date.prototype.toJSON = function (key) { - return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; - }; - var strProto = String.prototype; - var numProto = Number.prototype; - numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { -'\b': '\\b', -'\t': '\\t', -'\n': '\\n', -'\f': '\\f', -'\r': '\\r', -'"': '\\"', -'\\': '\\\\' }, rep; - function quote(string) { - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - function str(key, holder) { - var i, k = null, v, length, mind = gap, partial, value = holder[key]; - if(value && typeof value === 'object' && typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - if(typeof rep === 'function') { - value = rep.call(holder, key, value); - } - switch(typeof value) { - case 'string': { - return quote(value); - - } - case 'number': { - return isFinite(value) ? String(value) : 'null'; - - } - case 'boolean': - case 'null': { - return String(value); - - } - case 'object': { - if(!value) { - return 'null'; - } - gap += indent; - partial = []; - if(Object.prototype.toString.apply(value, []) === '[object Array]') { - length = value.length; - for(i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - if(rep && typeof rep === 'object') { - length = rep.length; - for(i = 0; i < length; i += 1) { - if(typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - for(k in value) { - if(Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; - gap = mind; - return v; - - } - } - } - if(typeof JSON2.stringify !== 'function') { - JSON2.stringify = function (value, replacer, space) { - var i; - gap = ''; - indent = ''; - if(typeof space === 'number') { - for(i = 0; i < space; i += 1) { - indent += ' '; - } - } else { - if(typeof space === 'string') { - indent = space; - } - } - rep = replacer; - if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - return str('', { - '': value - }); - }; - } - if(typeof JSON2.parse !== 'function') { - JSON2.parse = function (text, reviver) { - var j; - function walk(holder, key) { - var k = null, v, value = holder[key]; - if(value && typeof value === 'object') { - for(k in value) { - if(Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if(v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - text = String(text); - cx.lastIndex = 0; - if(cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - j = eval('(' + text + ')'); - return typeof reviver === 'function' ? walk({ - '': j - }, '') : j; - } - throw new SyntaxError('JSON.parse'); - }; - } -})()); -var TypeScript; -(function (TypeScript) { - var SourceMapPosition = (function () { - function SourceMapPosition() { } - return SourceMapPosition; - })(); - TypeScript.SourceMapPosition = SourceMapPosition; - var SourceMapping = (function () { - function SourceMapping() { - this.start = new SourceMapPosition(); - this.end = new SourceMapPosition(); - this.nameIndex = -1; - this.childMappings = []; - } - return SourceMapping; - })(); - TypeScript.SourceMapping = SourceMapping; - var SourceMapper = (function () { - function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter) { - this.jsFile = jsFile; - this.sourceMapOut = sourceMapOut; - this.errorReporter = errorReporter; - this.sourceMappings = []; - this.currentMappings = []; - this.names = []; - this.currentNameIndex = []; - this.currentMappings.push(this.sourceMappings); - jsFileName = TypeScript.switchToForwardSlashes(jsFileName); - this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); - var removalIndex = jsFileName.lastIndexOf(this.jsFileName); - var fixedPath = jsFileName.substring(0, removalIndex); - this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); - } - SourceMapper.MapFileExtension = ".map"; - SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { - var sourceMapper = allSourceMappers[0]; - sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); - var sourceMapOut = sourceMapper.sourceMapOut; - var mappingsString = ""; - var tsFiles = []; - var prevEmittedColumn = 0; - var prevEmittedLine = 0; - var prevSourceColumn = 0; - var prevSourceLine = 0; - var prevSourceIndex = 0; - var prevNameIndex = 0; - var namesList = []; - var namesCount = 0; - var emitComma = false; - var recordedPosition = null; - for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { - sourceMapper = allSourceMappers[sourceMapperIndex]; - var currentSourceIndex = tsFiles.length; - tsFiles.push(sourceMapper.tsFileName); - if(sourceMapper.names.length > 0) { - namesList.push.apply(namesList, sourceMapper.names); - } - var recordSourceMapping = function (mappedPosition, nameIndex) { - if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { - return; - } - if(prevEmittedLine !== mappedPosition.emittedLine) { - while(prevEmittedLine < mappedPosition.emittedLine) { - prevEmittedColumn = 0; - mappingsString = mappingsString + ";"; - prevEmittedLine++; - } - emitComma = false; - } else { - if(emitComma) { - mappingsString = mappingsString + ","; - } - } - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); - prevEmittedColumn = mappedPosition.emittedColumn; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); - prevSourceIndex = currentSourceIndex; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); - prevSourceLine = mappedPosition.sourceLine - 1; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); - prevSourceColumn = mappedPosition.sourceColumn; - if(nameIndex >= 0) { - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); - prevNameIndex = namesCount + nameIndex; - } - emitComma = true; - recordedPosition = mappedPosition; - }; - var recordSourceMappingSiblings = function (sourceMappings) { - for(var i = 0; i < sourceMappings.length; i++) { - var sourceMapping = sourceMappings[i]; - recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); - recordSourceMappingSiblings(sourceMapping.childMappings); - recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); - } - }; - recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); - namesCount = namesCount + sourceMapper.names.length; - } - if(mappingsString != "") { - sourceMapOut.Write(JSON2.stringify({ - version: 3, - file: sourceMapper.jsFileName, - sources: tsFiles, - names: namesList, - mappings: mappingsString - })); - } - try { - sourceMapOut.Close(); - } catch (ex) { - sourceMapper.errorReporter.emitterError(null, ex.message); - } - } - return SourceMapper; - })(); - TypeScript.SourceMapper = SourceMapper; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (EmitContainer) { - EmitContainer._map = []; - EmitContainer._map[0] = "Prog"; - EmitContainer.Prog = 0; - EmitContainer._map[1] = "Module"; - EmitContainer.Module = 1; - EmitContainer._map[2] = "DynamicModule"; - EmitContainer.DynamicModule = 2; - EmitContainer._map[3] = "Class"; - EmitContainer.Class = 3; - EmitContainer._map[4] = "Constructor"; - EmitContainer.Constructor = 4; - EmitContainer._map[5] = "Function"; - EmitContainer.Function = 5; - EmitContainer._map[6] = "Args"; - EmitContainer.Args = 6; - EmitContainer._map[7] = "Interface"; - EmitContainer.Interface = 7; - })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); - var EmitContainer = TypeScript.EmitContainer; - var EmitState = (function () { - function EmitState() { - this.column = 0; - this.line = 0; - this.pretty = false; - this.inObjectLiteral = false; - this.container = EmitContainer.Prog; - } - return EmitState; - })(); - TypeScript.EmitState = EmitState; - var EmitOptions = (function () { - function EmitOptions(settings) { - this.ioHost = null; - this.outputMany = true; - this.commonDirectoryPath = ""; - this.minWhitespace = settings.minWhitespace; - this.propagateConstants = settings.propagateConstants; - this.emitComments = settings.emitComments; - this.outputOption = settings.outputOption; - } - EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { - if(this.outputMany) { - var updatedFileName = fileName; - if(this.outputOption != "") { - updatedFileName = fileName.replace(this.commonDirectoryPath, ""); - updatedFileName = this.outputOption + updatedFileName; - } - return extensionChanger(updatedFileName, false); - } else { - return extensionChanger(this.outputOption, true); - } - }; - return EmitOptions; - })(); - TypeScript.EmitOptions = EmitOptions; - var Indenter = (function () { - function Indenter() { - this.indentAmt = 0; - } - Indenter.indentStep = 4; - Indenter.indentStepString = " "; - Indenter.indentStrings = []; - Indenter.prototype.increaseIndent = function () { - this.indentAmt += Indenter.indentStep; - }; - Indenter.prototype.decreaseIndent = function () { - this.indentAmt -= Indenter.indentStep; - }; - Indenter.prototype.getIndent = function () { - var indentString = Indenter.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { - indentString += Indenter.indentStepString; - } - Indenter.indentStrings[this.indentAmt] = indentString; - } - return indentString; - }; - return Indenter; - })(); - TypeScript.Indenter = Indenter; - var Emitter = (function () { - function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { - this.checker = checker; - this.emittingFileName = emittingFileName; - this.outfile = outfile; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.prologueEmitted = false; - this.thisClassNode = null; - this.thisFnc = null; - this.moduleDeclList = []; - this.moduleName = ""; - this.emitState = new EmitState(); - this.indenter = new Indenter(); - this.ambientModule = false; - this.modAliasId = null; - this.firstModAlias = null; - this.allSourceMappers = []; - this.sourceMapper = null; - this.captureThisStmtString = "var _this = this;"; - this.varListCountStack = [ - 0 - ]; - } - Emitter.prototype.setSourceMappings = function (mapper) { - this.allSourceMappers.push(mapper); - this.sourceMapper = mapper; - }; - Emitter.prototype.writeToOutput = function (s) { - this.outfile.Write(s); - this.emitState.column += s.length; - }; - Emitter.prototype.writeToOutputTrimmable = function (s) { - if(this.emitOptions.minWhitespace) { - s = s.replace(/[\s]*/g, ''); - } - this.writeToOutput(s); - }; - Emitter.prototype.writeLineToOutput = function (s) { - if(this.emitOptions.minWhitespace) { - this.writeToOutput(s); - var c = s.charCodeAt(s.length - 1); - if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { - this.writeToOutput(' '); - } - } else { - this.outfile.WriteLine(s); - this.emitState.column = 0; - this.emitState.line++; - } - }; - Emitter.prototype.writeCaptureThisStatement = function (ast) { - this.emitIndent(); - this.recordSourceMappingStart(ast); - this.writeToOutput(this.captureThisStmtString); - this.recordSourceMappingEnd(ast); - this.writeLineToOutput(""); - }; - Emitter.prototype.setInVarBlock = function (count) { - this.varListCountStack[this.varListCountStack.length - 1] = count; - }; - Emitter.prototype.setInObjectLiteral = function (val) { - var temp = this.emitState.inObjectLiteral; - this.emitState.inObjectLiteral = val; - return temp; - }; - Emitter.prototype.setContainer = function (c) { - var temp = this.emitState.container; - this.emitState.container = c; - return temp; - }; - Emitter.prototype.getIndentString = function () { - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - Emitter.prototype.emitIndent = function () { - this.writeToOutput(this.getIndentString()); - }; - Emitter.prototype.emitCommentInPlace = function (comment) { - this.recordSourceMappingStart(comment); - var text = comment.getText(); - var hadNewLine = false; - if(comment.isBlockComment) { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.writeToOutput(text[0]); - if(text.length > 1 || comment.endsLine) { - this.writeLineToOutput(""); - for(var i = 1; i < text.length; i++) { - this.emitIndent(); - this.writeLineToOutput(text[i]); - } - hadNewLine = true; - } - } else { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.writeLineToOutput(text[0]); - hadNewLine = true; - } - if(hadNewLine) { - this.emitIndent(); - } else { - this.writeToOutput(" "); - } - this.recordSourceMappingEnd(comment); - }; - Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { - var comments = pre ? ast.preComments : ast.postComments; - if(ast.isParenthesized && !pre) { - this.writeToOutput(")"); - } - if(this.emitOptions.emitComments && comments && comments.length != 0) { - for(var i = 0; i < comments.length; i++) { - this.emitCommentInPlace(comments[i]); - } - } - if(ast.isParenthesized && pre) { - this.writeToOutput("("); - } - }; - Emitter.prototype.emitObjectLiteral = function (content) { - this.writeLineToOutput("{"); - this.indenter.increaseIndent(); - var inObjectLiteral = this.setInObjectLiteral(true); - this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); - this.setInObjectLiteral(inObjectLiteral); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - }; - Emitter.prototype.emitArrayLiteral = function (content) { - this.writeToOutput("["); - if(content) { - this.writeLineToOutput(""); - this.indenter.increaseIndent(); - this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); - this.indenter.decreaseIndent(); - this.emitIndent(); - } - this.writeToOutput("]"); - }; - Emitter.prototype.emitNew = function (target, args) { - this.writeToOutput("new "); - if(target.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = target; - if(typeRef.arrayCount) { - this.writeToOutput("Array()"); - } else { - this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); - this.writeToOutput("()"); - } - } else { - this.emitJavascript(target, TypeScript.TokenID.Tilde, false); - this.recordSourceMappingStart(args); - this.writeToOutput("("); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } - }; - Emitter.prototype.tryEmitConstant = function (dotExpr) { - if(!this.emitOptions.propagateConstants) { - return false; - } - var propertyName = dotExpr.operand2; - if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { - if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { - if(propertyName.sym.declAST) { - var boundDecl = propertyName.sym.declAST; - if(boundDecl.init && (boundDecl.init.nodeType == TypeScript.NodeType.NumberLit)) { - var numLit = boundDecl.init; - this.writeToOutput(numLit.value.toString()); - var comment = " /* "; - comment += propertyName.actualText; - comment += " */ "; - this.writeToOutput(comment); - return true; - } - } - } - } - return false; - }; - Emitter.prototype.emitCall = function (callNode, target, args) { - if(!this.emitSuperCall(callNode)) { - if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput("("); - } - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("_super.call"); - } else { - this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); - } - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput(")"); - } - this.recordSourceMappingStart(args); - this.writeToOutput("("); - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("this"); - if(args && args.members.length) { - this.writeToOutput(", "); - } - } - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } else { - this.indenter.decreaseIndent(); - this.indenter.decreaseIndent(); - var constructorCall = new TypeScript.ASTList(); - constructorCall.members[0] = callNode; - this.emitConstructorCalls(constructorCall, this.thisClassNode); - this.indenter.increaseIndent(); - this.indenter.increaseIndent(); - } - } - }; - Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - this.recordSourceMappingStart(classDecl); - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - baseSymbol = (baseExpr).target.type.symbol; - } else { - baseSymbol = baseExpr.type.symbol; - } - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.emitIndent(); - this.writeToOutput("_super.call(this"); - var args = (baseExpr).arguments; - if(args && (args.members.length > 0)) { - this.writeToOutput(", "); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - } else { - if(baseExpr.type && (baseExpr.type.isClassInstance())) { - this.emitIndent(); - this.writeToOutput(classDecl.name.actualText + "._super.constructor"); - this.writeToOutput(".call(this)"); - } - } - } - this.recordSourceMappingEnd(classDecl); - }; - Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { - var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); - var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); - this.emitParensAndCommentsInPlace(funcDecl, true); - if(shouldParenthesize) { - this.writeToOutput("("); - } - this.recordSourceMappingStart(funcDecl); - if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { - this.writeToOutput("function "); - } - if(printName) { - var id = funcDecl.getNameText(); - if(id && !funcDecl.isAccessor()) { - if(funcDecl.name) { - this.recordSourceMappingStart(funcDecl.name); - } - this.writeToOutput(id); - if(funcDecl.name) { - this.recordSourceMappingEnd(funcDecl.name); - } - } - } - this.writeToOutput("("); - var argsLen = 0; - var i = 0; - var arg; - var defaultArgs = []; - if(funcDecl.arguments) { - var tempContainer = this.setContainer(EmitContainer.Args); - argsLen = funcDecl.arguments.members.length; - var printLen = argsLen; - if(funcDecl.variableArgList) { - printLen--; - } - for(i = 0; i < printLen; i++) { - arg = funcDecl.arguments.members[i]; - if(arg.init) { - defaultArgs.push(arg); - } - this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); - if(i < (printLen - 1)) { - this.writeToOutput(", "); - } - } - this.setContainer(tempContainer); - } - this.writeLineToOutput(") {"); - if(funcDecl.isConstructor) { - this.recordSourceMappingNameStart("constructor"); - } else { - if(funcDecl.isGetAccessor()) { - this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); - } else { - if(funcDecl.isSetAccessor()) { - this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); - } else { - this.recordSourceMappingNameStart(funcDecl.getNameText()); - } - } - } - this.indenter.increaseIndent(); - for(i = 0; i < defaultArgs.length; i++) { - var arg = defaultArgs[i]; - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); - this.writeLineToOutput("; }"); - this.recordSourceMappingEnd(arg); - } - if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { - if(funcDecl.arguments) { - argsLen = funcDecl.arguments.members.length; - for(i = 0; i < argsLen; i++) { - arg = funcDecl.arguments.members[i]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - this.emitConstructorCalls(bases, classDecl); - } - } - if(hasSelfRef) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.variableArgList) { - argsLen = funcDecl.arguments.members.length; - var lastArg = funcDecl.arguments.members[argsLen - 1]; - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var "); - this.recordSourceMappingStart(lastArg.id); - this.writeToOutput(lastArg.id.actualText); - this.recordSourceMappingEnd(lastArg.id); - this.writeLineToOutput(" = [];"); - this.recordSourceMappingEnd(lastArg); - this.emitIndent(); - this.writeToOutput("for ("); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var _i = 0;"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput(" "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput("; "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i++"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(") {"); - this.indenter.increaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { - var nProps = (this.thisClassNode.members).members.length; - for(var i = 0; i < nProps; i++) { - if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(funcDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(funcDecl.endingToken); - this.recordSourceMappingEnd(funcDecl); - if(shouldParenthesize) { - this.writeToOutput(")"); - } - this.recordSourceMappingEnd(funcDecl); - this.emitParensAndCommentsInPlace(funcDecl, false); - if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition) || funcDecl.isConstructor)) { - this.writeLineToOutput(""); - } else { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { - if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { - this.writeLineToOutput(";"); - } - } - } - }; - Emitter.prototype.emitJavascriptModule = function (moduleDecl) { - var modName = moduleDecl.name.actualText; - if(TypeScript.isTSFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 3)); - } else { - if(TypeScript.isSTRFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 4)); - } - } - if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { - var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); - var prevOutFile = this.outfile; - var prevOutFileName = this.emittingFileName; - var prevAllSourceMappers = this.allSourceMappers; - var prevSourceMapper = this.sourceMapper; - var prevColumn = this.emitState.column; - var prevLine = this.emitState.line; - var temp = this.setContainer(EmitContainer.Module); - var svModuleName = this.moduleName; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; - var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); - this.moduleName = moduleDecl.name.actualText; - if(isDynamicMod) { - var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); - var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; - modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); - if(this.emitOptions.ioHost) { - if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { - this.emittingFileName = modFilePath; - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); - if(prevSourceMapper != null) { - this.allSourceMappers = []; - var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); - this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter)); - this.emitState.column = 0; - this.emitState.line = 0; - } - } else { - TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); - } - } - this.setContainer(EmitContainer.DynamicModule); - this.recordSourceMappingStart(moduleDecl); - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - var dependencyList = "[\"require\", \"exports\""; - var importList = "require, exports"; - var importStatement = null; - for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { - importStatement = (moduleDecl.mod).importedModules[i]; - if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { - if(i <= (moduleDecl.mod).importedModules.length - 1) { - dependencyList += ", "; - importList += ", "; - } - importList += "__" + importStatement.id.actualText + "__"; - dependencyList += importStatement.firstAliasedModToString(); - } - } - for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { - dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; - } - dependencyList += "]"; - this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); - } else { - } - } else { - if(!isExported) { - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("var "); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(moduleDecl); - this.emitIndent(); - } - this.writeToOutput("("); - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("function ("); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(") {"); - } - if(!isWholeFile) { - this.recordSourceMappingNameStart(this.moduleName); - } - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.increaseIndent(); - } - if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { - this.writeCaptureThisStatement(moduleDecl); - } - this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.decreaseIndent(); - } - this.emitIndent(); - if(isDynamicMod) { - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("})"); - } else { - } - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl); - if(this.outfile != prevOutFile) { - this.Close(); - if(prevSourceMapper != null) { - this.allSourceMappers = prevAllSourceMappers; - this.sourceMapper = prevSourceMapper; - this.emitState.column = prevColumn; - this.emitState.line = prevLine; - } - this.outfile = prevOutFile; - this.emittingFileName = prevOutFileName; - } - } else { - var containingMod = null; - if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { - containingMod = moduleDecl.type.symbol.container.declAST; - } - var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); - this.recordSourceMappingStart(moduleDecl.endingToken); - if(temp == EmitContainer.Prog && isExported) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); - } else { - if(isExported || temp == EmitContainer.Prog) { - var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); - } else { - if(!isExported && temp != EmitContainer.Prog) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); - } else { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")();"); - } - } - } - this.recordSourceMappingEnd(moduleDecl); - if(temp != EmitContainer.Prog && isExported) { - this.emitIndent(); - this.recordSourceMappingStart(moduleDecl); - if(parentIsDynamic) { - this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); - } else { - this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); - } - this.recordSourceMappingEnd(moduleDecl); - } - } - this.setContainer(temp); - this.moduleName = svModuleName; - this.moduleDeclList.length--; - } - }; - Emitter.prototype.emitIndex = function (operand1, operand2) { - var temp = this.setInObjectLiteral(false); - this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); - this.writeToOutput("["); - this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput("]"); - this.setInObjectLiteral(temp); - }; - Emitter.prototype.emitStringLiteral = function (text) { - this.writeToOutput(text); - }; - Emitter.prototype.emitJavascriptFunction = function (funcDecl) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { - return; - } - var temp; - var tempFnc = this.thisFnc; - this.thisFnc = funcDecl; - if(funcDecl.isConstructor) { - temp = this.setContainer(EmitContainer.Constructor); - } else { - temp = this.setContainer(EmitContainer.Function); - } - var bases = null; - var hasSelfRef = false; - var funcName = funcDecl.getNameText(); - if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { - var tempLit = this.setInObjectLiteral(false); - if(this.thisClassNode) { - bases = this.thisClassNode.extendsList; - } - hasSelfRef = Emitter.shouldCaptureThis(funcDecl); - this.recordSourceMappingStart(funcDecl); - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { - this.writeToOutput("this." + funcName + " = "); - this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); - } else { - this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); - } - this.setInObjectLiteral(tempLit); - } - this.setContainer(temp); - this.thisFnc = tempFnc; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition)) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { - if(this.thisClassNode) { - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - } else { - if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { - this.emitIndent(); - var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - } - }; - Emitter.prototype.emitAmbientVarDecl = function (varDecl) { - if(varDecl.init) { - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.recordSourceMappingEnd(varDecl); - this.writeToOutput(";"); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.varListCount = function () { - return this.varListCountStack[this.varListCountStack.length - 1]; - }; - Emitter.prototype.emitVarDeclVar = function () { - if(this.varListCount() >= 0) { - this.writeToOutput("var "); - this.setInVarBlock(-this.varListCount()); - } - return true; - }; - Emitter.prototype.onEmitVar = function () { - if(this.varListCount() > 0) { - this.setInVarBlock(this.varListCount() - 1); - } else { - if(this.varListCount() < 0) { - this.setInVarBlock(this.varListCount() + 1); - } - } - }; - Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { - if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { - this.emitAmbientVarDecl(varDecl); - this.onEmitVar(); - } else { - var sym = varDecl.sym; - var hasInitializer = (varDecl.init != null); - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { - var type = (sym.container).type; - if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { - if(this.emitState.container != EmitContainer.Args) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { - this.writeToOutput(sym.container.name + "."); - } else { - this.writeToOutput("this."); - } - } - } else { - if(type.hasImplementation()) { - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - this.emitVarDeclVar(); - } else { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { - this.writeToOutput("."); - } else { - if(this.emitState.container == EmitContainer.DynamicModule) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(this.moduleName + "."); - } - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { - this.writeToOutput("this."); - } else { - this.emitVarDeclVar(); - } - } - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - this.emitVarDeclVar(); - } - } - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - if(hasInitializer) { - this.writeToOutputTrimmable(" = "); - this.varListCountStack.push(0); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.varListCountStack.pop(); - } - this.onEmitVar(); - if((tokenId != TypeScript.TokenID.OpenParen)) { - if(this.varListCount() < 0) { - this.writeToOutput(", "); - } else { - if(tokenId != TypeScript.TokenID.For) { - this.writeToOutputTrimmable(";"); - } - } - } - this.recordSourceMappingEnd(varDecl); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.declEnclosed = function (moduleDecl) { - if(moduleDecl == null) { - return true; - } - for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { - if(this.moduleDeclList[i] == moduleDecl) { - return true; - } - } - return false; - }; - Emitter.prototype.emitJavascriptName = function (name, addThis) { - var sym = name.sym; - this.emitParensAndCommentsInPlace(name, true); - this.recordSourceMappingStart(name); - if(!name.isMissing()) { - if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { - if(sym.container && (sym.container.name != TypeScript.globalId)) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } else { - if(sym.kind() == TypeScript.SymbolKind.Field) { - var fieldSym = sym; - if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { - if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { - if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } - } else { - if(sym.isInstanceProperty()) { - this.emitThis(); - this.writeToOutput("."); - } - } - } else { - if(sym.kind() == TypeScript.SymbolKind.Type) { - if(sym.isInstanceProperty()) { - var typeSym = sym; - var type = typeSym.type; - if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { - this.emitThis(); - this.writeToOutput("."); - } - } else { - if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { - this.writeToOutput(sym.container.name + "."); - } - } - } - } - } - } else { - if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { - this.writeToOutput("this."); - } - } - } - if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { - var moduleDecl = sym.declAST; - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("__" + this.modAliasId + "__;"); - } else { - var modPath = name.actualText; - var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); - modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); - modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); - this.writeToOutput("require(" + modPath + ")"); - } - } else { - this.writeToOutput(name.actualText); - } - } - this.recordSourceMappingEnd(name); - this.emitParensAndCommentsInPlace(name, false); - }; - Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { - if(stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); - if(emitEmptyBod || hasContents) { - var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); - this.recordSourceMappingStart(stmts); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(" {"); - this.indenter.increaseIndent(); - } - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - } - this.recordSourceMappingEnd(stmts); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else { - if(emitEmptyBod) { - this.writeToOutput("{ }"); - } - } - }; - Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if(stmts.nodeType != TypeScript.NodeType.Block) { - if(stmts.nodeType == TypeScript.NodeType.List) { - var stmtList = stmts; - if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { - this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); - this.writeLineToOutput(""); - } else { - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - }; - Emitter.prototype.recordSourceMappingNameStart = function (name) { - if(this.sourceMapper) { - var finalName = name; - if(!name) { - finalName = ""; - } else { - if(this.sourceMapper.currentNameIndex.length > 0) { - finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex.length - 1] + "." + name; - } - } - this.sourceMapper.names.push(finalName); - this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); - } - }; - Emitter.prototype.recordSourceMappingNameEnd = function () { - if(this.sourceMapper) { - this.sourceMapper.currentNameIndex.pop(); - } - }; - Emitter.prototype.recordSourceMappingStart = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - var lineCol = { - line: -1, - col: -1 - }; - var sourceMapping = new TypeScript.SourceMapping(); - sourceMapping.start.emittedColumn = this.emitState.column; - sourceMapping.start.emittedLine = this.emitState.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); - sourceMapping.start.sourceColumn = lineCol.col; - sourceMapping.start.sourceLine = lineCol.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); - sourceMapping.end.sourceColumn = lineCol.col; - sourceMapping.end.sourceLine = lineCol.line; - if(this.sourceMapper.currentNameIndex.length > 0) { - sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; - } - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - siblings.push(sourceMapping); - this.sourceMapper.currentMappings.push(sourceMapping.childMappings); - } - }; - Emitter.prototype.recordSourceMappingEnd = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - this.sourceMapper.currentMappings.pop(); - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - var sourceMapping = siblings[siblings.length - 1]; - sourceMapping.end.emittedColumn = this.emitState.column; - sourceMapping.end.emittedLine = this.emitState.line; - } - }; - Emitter.prototype.Close = function () { - if(this.sourceMapper != null) { - TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); - } - try { - this.outfile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if (typeof emitPrologue === "undefined") { emitPrologue = false; } - if(ast == null) { - return; - } else { - if(ast.nodeType != TypeScript.NodeType.List) { - this.emitPrologue(emitPrologue); - this.emitJavascript(ast, tokenId, startLine); - } else { - var list = ast; - if(list.members.length == 0) { - return; - } - this.emitParensAndCommentsInPlace(ast, true); - var len = list.members.length; - for(var i = 0; i < len; i++) { - if(emitPrologue) { - if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { - this.emitPrologue(requiresExtendsBlock); - emitPrologue = false; - } - } - if(i == 1 && emitClassPropertiesAfterSuperCall) { - var constructorDecl = (this.thisClassNode).constructorDecl; - if(constructorDecl && constructorDecl.arguments) { - var argsLen = constructorDecl.arguments.members.length; - for(var iArg = 0; iArg < argsLen; iArg++) { - var arg = constructorDecl.arguments.members[iArg]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - var nProps = (this.thisClassNode.members).members.length; - for(var iMember = 0; iMember < nProps; iMember++) { - if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[iMember]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - var emitNode = list.members[i]; - var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); - if(onlyStatics ? !isStaticDecl : isStaticDecl) { - continue; - } - this.emitJavascript(emitNode, tokenId, startLine); - if(delimiter && (i < (len - 1))) { - if(startLine) { - this.writeLineToOutput(delimiter); - } else { - this.writeToOutput(delimiter); - } - } else { - if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { - this.writeLineToOutput(""); - } - } - } - this.emitParensAndCommentsInPlace(ast, false); - } - } - }; - Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { - if(ast == null) { - return; - } - if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { - if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { - this.emitIndent(); - } - } - ast.emit(this, tokenId, startLine); - if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { - this.writeToOutput(";"); - } - }; - Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { - if(!(funcDecl.accessorSymbol).hasBeenEmitted) { - var accessorSymbol = funcDecl.accessorSymbol; - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); - this.indenter.increaseIndent(); - if(accessorSymbol.getter) { - var getter = accessorSymbol.getter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(getter); - this.writeToOutput("get: "); - this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); - this.writeLineToOutput(","); - } - if(accessorSymbol.setter) { - var setter = accessorSymbol.setter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(setter); - this.writeToOutput("set: "); - this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); - this.writeLineToOutput(","); - } - this.emitIndent(); - this.writeLineToOutput("enumerable: true,"); - this.emitIndent(); - this.writeLineToOutput("configurable: true"); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("});"); - this.recordSourceMappingEnd(funcDecl); - accessorSymbol.hasBeenEmitted = true; - } - }; - Emitter.prototype.emitPrototypeMember = function (member, className) { - if(member.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = member; - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, className, true); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); - this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); - this.writeLineToOutput(";"); - } - } else { - if(member.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = member; - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(className + ".prototype." + varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.recordSourceMappingEnd(varDecl); - this.writeLineToOutput(";"); - } - } - } - }; - Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { - if(base.members) { - var baseSymbol = base.symbol; - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - base.members.allMembers.map(function (key, s, c) { - var sym = s; - if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { - this.recordSourceMappingStart(sym.declAST); - this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); - this.recordSourceMappingEnd(sym.declAST); - } - }, null); - } - if(base.extendsList) { - for(var i = 0, len = base.extendsList.length; i < len; i++) { - this.emitAddBaseMethods(className, base.extendsList[i], classDecl); - } - } - }; - Emitter.prototype.emitJavascriptClass = function (classDecl) { - if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { - var svClassNode = this.thisClassNode; - var i = 0; - this.thisClassNode = classDecl; - var className = classDecl.name.actualText; - this.emitParensAndCommentsInPlace(classDecl, true); - var temp = this.setContainer(EmitContainer.Class); - this.recordSourceMappingStart(classDecl); - if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { - this.writeToOutput("this." + className); - } else { - this.writeToOutput("var " + className); - } - var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; - var baseNameDecl = null; - var baseName = null; - if(hasBaseClass) { - this.writeLineToOutput(" = (function (_super) {"); - } else { - this.writeLineToOutput(" = (function () {"); - } - this.recordSourceMappingNameStart(className); - this.indenter.increaseIndent(); - if(hasBaseClass) { - baseNameDecl = classDecl.extendsList.members[0]; - baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; - this.emitIndent(); - this.writeLineToOutput("__extends(" + className + ", _super);"); - } - this.emitIndent(); - var constrDecl = classDecl.constructorDecl; - if(constrDecl) { - this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); - } else { - var wroteProps = 0; - this.recordSourceMappingStart(classDecl); - this.indenter.increaseIndent(); - this.writeToOutput("function " + classDecl.name.actualText + "() {"); - this.recordSourceMappingNameStart("constructor"); - if(hasBaseClass) { - this.writeLineToOutput(""); - this.emitIndent(); - this.writeLineToOutput("_super.apply(this, arguments);"); - wroteProps++; - } - if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { - this.writeCaptureThisStatement(classDecl); - } - var members = (this.thisClassNode.members).members; - for(var i = 0; i < members.length; i++) { - if(members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.writeLineToOutput(""); - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - wroteProps++; - } - } - } - if(wroteProps) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } else { - this.writeLineToOutput(" }"); - this.indenter.decreaseIndent(); - } - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl); - } - var membersLen = classDecl.members.members.length; - for(var j = 0; j < membersLen; j++) { - var memberDecl = classDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var fn = memberDecl; - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { - if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { - this.emitPrototypeMember(fn, className); - } else { - if(fn.isAccessor()) { - this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(fn); - this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); - this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); - this.writeLineToOutput(";"); - } - } - } - } else { - if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = memberDecl; - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(varDecl); - } - } - } else { - throw Error("We want to catch this"); - } - } - } - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeLineToOutput("return " + className + ";"); - this.recordSourceMappingEnd(classDecl.endingToken); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl.endingToken); - this.recordSourceMappingStart(classDecl); - this.writeToOutput(")("); - if(hasBaseClass) { - this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); - } - this.writeToOutput(");"); - this.recordSourceMappingEnd(classDecl); - if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { - this.writeLineToOutput(""); - this.emitIndent(); - var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(classDecl); - this.writeToOutput(modName + "." + className + " = " + className + ";"); - this.recordSourceMappingEnd(classDecl); - } - this.emitIndent(); - this.recordSourceMappingEnd(classDecl); - this.emitParensAndCommentsInPlace(classDecl, false); - this.setContainer(temp); - this.thisClassNode = svClassNode; - } - }; - Emitter.prototype.emitPrologue = function (reqInherits) { - if(!this.prologueEmitted) { - if(reqInherits) { - this.prologueEmitted = true; - this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); - this.writeLineToOutput(" function __() { this.constructor = d; }"); - this.writeLineToOutput(" __.prototype = b.prototype;"); - this.writeLineToOutput(" d.prototype = new __();"); - this.writeLineToOutput("};"); - } - if(this.checker.mustCaptureGlobalThis) { - this.prologueEmitted = true; - this.writeLineToOutput(this.captureThisStmtString); - } - } - }; - Emitter.prototype.emitSuperReference = function () { - this.writeToOutput("_super.prototype"); - }; - Emitter.prototype.emitSuperCall = function (callEx) { - if(callEx.target.nodeType == TypeScript.NodeType.Dot) { - var dotNode = callEx.target; - if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { - this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); - this.writeToOutput(".call("); - this.emitThis(); - if(callEx.arguments && callEx.arguments.members.length > 0) { - this.writeToOutput(", "); - this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - return true; - } - } - return false; - }; - Emitter.prototype.emitThis = function () { - if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { - this.writeToOutput("_this"); - } else { - this.writeToOutput("this"); - } - }; - Emitter.shouldCaptureThis = function shouldCaptureThis(func) { - return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); - } - Emitter.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitOptions.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return Emitter; - })(); - TypeScript.Emitter = Emitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ErrorReporter = (function () { - function ErrorReporter(outfile) { - this.outfile = outfile; - this.parser = null; - this.checker = null; - this.lineCol = { - line: 0, - col: 0 - }; - this.emitAsComments = true; - this.hasErrors = false; - this.pushToErrorSink = false; - this.errorSink = []; - } - ErrorReporter.prototype.getCapturedErrors = function () { - return this.errorSink; - }; - ErrorReporter.prototype.freeCapturedErrors = function () { - this.errorSink = []; - }; - ErrorReporter.prototype.captureError = function (emsg) { - this.errorSink[this.errorSink.length] = emsg; - }; - ErrorReporter.prototype.setErrOut = function (outerr) { - this.outfile = outerr; - this.emitAsComments = false; - }; - ErrorReporter.prototype.emitPrefix = function () { - if(this.emitAsComments) { - this.outfile.Write("// "); - } - this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); - }; - ErrorReporter.prototype.writePrefix = function (ast) { - if(ast) { - this.setError(ast); - } else { - this.lineCol.line = 0; - this.lineCol.col = 0; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.writePrefixFromSym = function (symbol) { - if(symbol && this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); - } else { - this.lineCol.line = -1; - this.lineCol.col = -1; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.setError = function (ast) { - if(ast) { - ast.flags |= TypeScript.ASTFlags.Error; - if(this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); - } - } - }; - ErrorReporter.prototype.reportError = function (ast, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(ast && this.parser.errorRecovery && this.parser.errorCallback) { - var len = (ast.limChar - ast.minChar); - this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefix(ast); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(this.parser.errorRecovery && this.parser.errorCallback) { - this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefixFromSym(symbol); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.emitterError = function (ast, message) { - this.reportError(ast, message); - throw Error("EmitError"); - }; - ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { - this.reportError(ast, "Duplicate identifier '" + name + "'"); - }; - ErrorReporter.prototype.showRef = function (ast, text, symbol) { - var defLineCol = { - line: -1, - col: -1 - }; - this.parser.getSourceLineCol(defLineCol, symbol.location); - this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); - }; - ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); - }; - ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not refer to a value"); - }; - ErrorReporter.prototype.styleError = function (ast, msg) { - var bkThrow = this.pushToErrorSink; - this.pushToErrorSink = false; - this.reportError(ast, "STYLE: " + msg); - this.pushToErrorSink = bkThrow; - }; - ErrorReporter.prototype.simpleError = function (ast, msg) { - this.reportError(ast, msg); - }; - ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { - this.reportErrorFromSym(sym, msg); - }; - ErrorReporter.prototype.invalidSuperReference = function (ast) { - this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); - }; - ErrorReporter.prototype.valueCannotBeModified = function (ast) { - this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); - }; - ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { - var targetType = ast.target.type; - var typeName = targetType.getScopedTypeName(scope); - if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { - this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); - } else { - var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; - this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); - } - }; - ErrorReporter.prototype.indexLHS = function (ast, scope) { - var targetType = ast.operand1.type.getScopedTypeName(scope); - var indexType = ast.operand2.type.getScopedTypeName(scope); - this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); - }; - ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { - if(!t1) { - t1 = this.checker.anyType; - } - if(!t2) { - t2 = this.checker.anyType; - } - var reason = comparisonInfo ? comparisonInfo.message : ""; - if(op) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } else { - this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } - }; - ErrorReporter.prototype.expectedClassOrInterface = function (ast) { - this.simpleError(ast, "Expected var, class, interface, or module"); - }; - ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); - }; - return ErrorReporter; - })(); - TypeScript.ErrorReporter = ErrorReporter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeContext) { - TypeContext._map = []; - TypeContext.NoTypes = 0; - TypeContext.ArraySuffix = 1; - TypeContext.Primitive = 2; - TypeContext.Named = 4; - TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; - TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; - })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); - var TypeContext = TypeScript.TypeContext; - (function (ParseState) { - ParseState._map = []; - ParseState._map[0] = "None"; - ParseState.None = 0; - ParseState._map[1] = "StartScript"; - ParseState.StartScript = 1; - ParseState._map[2] = "StartStatementList"; - ParseState.StartStatementList = 2; - ParseState._map[3] = "StartStatement"; - ParseState.StartStatement = 3; - ParseState._map[4] = "StartFncDecl"; - ParseState.StartFncDecl = 4; - ParseState._map[5] = "FncDeclName"; - ParseState.FncDeclName = 5; - ParseState._map[6] = "FncDeclArgs"; - ParseState.FncDeclArgs = 6; - ParseState._map[7] = "FncDeclReturnType"; - ParseState.FncDeclReturnType = 7; - ParseState._map[8] = "ForInit"; - ParseState.ForInit = 8; - ParseState._map[9] = "ForInitAfterVar"; - ParseState.ForInitAfterVar = 9; - ParseState._map[10] = "ForCondStart"; - ParseState.ForCondStart = 10; - ParseState._map[11] = "EndStmtList"; - ParseState.EndStmtList = 11; - ParseState._map[12] = "EndScript"; - ParseState.EndScript = 12; - })(TypeScript.ParseState || (TypeScript.ParseState = {})); - var ParseState = TypeScript.ParseState; - var QuickParseResult = (function () { - function QuickParseResult(Script, endLexState) { - this.Script = Script; - this.endLexState = endLexState; - } - return QuickParseResult; - })(); - TypeScript.QuickParseResult = QuickParseResult; - var Parser = (function () { - function Parser() { - this.varLists = []; - this.scopeLists = []; - this.staticsLists = []; - this.scanner = new TypeScript.Scanner(); - this.currentToken = null; - this.needTerminator = false; - this.inFunction = false; - this.inInterfaceDecl = false; - this.currentClassDecl = null; - this.inFncDecl = false; - this.anonId = new TypeScript.Identifier("_anonymous"); - this.style_requireSemi = false; - this.style_funcInLoop = true; - this.incremental = false; - this.errorRecovery = false; - this.outfile = undefined; - this.errorCallback = null; - this.state = ParseState.StartStatementList; - this.ambientModule = false; - this.ambientClass = false; - this.topLevel = true; - this.allowImportDeclaration = true; - this.currentUnitIndex = (-1); - this.prevIDTok = null; - this.statementInfoStack = new Array(); - this.hasTopLevelImportOrExport = false; - this.strictMode = false; - this.nestingLevel = 0; - this.prevExpr = null; - this.currentClassDefinition = null; - this.parsingClassConstructorDefinition = false; - this.parsingDeclareFile = false; - this.amdDependencies = []; - this.inferPropertiesFromThisAssignment = false; - this.requiresExtendsBlock = false; - this.fname = ""; - } - Parser.prototype.resetStmtStack = function () { - this.statementInfoStack = new Array(); - }; - Parser.prototype.inLoop = function () { - for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { - if(this.statementInfoStack[j].stmt.isLoop()) { - return true; - } - } - return false; - }; - Parser.prototype.pushStmt = function (stmt, labels) { - var info = { - stmt: stmt, - labels: labels - }; - this.statementInfoStack.push(info); - }; - Parser.prototype.popStmt = function () { - return this.statementInfoStack.pop(); - }; - Parser.prototype.resolveJumpTarget = function (jump) { - var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); - var len = this.statementInfoStack.length; - for(var i = len - 1; i >= 0; i--) { - var info = this.statementInfoStack[i]; - if(jump.target) { - if(info.labels && (info.labels.members.length > 0)) { - for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { - var label = info.labels.members[j]; - if(label.id.text == resolvedTarget) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - } else { - if(info.stmt.isLoop()) { - jump.setResolvedTarget(this, info.stmt); - return; - } else { - if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - } - if(jump.target) { - this.reportParseError("could not find enclosing statement with label " + jump.target); - } else { - if(jump.nodeType == TypeScript.NodeType.Break) { - this.reportParseError("break statement requires enclosing loop or switch"); - } else { - this.reportParseError("continue statement requires enclosing loop"); - } - } - }; - Parser.prototype.setErrorRecovery = function (outfile) { - this.outfile = outfile; - this.errorRecovery = true; - }; - Parser.prototype.getSourceLineCol = function (lineCol, minChar) { - TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); - }; - Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { - var id = new TypeScript.Identifier(text, hasEscapeSequence); - id.minChar = minChar; - return id; - }; - Parser.prototype.reportParseStyleError = function (message) { - this.reportParseError("STYLE: " + message); - }; - Parser.prototype.reportParseError = function (message, startPos, pos) { - if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } - if (typeof pos === "undefined") { pos = this.scanner.pos; } - var len = Math.max(1, pos - startPos); - if(this.errorCallback) { - this.errorCallback(startPos, len, message, this.currentUnitIndex); - } else { - if(this.errorRecovery) { - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, startPos); - if(this.outfile) { - this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); - } - } else { - throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); - } - } - }; - Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(tokenId, errorRecoverySet, errorText); - }; - Parser.prototype.skip = function (errorRecoverySet) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; - var ersTok = TypeScript.ErrorRecoverySet.None; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - var pendingRightCurlies = 0; - while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { - if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - pendingRightCurlies++; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - pendingRightCurlies--; - } - } - this.currentToken = this.scanner.scan(); - ersTok = TypeScript.ErrorRecoverySet.None; - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - } - }; - Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - if(this.currentToken.tokenId != tokenId) { - errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; - this.reportParseError(errorText); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - } - } else { - this.currentToken = this.scanner.scan(); - } - }; - Parser.prototype.pushDeclLists = function () { - this.staticsLists.push(new TypeScript.ASTList()); - this.varLists.push(new TypeScript.ASTList()); - this.scopeLists.push(new TypeScript.ASTList()); - }; - Parser.prototype.popDeclLists = function () { - this.staticsLists.pop(); - this.varLists.pop(); - this.scopeLists.pop(); - }; - Parser.prototype.topVarList = function () { - return this.varLists[this.varLists.length - 1]; - }; - Parser.prototype.topScopeList = function () { - return this.scopeLists[this.scopeLists.length - 1]; - }; - Parser.prototype.topStaticsList = function () { - return this.staticsLists[this.staticsLists.length - 1]; - }; - Parser.prototype.parseComment = function (comment) { - if(comment) { - var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); - c.minChar = comment.startPos; - c.limChar = comment.startPos + comment.value.length; - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, c.minChar); - c.minLine = lineCol.line; - this.getSourceLineCol(lineCol, c.limChar); - c.limLine = lineCol.line; - if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { - var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); - if(dependencyPath) { - this.amdDependencies.push(dependencyPath); - } - if(TypeScript.getImplicitImport(comment.value)) { - this.hasTopLevelImportOrExport = true; - } - } - return c; - } else { - return null; - } - }; - Parser.prototype.parseCommentsInner = function (comments) { - if(comments) { - var commentASTs = new Array(); - for(var i = 0; i < comments.length; i++) { - commentASTs.push(this.parseComment(comments[i])); - } - return commentASTs; - } else { - return null; - } - }; - Parser.prototype.parseComments = function () { - var comments = this.scanner.getComments(); - return this.parseCommentsInner(comments); - }; - Parser.prototype.parseCommentsForLine = function (line) { - var comments = this.scanner.getCommentsForLine(line); - return this.parseCommentsInner(comments); - }; - Parser.prototype.combineComments = function (comment1, comment2) { - if(comment1 == null) { - return comment2; - } else { - if(comment2 == null) { - return comment1; - } else { - return comment1.concat(comment2); - } - } - }; - Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Enum declaration requires identifier"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.startPos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - this.pushDeclLists(); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); - mapDecl.varFlags |= TypeScript.VarFlags.Exported; - mapDecl.varFlags |= TypeScript.VarFlags.Private; - mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); - mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); - members.append(mapDecl); - var lastValue = null; - for(; ; ) { - var minChar = this.scanner.startPos; - var limChar; - var memberName = null; - var memberValue = null; - var preComments = null; - var postComments = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } else { - this.reportParseError("Expected identifer of enum member"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - } - } - } - limChar = this.scanner.pos; - preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - postComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - this.currentToken = this.scanner.scan(); - memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - lastValue = memberValue; - limChar = memberValue.limChar; - } else { - if(lastValue == null) { - memberValue = new TypeScript.NumberLiteral(0); - lastValue = memberValue; - } else { - memberValue = new TypeScript.NumberLiteral(lastValue.value + 1); - lastValue = memberValue; - } - var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); - members.append(map); - } - var member = new TypeScript.VarDecl(memberName, this.nestingLevel); - member.minChar = minChar; - member.limChar = limChar; - member.init = memberValue; - member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); - member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); - if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { - member.varFlags |= TypeScript.VarFlags.Constant; - } - member.preComments = preComments; - members.append(member); - member.postComments = postComments; - member.varFlags |= TypeScript.VarFlags.Exported; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { - continue; - } - } - break; - } - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - members.limChar = this.scanner.lastTokenLimChar(); - var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), this.topScopeList(), endingToken); - modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; - this.popDeclLists(); - modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return modDecl; - }; - Parser.prototype.parseDottedName = function (enclosedList) { - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.preComments = this.parseComments(); - enclosedList[enclosedList.length] = id; - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - this.parseDottedName(enclosedList); - } - } else { - this.reportParseError("need identifier after '.'"); - } - }; - Parser.prototype.isValidImportPath = function (importPath) { - importPath = TypeScript.stripQuotes(importPath); - if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { - return false; - } - return true; - }; - Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { - var name = null; - var alias = null; - var importDecl = null; - var minChar = this.scanner.startPos; - var isDynamicImport = false; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - } else { - this.reportParseError("Expected identifer after 'import'"); - name = new TypeScript.MissingIdentifier(); - } - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - var aliasPreComments = this.parseComments(); - var limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Module) { - limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } else { - if(!this.allowImportDeclaration) { - this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); - } - } - var aliasText = this.currentToken.getText(); - alias = TypeScript.Identifier.fromToken(this.currentToken); - alias.minChar = this.scanner.startPos; - alias.limChar = this.scanner.pos; - if(!this.isValidImportPath((alias).text)) { - this.reportParseError("Invalid import path"); - } - isDynamicImport = true; - this.currentToken = this.scanner.scan(); - alias.preComments = aliasPreComments; - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - alias.preComments = aliasPreComments; - } - } - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(alias) { - alias.postComments = this.parseComments(); - } - } - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - limChar = this.scanner.pos; - } - } else { - this.reportParseError("Expected module name"); - alias = new TypeScript.MissingIdentifier(); - alias.minChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - alias.limChar = this.scanner.startPos; - } else { - alias.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - alias.flags |= TypeScript.ASTFlags.Error; - limChar = alias.limChar; - } - importDecl = new TypeScript.ImportDeclaration(name, alias); - importDecl.isDynamicImport = isDynamicImport; - importDecl.minChar = minChar; - importDecl.limChar = limChar; - return importDecl; - }; - Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var svAmbient = this.ambientModule; - var svTopLevel = this.topLevel; - this.topLevel = false; - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.ambientModule = true; - } - this.currentToken = this.scanner.scan(); - var name = null; - var enclosedList = null; - this.pushDeclLists(); - var minChar = this.scanner.startPos; - var isDynamicMod = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var nameText = this.currentToken.getText(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - isDynamicMod = true; - if(!this.ambientModule) { - this.reportParseError("Only ambient dynamic modules may have string literal names"); - } - if(!svTopLevel) { - this.reportParseError("Dynamic modules may not be nested within other modules"); - } - } - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - this.reportParseError("Module name missing"); - name = new TypeScript.Identifier(""); - name.minChar = minChar; - name.limChar = minChar; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - enclosedList = new Array(); - this.parseDottedName(enclosedList); - } - if(name == null) { - name = new TypeScript.MissingIdentifier(); - } - var moduleBody = new TypeScript.ASTList(); - var bodyMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(svTopLevel && isDynamicMod) { - this.allowImportDeclaration = true; - } else { - this.allowImportDeclaration = false; - } - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); - moduleBody.minChar = bodyMinChar; - moduleBody.limChar = this.scanner.pos; - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var limChar = this.scanner.lastTokenLimChar(); - var moduleDecl; - this.allowImportDeclaration = svTopLevel; - if(enclosedList && (enclosedList.length > 0)) { - var len = enclosedList.length; - var innerName = enclosedList[len - 1]; - var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), this.topScopeList(), endingToken); - innerDecl.preComments = preComments; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - innerDecl.minChar = minChar; - innerDecl.limChar = limChar; - this.popDeclLists(); - var outerModBod; - for(var i = len - 2; i >= 0; i--) { - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - innerName = enclosedList[i]; - innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); - outerModBod.minChar = innerDecl.minChar = minChar; - outerModBod.limChar = innerDecl.limChar = limChar; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - outerModBod.minChar = minChar; - outerModBod.limChar = limChar; - moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); - } else { - moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), this.topScopeList(), endingToken); - moduleDecl.preComments = preComments; - this.popDeclLists(); - } - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - if(isDynamicMod) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; - } - this.ambientModule = svAmbient; - this.topLevel = svTopLevel; - moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - moduleDecl.limChar = moduleBody.limChar; - return moduleDecl; - }; - Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { - var result = new TypeScript.TypeReference(term, 0); - result.minChar = minChar; - while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { - this.currentToken = this.scanner.scan(); - result.arrayCount++; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); - } - result.limChar = this.scanner.lastTokenLimChar(); - return result; - }; - Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var op2 = TypeScript.Identifier.fromToken(this.currentToken); - op2.minChar = this.scanner.startPos; - op2.limChar = this.scanner.pos; - var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); - dotNode.minChar = term.minChar; - dotNode.limChar = op2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); - } else { - this.reportParseError("need identifier after '.'"); - if(this.errorRecovery) { - term.flags |= TypeScript.ASTFlags.DotLHS; - term.limChar = this.scanner.lastTokenLimChar(); - return term; - } else { - var eop2 = new TypeScript.MissingIdentifier(); - eop2.minChar = this.scanner.pos; - eop2.limChar = this.scanner.pos; - var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); - edotNode.flags |= TypeScript.ASTFlags.Error; - edotNode.minChar = term.minChar; - edotNode.limChar = eop2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); - } - } - } else { - if(tail) { - return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); - } else { - return term; - } - } - }; - Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { - var minChar = this.scanner.startPos; - var isConstructorMember = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Void: { - if(!allowVoid) { - this.reportParseError("void not a valid type in this context"); - } - - } - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.String: { - var text = TypeScript.tokenTable[this.currentToken.tokenId].text; - var predefinedIdentifier = new TypeScript.Identifier(text); - predefinedIdentifier.minChar = minChar; - predefinedIdentifier.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); - } - - case TypeScript.TokenID.Identifier: { - var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); - ident.limChar = this.scanner.pos; - return this.parseNamedType(errorRecoverySet, minChar, ident, true); - - } - case TypeScript.TokenID.OpenBrace: { - return this.parseObjectType(minChar, errorRecoverySet); - - } - case TypeScript.TokenID.New: { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { - this.reportParseError("Expected '('"); - } else { - isConstructorMember = true; - } - - } - case TypeScript.TokenID.OpenParen: { - var formals = new TypeScript.ASTList(); - var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); - this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); - var returnType = this.parseTypeReference(errorRecoverySet, true); - var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); - funcDecl.returnTypeAnnotation = returnType; - funcDecl.variableArgList = variableArgList; - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - if(isConstructorMember) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = null; - } - funcDecl.minChar = minChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); - } - - default: { - this.reportParseError("Expected type name"); - var etr = new TypeScript.TypeReference(null, 0); - etr.flags |= TypeScript.ASTFlags.Error; - etr.minChar = this.scanner.pos; - etr.limChar = this.scanner.pos; - return etr; - - } - } - }; - Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { - this.currentToken = this.scanner.scan(); - var members = new TypeScript.ASTList(); - members.minChar = minChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); - interfaceDecl.minChar = minChar; - interfaceDecl.limChar = members.limChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); - }; - Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { - this.state = ParseState.StartStatementList; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - var savedInFunction = this.inFunction; - this.inFunction = true; - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); - bod.minChar = bodMinChar; - bod.limChar = this.scanner.pos; - this.inFunction = savedInFunction; - var ec = new TypeScript.EndCode(); - ec.minChar = bod.limChar; - ec.limChar = ec.minChar; - bod.append(ec); - }; - Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { - this.pushDeclLists(); - var svStmtStack = this.statementInfoStack; - this.resetStmtStack(); - var bod = null; - var wasShorthand = false; - var isAnonLambda = false; - var limChar; - if(requiresSignature) { - limChar = this.scanner.pos; - if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { - this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - } else { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); - } - } else { - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { - if(isMethod) { - this.reportParseError("'=>' may not be used for class methods"); - } - wasShorthand = true; - this.currentToken = this.scanner.scan(); - } - if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.returnExpression = retExpr; - retStmt.minChar = retExpr.minChar; - retStmt.limChar = retExpr.limChar; - bod.minChar = bodMinChar; - bod.append(retStmt); - } else { - isAnonLambda = wasShorthand; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - } - limChar = this.scanner.pos; - } - var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); - this.popDeclLists(); - var scopeList = this.topScopeList(); - scopeList.append(funcDecl); - var staticFuncDecl = false; - if(!requiresSignature) { - if(!wasShorthand || isAnonLambda) { - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = this.scanner.startPos; - funcDecl.endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(isAnonLambda) { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - } - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = bod.members[0].minChar; - funcDecl.endingToken.limChar = bod.members[0].limChar; - } - } - funcDecl.minChar = minChar; - funcDecl.limChar = limChar; - if(!requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Definition; - } - this.statementInfoStack = svStmtStack; - return funcDecl; - }; - Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { - var _this = this; - var translateBinExOperand = function (operand) { - if(operand.nodeType == TypeScript.NodeType.Comma) { - return _this.transformAnonymousArgsIntoFormals(formals, operand); - } else { - if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { - var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; - var arg = new TypeScript.ArgDecl(opArg); - arg.preComments = opArg.preComments; - arg.postComments = opArg.postComments; - arg.minChar = operand.minChar; - arg.limChar = operand.limChar; - if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - arg.isOptional = true; - } - if(operand.nodeType == TypeScript.NodeType.Asg) { - arg.init = (operand).operand2; - } - formals.append(arg); - return arg.isOptional || arg.init; - } else { - _this.reportParseError("Invalid lambda argument"); - } - } - return false; - }; - if(argList) { - if(argList.nodeType == TypeScript.NodeType.Comma) { - var commaList = argList; - if(commaList.operand1.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); - } - if(commaList.operand2.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); - } - var isOptional = translateBinExOperand(commaList.operand1); - isOptional = translateBinExOperand(commaList.operand2) || isOptional; - return isOptional; - } else { - return translateBinExOperand(argList); - } - } - }; - Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { - formals.minChar = this.scanner.startPos; - if(isIndexer) { - this.currentToken = this.scanner.scan(); - } else { - if(!isLambda) { - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); - } - } - var sawEllipsis = false; - var firstArg = true; - var hasOptional = false; - var haveFirstArgID = false; - if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { - hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); - haveFirstArgID = true; - } - while(true) { - var munchedArg = false; - var argFlags = TypeScript.VarFlags.None; - var argMinChar = this.scanner.startPos; - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { - this.reportParseError("Static properties can not be declared as parameter properties"); - this.currentToken = this.scanner.scan(); - } - } - } - if(argFlags != TypeScript.VarFlags.None) { - if(!isClassConstr) { - this.reportParseError("only constructor parameters can be properties"); - } - this.currentToken = this.scanner.scan(); - if(TypeScript.isModifier(this.currentToken)) { - this.reportParseError("Multiple modifiers may not be applied to parameters"); - this.currentToken = this.scanner.scan(); - } - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - this.currentToken = this.scanner.scan(); - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - sawEllipsis = true; - this.currentToken = this.scanner.scan(); - if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - sawEllipsis = false; - } - } - } - var argId = null; - if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - argId = TypeScript.Identifier.fromToken(this.currentToken); - argId.minChar = this.scanner.startPos; - argId.limChar = this.scanner.pos; - } - if(haveFirstArgID || argId) { - munchedArg = true; - var type = null; - var arg = null; - if(haveFirstArgID && formals.members.length) { - arg = formals.members[formals.members.length - 1]; - if(arg.isOptional) { - hasOptional = true; - } - } else { - arg = new TypeScript.ArgDecl(argId); - if(isGetter) { - this.reportParseError("Property getters may not take any arguments"); - } - if(isSetter && !firstArg) { - this.reportParseError("Property setters may only take one argument"); - } - arg.minChar = argMinChar; - arg.preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - arg.isOptional = true; - hasOptional = true; - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - type = this.parseTypeReference(errorRecoverySet, false); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(isSig) { - this.reportParseError("Arguments in signatures may not have default values"); - } - hasOptional = true; - this.currentToken = this.scanner.scan(); - arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); - } - if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { - this.reportParseError("Optional parameters may only be followed by other optional parameters"); - } - if(sawEllipsis && arg.isOptionalArg()) { - this.reportParseError("Varargs may not be optional or have default parameters"); - } - if(sawEllipsis && !type) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - } - arg.postComments = this.parseComments(); - arg.typeExpr = type; - arg.limChar = this.scanner.lastTokenLimChar(); - arg.varFlags |= argFlags; - if(!haveFirstArgID) { - formals.append(arg); - } else { - haveFirstArgID = false; - } - } - firstArg = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - if((munchedArg) && (!sawEllipsis)) { - this.currentToken = this.scanner.scan(); - continue; - } else { - this.reportParseError("Unexpected ',' in argument list"); - if(this.errorRecovery) { - this.currentToken = this.scanner.scan(); - continue; - } - } - } else { - break; - } - } - if(isIndexer) { - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } else { - if(expectClosingRParen) { - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } - } - formals.limChar = this.scanner.lastTokenLimChar(); - return sawEllipsis; - }; - Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var prevInConstr = this.parsingClassConstructorDefinition; - this.parsingClassConstructorDefinition = false; - var name = null; - var fnMin = this.scanner.startPos; - var minChar = this.scanner.pos; - var prevNestingLevel = this.nestingLevel; - var preComments = this.parseComments(); - var isLambda = !!lambdaArgContext; - this.nestingLevel = 0; - if((!this.style_funcInLoop) && this.inLoop()) { - this.reportParseStyleError("function declaration in loop"); - } - if(!isMethod && !isStatic && !indexer && !lambdaArgContext) { - this.currentToken = this.scanner.scan(); - this.state = ParseState.StartFncDecl; - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - if(isDecl) { - this.reportParseError("Function declaration must include identifier"); - this.nestingLevel = prevNestingLevel; - return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); - } - } else { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } else { - if(methodName) { - name = methodName; - } - } - this.state = ParseState.FncDeclName; - var args = new TypeScript.ASTList(); - var variableArgList = false; - var isOverload = false; - var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); - var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); - } - this.state = ParseState.FncDeclArgs; - var returnType = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { - this.reportParseError("Property setters may not declare a return type"); - } - returnType = this.parseTypeReference(errorRecoverySet, true); - } - if(indexer && args.members.length == 0) { - this.reportParseError("Index signatures require a parameter type to be specified"); - } - this.state = ParseState.FncDeclReturnType; - if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { - this.reportParseError("Expected '=>'"); - } - if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && (!isMethod || !(this.ambientModule || this.ambientClass || this.inInterfaceDecl)) && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - isOverload = true; - isDecl = false; - requiresSignature = true; - } - var svInFncDecl = this.inFncDecl; - this.inFncDecl = true; - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); - this.inFncDecl = svInFncDecl; - funcDecl.variableArgList = variableArgList; - funcDecl.isOverload = isOverload; - if(!requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Definition; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(indexer) { - funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; - } - funcDecl.returnTypeAnnotation = returnType; - if(isMethod) { - funcDecl.fncFlags |= TypeScript.FncFlags.Method; - funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; - } - funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - this.nestingLevel = prevNestingLevel; - this.parsingClassConstructorDefinition = prevInConstr; - funcDecl.preComments = preComments; - return funcDecl; - }; - Parser.prototype.convertToTypeReference = function (ast) { - var result; - switch(ast.nodeType) { - case TypeScript.NodeType.TypeRef: { - return ast; - - } - case TypeScript.NodeType.Name: { - result = new TypeScript.TypeReference(ast, 0); - result.minChar = ast.minChar; - result.limChar = ast.limChar; - return result; - - } - case TypeScript.NodeType.Index: { - var expr = ast; - result = this.convertToTypeReference(expr.operand1); - if(result) { - result.arrayCount++; - result.minChar = expr.minChar; - result.limChar = expr.limChar; - return result; - } else { - var etr = new TypeScript.AST(TypeScript.NodeType.Error); - return etr; - } - } - - } - return null; - }; - Parser.prototype.parseArgList = function (errorRecoverySet) { - var args = new TypeScript.ASTList(); - args.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { - while(true) { - if(args.members.length > 65535) { - this.reportParseError("max number of args exceeded"); - break; - } - var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - args.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - } - args.limChar = this.scanner.pos; - return args; - }; - Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { - var keyword = true; - var currentList = extendsList; - for(; ; ) { - if(keyword) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - currentList = implementsList; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - } - this.currentToken = this.scanner.scan(); - keyword = false; - } - var baseName = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var minChar = this.scanner.startPos; - baseName = TypeScript.Identifier.fromToken(this.currentToken); - baseName.minChar = minChar; - baseName.limChar = this.scanner.pos; - baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); - } else { - this.reportParseError("Expected base name"); - if(this.errorRecovery) { - baseName = new TypeScript.MissingIdentifier(); - baseName.minChar = this.scanner.pos; - baseName.limChar = this.scanner.pos; - baseName.flags |= TypeScript.ASTFlags.Error; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - if(isClass) { - this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); - } else { - this.reportParseError("Interfaces may not be extended with a call expression"); - } - } else { - currentList.append(baseName); - } - if(isClass && currentList == extendsList && extendsList.members.length > 1) { - this.reportParseError("A class may only extend one other class"); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - continue; - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - currentList = extendsList; - keyword = true; - continue; - } - } - break; - } - }; - Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - this.reportParseError("const modifier is implicit for class"); - } - if(this.parsingDeclareFile || this.ambientModule) { - modifiers |= TypeScript.Modifiers.Ambient; - modifiers |= TypeScript.Modifiers.Exported; - } - var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; - var svAmbientClass = this.ambientClass; - this.ambientClass = classIsMarkedAsAmbient; - this.currentToken = this.scanner.scan(); - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("class missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - var requiresSignature = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); - } - var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); - this.currentClassDefinition = classDecl; - this.parseClassElements(classDecl, errorRecoverySet, modifiers); - if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - classDecl.varFlags |= TypeScript.VarFlags.Exported; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - classDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - classDecl.varFlags |= TypeScript.VarFlags.Class; - this.ambientClass = svAmbientClass; - classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return classDecl; - }; - Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { - var modifiers = parentModifiers; - var resetModifiers = false; - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); - this.nestingLevel++; - var currentMemberMinChar = this.scanner.startPos; - var wasGetOrSetId = false; - while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - var scanNext = true; - var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Duplicate 'get' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Getter already marked as a setter"); - } - modifiers |= TypeScript.Modifiers.Getter; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Duplicate 'set' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Setter already marked as a getter"); - } - modifiers |= TypeScript.Modifiers.Setter; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Private; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Public; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Static) { - if(modifiers & TypeScript.Modifiers.Static) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Static; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { - if(modifiers != parentModifiers) { - this.reportParseError("Constructors may not have modifiers"); - } - this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - resetModifiers = true; - } else { - if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { - var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); - var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - if(wasGetOrSetId) { - modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); - wasGetOrSetId = false; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - } else { - if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Property accessors must be functions"); - } - var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); - if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - scanNext = false; - } - } else { - if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - scanNext = false; - varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Expected ';'"); - scanNext = false; - } - } - } - } - resetModifiers = true; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Super) { - this.reportParseError("Base class initializers must be the first statement in a class definition"); - } else { - if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { - wasGetOrSetId = true; - scanNext = false; - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); - resetModifiers = true; - } - } - } - } - } - } - } - } - } - } - if(scanNext) { - this.currentToken = this.scanner.scan(); - } - if(resetModifiers) { - modifiers = parentModifiers; - currentMemberMinChar = this.scanner.startPos; - resetModifiers = false; - } - } - var membersLimChar = this.scanner.pos; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - classDecl.endingToken = new TypeScript.ASTSpan(); - classDecl.endingToken.minChar = this.scanner.startPos; - classDecl.endingToken.limChar = this.scanner.pos; - if(!this.currentClassDefinition.members.members.length) { - this.currentClassDefinition.preComments = this.parseComments(); - } - this.currentToken = this.scanner.scan(); - } - this.nestingLevel--; - this.currentClassDefinition.members.minChar = membersMinChar; - this.currentClassDefinition.members.limChar = membersLimChar; - this.currentClassDefinition.limChar = membersLimChar; - this.currentClassDefinition = null; - }; - Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { - this.parsingClassConstructorDefinition = true; - var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - var args = new TypeScript.ASTList(); - var variableArgList = false; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); - if(args.members.length > 0) { - var lastArg = args.members[args.members.length - 1]; - } - } - var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; - if(requiresSignature) { - for(var i = 0; i < args.members.length; i++) { - var arg = args.members[i]; - if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { - this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); - } - } - } - if(!requiresSignature) { - this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; - } - var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); - constructorFuncDecl.preComments = preComments; - if(requiresSignature && !isAmbient) { - constructorFuncDecl.isOverload = true; - } - constructorFuncDecl.variableArgList = variableArgList; - this.currentClassDecl = null; - constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); - constructorFuncDecl.classDecl = this.currentClassDefinition; - if(isAmbient) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(requiresSignature) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; - } - if(this.currentClassDefinition.constructorDecl) { - if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { - this.reportParseError("Duplicate constructor definition"); - } - } - if(isAmbient || !constructorFuncDecl.isSignature()) { - this.currentClassDefinition.constructorDecl = constructorFuncDecl; - } - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; - this.parsingClassConstructorDefinition = false; - return constructorFuncDecl; - }; - Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.minChar = minChar; - var isStatic = false; - varDecl.preComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(!(modifiers & TypeScript.Modifiers.Static)) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - varDecl.limChar = this.scanner.pos; - } - if(modifiers & TypeScript.Modifiers.Static) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - isStatic = true; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } else { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - if(isDeclaredInConstructor) { - varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; - } - if(!isDeclaredInConstructor && !isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; - } - this.currentClassDefinition.knownMemberNames[text.actualText] = true; - if(!isDeclaredInConstructor) { - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; - } - varDecl.postComments = this.parseComments(); - return varDecl; - }; - Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); - var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; - if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { - this.reportParseError("Property accessors may not be declared in ambient classes"); - } - var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } - var funcDecl = ast; - funcDecl.minChar = minChar; - if(funcDecl.bod !== null) { - funcDecl.limChar = funcDecl.bod.limChar; - } - if(modifiers & TypeScript.Modifiers.Private) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); - } - } - funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; - return funcDecl; - }; - Parser.prototype.parseTypeMember = function (errorRecoverySet) { - var minChar = this.scanner.startPos; - var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); - if(propertyDecl) { - propertyDecl.minChar = minChar; - if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - } - } - return propertyDecl; - }; - Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; - while(true) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.CloseBrace: - case TypeScript.TokenID.EndOfFile: { - members.limChar = this.scanner.pos; - return; - - } - } - var element = this.parseTypeMember(errorRecoverySet); - if(element) { - members.append(element); - } - } - }; - Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - this.currentToken = this.scanner.scan(); - var minChar = this.scanner.pos; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("interface missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - this.reportParseError("Expected 'extends'"); - } - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - extendsList.minChar = this.scanner.startPos; - this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Private; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Public; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; - } - interfaceDecl.limChar = members.limChar; - interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return interfaceDecl; - }; - Parser.prototype.makeVarDecl = function (id, nest) { - var varDecl = new TypeScript.VarDecl(id, nest); - var currentVarList = this.topVarList(); - if(currentVarList) { - currentVarList.append(varDecl); - } - return varDecl; - }; - Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic) { - var text = null; - var minChar = this.scanner.startPos; - var nameLimChar = minChar; - var isNew = false; - var isIndexer = false; - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - requireSignature = true; - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { - if(!requireSignature && !isStatic) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - text = new TypeScript.MissingIdentifier(); - } - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.New) { - if(requireSignature) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - isNew = true; - } - } - if(!isNew) { - if(!requireSignature) { - this.currentToken = this.scanner.scan(); - } - text = new TypeScript.Identifier("new"); - text.minChar = this.scanner.pos - 3; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - } - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { - isIndexer = true; - text = new TypeScript.Identifier("__item"); - } else { - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - var eminChar = this.scanner.startPos; - var curpos = this.scanner.pos; - this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); - if(this.scanner.pos == curpos) { - this.currentToken = this.scanner.scan(); - } - var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - epd.flags |= TypeScript.ASTFlags.Error; - epd.minChar = eminChar; - epd.limChar = this.scanner.lastTokenLimChar(); - return epd; - } - } else { - if(wasAccessorID) { - text = TypeScript.Identifier.fromToken(this.prevIDTok); - text.minChar = this.scanner.lastTokenLimChar() - 3; - text.limChar = this.scanner.lastTokenLimChar(); - nameLimChar = text.limChar; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { - this.currentToken = this.scanner.scan(); - } - this.prevIDTok = null; - } else { - text = TypeScript.Identifier.fromToken(this.currentToken); - text.minChar = this.scanner.startPos; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - if(this.inInterfaceDecl && text) { - text.flags |= TypeScript.ASTFlags.OptionalName; - } else { - this.reportParseError("Optional properties may only be declared on interface or object types"); - } - this.currentToken = this.scanner.scan(); - } - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { - var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; - if(isIndexer) { - ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; - } - var ast = this.parseFncDecl(ers, true, requireSignature, !this.inFncDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); - var funcDecl; - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } else { - funcDecl = ast; - } - if(funcDecl.name) { - funcDecl.name.minChar = minChar; - funcDecl.name.limChar = nameLimChar; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(modifiers & TypeScript.Modifiers.Ambient) { - this.reportParseError("Property accessors may not be declared in ambient types"); - } - } - if(text == null) { - if(isNew) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = this.currentClassDecl; - } else { - funcDecl.hint = "_call"; - funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; - } - } - return funcDecl; - } else { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.preComments = this.parseComments(); - varDecl.minChar = minChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(requireSignature) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.text; - funcDecl.boundToProperty = varDecl; - } else { - if(isAccessor) { - this.reportParseError("Accessors may only be functions"); - } - } - } else { - varDecl.limChar = this.scanner.pos; - } - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - return varDecl; - } - }; - Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { - var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); - var minChar = this.scanner.startPos; - var varDecl = null; - var declList = null; - var multivar = false; - this.currentToken = this.scanner.scan(); - var varDeclPreComments = this.parseComments(); - while(true) { - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - this.reportParseError("Expected identifier in variable declaration"); - if(this.errorRecovery) { - varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - varDecl.minChar = minChar; - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); - if(this.strictMode && (varDeclName.text == "eval")) { - this.reportParseError("'eval' may not name a variable in strict mode"); - } - varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); - varDecl.id.minChar = this.scanner.startPos; - varDecl.id.limChar = this.scanner.pos; - varDecl.preComments = varDeclPreComments; - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - varDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - varDecl.varFlags |= TypeScript.VarFlags.Exported; - } - varDecl.minChar = minChar; - if(declList) { - declList.append(varDecl); - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - var prevInFncDecl = this.inFncDecl; - this.inFncDecl = false; - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - this.inFncDecl = prevInFncDecl; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { - this.reportParseError("Ambient variable can not have an initializer"); - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.actualText; - } - } else { - if(isConst) { - this.reportParseError("const declaration requires initializer"); - } - varDecl.limChar = this.scanner.pos; - } - varDecl.postComments = this.parseCommentsForLine(this.scanner.line); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - if(declList) { - declList.limChar = varDecl.limChar; - return declList; - } else { - return varDecl; - } - } - if(!multivar) { - declList = new TypeScript.ASTList(); - declList.minChar = varDecl.minChar; - declList.append(varDecl); - multivar = true; - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.startPos; - } - }; - Parser.prototype.parseMemberList = function (errorRecoverySet) { - var elements = new TypeScript.ASTList(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - return elements; - } - var idHint = null; - var memberName = null; - var memberExpr = null; - var member = null; - var minChar = this.scanner.startPos; - var isSet = false; - var skippedTokenForGetSetId = false; - var getSetTok = null; - var getSetStartPos = 0; - var getSetPos = 0; - for(; ; ) { - var accessorPattern = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { - isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; - getSetTok = this.currentToken; - getSetStartPos = this.scanner.startPos; - getSetPos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = isSet ? "set" : "get"; - idHint = idHint + this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - accessorPattern = true; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { - this.reportParseError("Expected identifier, string or number as accessor name"); - } else { - skippedTokenForGetSetId = true; - memberName = TypeScript.Identifier.fromToken(getSetTok); - memberName.minChar = getSetStartPos; - memberName.limChar = getSetPos; - } - } - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - idHint = this.currentToken.getText(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { - var ntok = this.currentToken; - idHint = ntok.value.toString(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - this.reportParseError("Expected identifier, string or number as member name"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); - memberName.limChar = this.scanner.lastTokenLimChar(); - } - } - } - } - } - if(!skippedTokenForGetSetId) { - this.currentToken = this.scanner.scan(); - } else { - skippedTokenForGetSetId = false; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - memberName.flags |= TypeScript.ASTFlags.OptionalName; - this.currentToken = this.scanner.scan(); - } - if(accessorPattern) { - var args = new TypeScript.ASTList(); - this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); - if(isSet && funcDecl.returnTypeAnnotation) { - this.reportParseError("Property setters may not declare a return type"); - } - funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - funcDecl.hint = idHint; - memberExpr = funcDecl; - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { - this.reportParseError("Expected 'new' on array declaration in member definition"); - } - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else { - this.reportParseError("Expected ':' in member definition"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - elements.flags |= TypeScript.ASTFlags.Error; - elements.minChar = minChar; - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - } - } - } - idHint = null; - elements.append(member); - member.limChar = this.scanner.lastTokenLimChar(); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } - } - if(member) { - elements.limChar = member.limChar; - } - elements.minChar = minChar; - return elements; - }; - Parser.prototype.parseArrayList = function (errorRecoverySet) { - var elements = null; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - return elements; - } else { - elements = new TypeScript.ASTList(); - elements.minChar = this.scanner.startPos; - } - var arg; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { - arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - } else { - arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - } - elements.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - }; - Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { - var arrayLiteral = null; - arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); - return arrayLiteral; - }; - Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { - var ast = null; - var sawId = false; - var inNew = false; - var minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var parseAsLambda = false; - var expectlambdaRParen = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Any: - case TypeScript.TokenID.String: { - var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); - if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { - ast = new TypeScript.TypeReference(tid, 0); - sawId = true; - } else { - ast = tid; - sawId = true; - } - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.This: { - ast = new TypeScript.AST(TypeScript.NodeType.This); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.Super: { - ast = new TypeScript.AST(TypeScript.NodeType.Super); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.True: { - ast = new TypeScript.AST(TypeScript.NodeType.True); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - - } - case TypeScript.TokenID.False: { - ast = new TypeScript.AST(TypeScript.NodeType.False); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - - } - case TypeScript.TokenID.Null: { - ast = new TypeScript.AST(TypeScript.NodeType.Null); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - - } - case TypeScript.TokenID.New: { - minChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); - if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { - this.reportParseError("Cannot invoke 'new' on this expression"); - } else { - ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - inNew = true; - } - break; - - } - case TypeScript.TokenID.Function: { - minChar = this.scanner.pos; - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - break; - - } - } - if(ast == null) { - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var idText = this.currentToken.getText(); - ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); - sawId = true; - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; - } - limChar = this.scanner.lastTokenLimChar(); - } - } - if(inCast) { - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - } - if(ast == null) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: { - minChar = this.scanner.pos; - var prevTokId = this.scanner.previousToken().tokenId; - this.currentToken = this.scanner.scan(); - var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; - if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - parseAsLambda = true; - expectlambdaRParen = false; - this.currentToken = this.scanner.scan(); - } else { - if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - parseAsLambda = true; - expectlambdaRParen = true; - } else { - ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); - limChar = this.scanner.lastTokenLimChar(); - parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); - expectlambdaRParen = true; - } - } - if((ast && !parseAsLambda)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); - break; - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast.isParenthesized = true; - } - break; - - } - case TypeScript.TokenID.NumberLiteral: { - var numTok = this.currentToken; - this.currentToken = this.scanner.scan(); - ast = new TypeScript.NumberLiteral(numTok.value, numTok.hasEmptyFraction); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - - case TypeScript.TokenID.StringLiteral: { - ast = new TypeScript.StringLiteral(this.currentToken.getText()); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.RegularExpressionLiteral: { - var rtok = this.currentToken; - ast = new TypeScript.RegexLiteral(rtok.regex); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - - case TypeScript.TokenID.OpenBracket: { - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); - ast.minChar = minChar; - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - - } - case TypeScript.TokenID.OpenBrace: { - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - members.minChar = minChar; - members.limChar = limChar; - break; - - } - case TypeScript.TokenID.LessThan: { - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); - (ast).castTerm = term; - break; - - } - default: { - if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - parseAsLambda = true; - ast = this.prevExpr; - } else { - this.reportParseError("Check format of expression term"); - if(this.errorRecovery) { - var ident = new TypeScript.MissingIdentifier(); - ident.minChar = minChar; - ident.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - } else { - limChar = this.scanner.lastTokenLimChar(); - } - ast = ident; - } - } - - } - } - } - if(parseAsLambda) { - if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - } else { - if(ast) { - ast.isParenthesized = true; - } - } - } - if(sawId && (typeContext != TypeContext.NoTypes)) { - typeContext |= TypeContext.ArraySuffix; - } - var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); - if(postFix) { - if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { - var binExpr = postFix; - if(binExpr.operand2 == null) { - postFix = this.convertToTypeReference(postFix); - } - } - postFix.minChar = minChar; - postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); - return postFix; - } else { - return new TypeScript.AST(TypeScript.NodeType.Error); - } - }; - Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { - var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: lambdaArgs - }, expectClosingRParen); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - if(!skipNextRParen) { - ast.flags |= TypeScript.ASTFlags.SkipNextRParen; - } - ast.limChar = this.scanner.lastTokenLimChar(); - ; ; - return ast; - }; - Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { - if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } - var ast = null; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - var canAssign = true; - var idHint = null; - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - var exprIsAnonLambda = false; - if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { - canAssign = false; - this.currentToken = this.scanner.scan(); - var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); - if((tokenInfo.unopNodeType == TypeScript.NodeType.Pos) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { - ast = tempExpr; - } else { - if((tokenInfo.unopNodeType == TypeScript.NodeType.Neg) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { - var numLit = tempExpr; - numLit.value = (-numLit.value); - if(numLit.value == 0) { - numLit.isNegativeZero = true; - } - ast = tempExpr; - } else { - ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); - ast.limChar = tempExpr.limChar; - } - } - ast.minChar = minChar; - } else { - ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); - var id; - var temp; - if(ast.nodeType == TypeScript.NodeType.Name) { - id = ast; - idHint = id.actualText; - } else { - if(ast.nodeType == TypeScript.NodeType.Dot) { - var subsumedExpr = false; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { - if((ast).operand2.nodeType == TypeScript.NodeType.Name) { - var op2ID = ((ast).operand2); - if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { - ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); - subsumedExpr = true; - } - } - } - if(!subsumedExpr) { - temp = ast; - while(temp.nodeType == TypeScript.NodeType.Dot) { - var binExpr = temp; - temp = binExpr.operand2; - } - if(temp.nodeType == TypeScript.NodeType.Name) { - id = temp; - idHint = id.actualText; - } - } - } - } - if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { - canAssign = false; - var operand = ast; - ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); - ast.limChar = this.scanner.pos; - ast.minChar = operand.minChar; - this.currentToken = this.scanner.scan(); - } - } - for(; ; ) { - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { - break; - } - if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { - break; - } - if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { - if(tokenInfo.binopPrecedence < minPrecedence) { - break; - } - if(!canAssign) { - this.reportParseError("illegal assignment"); - } - } else { - if(tokenInfo.binopPrecedence <= minPrecedence) { - break; - } - } - if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { - exprIsAnonLambda = true; - canAssign = false; - ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); - break; - } - this.currentToken = this.scanner.scan(); - canAssign = false; - if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { - if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { - exprIsAnonLambda = true; - canAssign = true; - } else { - this.prevExpr = ast; - var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - this.prevExpr = null; - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); - } - } else { - var tc = TypeContext.NoTypes; - var binExpr2; - binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); - if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = binExpr2.operand2; - funcDecl.hint = idHint; - } - binExpr2.minChar = ast.minChar; - binExpr2.limChar = this.scanner.lastTokenLimChar(); - idHint = null; - ast = binExpr2; - } - } - if(canAssign) { - ast.flags |= TypeScript.ASTFlags.Writeable; - } - if(!exprIsAnonLambda) { - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - ast.preComments = preComments; - ast.postComments = this.parseCommentsForLine(this.scanner.line); - } - return ast; - }; - Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { - var count = 0; - if(!ast) { - ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - ast.isParenthesized = true; - } - ast.minChar = lhsMinChar; - ast.limChar = lhsLimChar; - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: { - if(inNew) { - var callExpr = ast; - callExpr.arguments = this.parseArgList(errorRecoverySet); - inNew = false; - } else { - if(!allowCall) { - return ast; - } - ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); - ast.minChar = lhsMinChar; - } - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - break; - - } - case TypeScript.TokenID.OpenBracket: { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { - this.currentToken = this.scanner.scan(); - if(ast.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = ast; - typeRef.arrayCount++; - } else { - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); - } - ast.limChar = this.scanner.pos; - break; - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - - } - case TypeScript.TokenID.Dot: { - var name = null; - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { - ast.flags |= TypeScript.ASTFlags.DotLHS; - name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Expected identifier following dot"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); - return ast; - } else { - name = new TypeScript.MissingIdentifier(); - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - } - - case TypeScript.TokenID.EqualsGreaterThan: { - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: ast - }, false); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - - } - default: { - return ast; - - } - } - } - }; - Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{'"); - if(this.errorRecovery) { - var etryNode = tryNode; - etryNode.minChar = minChar; - etryNode.limChar = this.scanner.lastTokenLimChar(); - etryNode.flags |= TypeScript.ASTFlags.Error; - return etryNode; - } - } - tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - tryNode.minChar = minChar; - tryNode.limChar = tryNode.body.limChar; - tryNode.preComments = preComments; - tryNode.postComments = this.parseComments(); - return tryNode; - }; - Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { - var catchMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("Expected identifier in catch header"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = this.scanner.pos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); - param.id.minChar = this.scanner.startPos; - param.id.limChar = this.scanner.pos; - param.minChar = param.id.minChar; - param.limChar = param.id.limChar; - this.currentToken = this.scanner.scan(); - var statementPos = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start catch body"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = statementPos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var catchNode = new TypeScript.Catch(param, catchStmt); - catchNode.statement.minChar = catchMinChar; - catchNode.statement.limChar = statementPos; - catchNode.minChar = catchMinChar; - catchNode.limChar = catchStmt.limChar; - catchNode.preComments = preComments; - catchNode.postComments = this.parseComments(); - return catchNode; - }; - Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { - var finMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start body of finally statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); - efin.flags |= TypeScript.ASTFlags.Error; - efin.minChar = this.scanner.startPos; - efin.limChar = this.scanner.pos; - return efin; - } - } - var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var fin = new TypeScript.Finally(finBody); - fin.minChar = finMinChar; - fin.limChar = fin.body.limChar; - fin.preComments = preComments; - fin.postComments = this.parseComments(); - return fin; - }; - Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { - var tryPart = new TypeScript.Try(null); - var tryMinChar = this.scanner.startPos; - this.pushStmt(tryPart, labelList); - this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - this.popStmt(); - var tc = null; - var tf = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { - var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - tc = new TypeScript.TryCatch(tryPart, catchPart); - tc.minChar = tryPart.minChar; - tc.limChar = catchPart.limChar; - } - if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { - if(tc == null) { - this.reportParseError("try with neither catch nor finally"); - if(this.errorRecovery) { - var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - etf.flags |= TypeScript.ASTFlags.Error; - etf.minChar = this.scanner.startPos; - etf.limChar = this.scanner.pos; - return etf; - } - return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - } else { - return tc; - } - } else { - if(tc) { - tryPart = tc; - } - var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); - tf = new TypeScript.TryFinally(tryPart, finallyPart); - tf.minChar = tryMinChar; - tf.limChar = finallyPart.limChar; - return tf; - } - }; - Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { - var ast = null; - var labelList = null; - var astList = null; - var temp; - var modifiers = TypeScript.Modifiers.None; - var minChar = this.scanner.startPos; - var forInOk = false; - var needTerminator = false; - var fnOrVar = null; - var preComments = this.parseComments(); - this.state = ParseState.StartStatement; - function isAmbient() { - return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); - } - function mayNotBeExported() { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportError("Statement may not be exported"); - } - } - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.EndOfFile: { - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.pos; - break; - - } - case TypeScript.TokenID.Function: { - if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { - this.currentToken = this.scanner.scan(); - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false); - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - this.reportParseError("function keyword can only introduce function declaration"); - } else { - if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - } - ast = fnOrVar; - if(this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } else { - ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, isAmbient(), modifiers, null, true); - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - if(this.ambientModule) { - this.reportParseError("function declaration not permitted within ambient module"); - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } - break; - - } - case TypeScript.TokenID.Module: { - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); - preComments = null; - } - break; - - } - case TypeScript.TokenID.Import: { - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportParseError("export keyword not permitted on import declaration"); - } - ast = this.parseImportDeclaration(errorRecoverySet, modifiers); - needTerminator = true; - } - break; - - } - case TypeScript.TokenID.Export: { - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("'export' statements are only allowed at the global and module levels"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } - modifiers |= TypeScript.Modifiers.Exported; - this.currentToken = this.scanner.scan(); - break; - - } - case TypeScript.TokenID.Private: { - modifiers |= TypeScript.Modifiers.Private; - this.currentToken = this.scanner.scan(); - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - minChar = this.scanner.pos; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - - } - case TypeScript.TokenID.Public: { - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.pos; - modifiers |= TypeScript.Modifiers.Public; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { - this.reportParseError("'property' statements are only allowed within classes"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - - } - case TypeScript.TokenID.Declare: { - if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { - this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); - } - if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); - } - modifiers |= TypeScript.Modifiers.Ambient; - this.currentToken = this.scanner.scan(); - break; - - } - case TypeScript.TokenID.Class: { - if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("class not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); - } - break; - - } - case TypeScript.TokenID.Interface: { - if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("interface not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); - } - break; - - } - case TypeScript.TokenID.Var: { - var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); - if(declAst.nodeType == TypeScript.NodeType.VarDecl) { - ast = declAst; - } else { - ast = new TypeScript.Block(declAst, false); - } - needTerminator = true; - break; - - } - case TypeScript.TokenID.Static: { - if(this.currentClassDecl == null) { - this.reportParseError("Statics may only be class members"); - } - mayNotBeExported(); - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - } - } - } - if(isAmbient()) { - modifiers |= TypeScript.Modifiers.Ambient; - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); - var staticsList = this.topStaticsList(); - if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - staticsList.append(fnOrVar); - } - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - break; - - } - case TypeScript.TokenID.For: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("syntax error: for statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - this.state = ParseState.ForInit; - forInOk = true; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Var: { - temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); - break; - - } - case TypeScript.TokenID.Semicolon: { - temp = null; - this.state = ParseState.ForCondStart; - break; - - } - default: { - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); - break; - - } - } - this.state = ParseState.ForInitAfterVar; - if(this.currentToken.tokenId == TypeScript.TokenID.In) { - if((temp == null) || (!forInOk)) { - this.reportParseError("malformed for statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - ast.flags |= TypeScript.ASTFlags.Error; - } - } else { - this.currentToken = this.scanner.scan(); - var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); - forInStmt.limChar = this.scanner.pos; - forInStmt.statement.minChar = minChar; - forInStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); - this.pushStmt(forInStmt, labelList); - forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forInStmt.minChar = minChar; - ast = forInStmt; - } - } else { - var forStmt = new TypeScript.ForStatement(temp); - forStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - forStmt.cond = null; - } else { - forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = forStmt; - ast.flags |= TypeScript.ASTFlags.Error; - } - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - forStmt.incr = null; - } else { - forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - this.pushStmt(forStmt, labelList); - forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forStmt.limChar = forStmt.body.limChar; - ast = forStmt; - } - break; - - } - case TypeScript.TokenID.With: { - { - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); - } - if(this.strictMode) { - this.reportParseError("'with' statements are not available in strict mode"); - } - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'with' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var withStmt = new TypeScript.WithStatement(expr); - withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - withStmt.minChar = minChar; - withStmt.limChar = withStmt.body.limChar; - ast = withStmt; - } - break; - - } - case TypeScript.TokenID.Switch: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'switch' statement does not take modifiers"); - } - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - switchStmt.statement.minChar = minChar; - switchStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var caseListMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); - switchStmt.defaultCase = null; - switchStmt.caseList = new TypeScript.ASTList(); - var caseStmt = null; - this.pushStmt(switchStmt, labelList); - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { - var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); - caseStmt = new TypeScript.CaseStatement(); - caseStmt.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(isDefault) { - switchStmt.defaultCase = caseStmt; - } else { - caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - caseStmt.body = new TypeScript.ASTList(); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); - caseStmt.limChar = caseStmt.body.limChar; - switchStmt.caseList.append(caseStmt); - } else { - break; - } - } - switchStmt.caseList.minChar = caseListMinChar; - switchStmt.caseList.limChar = this.scanner.pos; - switchStmt.limChar = switchStmt.caseList.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - this.popStmt(); - ast = switchStmt; - break; - } - - case TypeScript.TokenID.While: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'while' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); - var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - whileStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(whileStmt, labelList); - whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - whileStmt.limChar = whileStmt.body.limChar; - this.popStmt(); - ast = whileStmt; - break; - } - - case TypeScript.TokenID.Do: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'do' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var doStmt = new TypeScript.DoWhileStatement(); - doStmt.minChar = minChar; - this.pushStmt(doStmt, labelList); - doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); - this.popStmt(); - doStmt.whileAST = new TypeScript.Identifier("while"); - doStmt.whileAST.minChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); - doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - doStmt.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast = doStmt; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - break; - } - - case TypeScript.TokenID.If: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("if statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ifStmt.minChar = minChar; - ifStmt.statement.minChar = minChar; - ifStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(ifStmt, labelList); - ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.thenBod.limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Else) { - this.currentToken = this.scanner.scan(); - ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.elseBod.limChar; - } - this.popStmt(); - ast = ifStmt; - break; - } - - case TypeScript.TokenID.Try: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("try statement does not take modifiers"); - } - minChar = this.scanner.startPos; - ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); - break; - } - - case TypeScript.TokenID.OpenBrace: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("block does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var block = new TypeScript.Block(new TypeScript.ASTList(), true); - this.pushStmt(block, labelList); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); - this.popStmt(); - block.statements.minChar = minChar; - block.statements.limChar = this.scanner.pos; - block.minChar = block.statements.minChar; - block.limChar = block.statements.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = block; - break; - } - - case TypeScript.TokenID.Semicolon: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifier can not appear here"); - } - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - this.currentToken = this.scanner.scan(); - break; - - } - case TypeScript.TokenID.Break: - case TypeScript.TokenID.Continue: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before jump statement"); - } - var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { - jump.target = this.currentToken.getText(); - this.currentToken = this.scanner.scan(); - } - this.resolveJumpTarget(jump); - ast = jump; - needTerminator = true; - break; - } - - case TypeScript.TokenID.Return: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before return statement"); - } - if(!this.inFunction) { - this.reportParseError("return statement outside of function body"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.minChar = minChar; - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - needTerminator = true; - retStmt.limChar = this.scanner.lastTokenLimChar(); - ast = retStmt; - break; - } - - case TypeScript.TokenID.Throw: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before a throw statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } else { - this.reportParseError("throw with no target"); - temp = null; - } - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); - ast.limChar = this.scanner.lastTokenLimChar(); - needTerminator = true; - break; - - } - case TypeScript.TokenID.Enum: { - this.currentToken = this.scanner.scan(); - ast = this.parseEnumDecl(errorRecoverySet, modifiers); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - (ast).modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).modFlags |= TypeScript.ModuleFlags.Exported; - } - break; - - } - case TypeScript.TokenID.Debugger: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before debugger statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var debuggerStmt = new TypeScript.DebuggerStatement(); - debuggerStmt.minChar = minChar; - needTerminator = true; - debuggerStmt.limChar = this.scanner.lastTokenLimChar(); - ast = debuggerStmt; - break; - - } - default: { - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before an expression statement or label"); - } - minChar = this.scanner.startPos; - var svPos = this.scanner.pos; - temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.scanner.pos == svPos) { - this.currentToken = this.scanner.scan(); - ast = temp; - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { - if(labelList == null) { - labelList = new TypeScript.ASTList(); - } - labelList.append(new TypeScript.Label(temp)); - this.currentToken = this.scanner.scan(); - } else { - ast = temp; - needTerminator = true; - } - } - - } - } - if(ast) { - break; - } - } - if(needTerminator) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Semicolon: { - this.currentToken = this.scanner.scan(); - ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; - break; - - } - case TypeScript.TokenID.EndOfFile: { - ast.limChar = this.scanner.pos; - - } - case TypeScript.TokenID.CloseBrace: { - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - break; - - } - default: { - if(!this.scanner.lastTokenHadNewline()) { - this.reportParseError("Expected ';'"); - } else { - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - } - break; - - } - } - } - if(labelList) { - ast = new TypeScript.LabeledStatement(labelList, ast); - } - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - if(preComments) { - ast.preComments = preComments; - } - if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { - this.reportParseError("statement not permitted within ambient module"); - } - ast.flags |= TypeScript.ASTFlags.IsStatement; - return ast; - }; - Parser.prototype.okAmbientModuleMember = function (ast) { - var nt = ast.nodeType; - return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).isMethod())); - }; - Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { - var directivePrologue = sourceElms; - statements.minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; - var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; - this.state = ParseState.StartStatementList; - var oldStrictMode = this.strictMode; - this.nestingLevel++; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - this.state = ParseState.EndStmtList; - statements.limChar = limChar; - if(statements.members.length == 0) { - statements.preComments = this.parseComments(); - } else { - statements.postComments = this.parseComments(); - } - this.strictMode = oldStrictMode; - this.nestingLevel--; - return; - } - var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); - if(stmt) { - stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - statements.append(stmt); - limChar = stmt.limChar; - if(directivePrologue) { - if(stmt.nodeType == TypeScript.NodeType.QString) { - var qstring = stmt; - if(qstring.text == "\"use strict\"") { - statements.flags |= TypeScript.ASTFlags.StrictMode; - this.strictMode = true; - } else { - directivePrologue = false; - } - } else { - directivePrologue = false; - } - } - } - } - }; - Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { - var svGenTarget = TypeScript.moduleGenTarget; - try { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; - var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); - return new QuickParseResult(script, this.scanner.lexState); - }finally { - TypeScript.moduleGenTarget = svGenTarget; - } - }; - Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { - if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } - var _this = this; - this.ambientModule = false; - this.topLevel = true; - this.hasTopLevelImportOrExport = false; - this.requiresExtendsBlock = false; - this.fname = filename; - this.currentUnitIndex = unitIndex; - this.amdDependencies = []; - this.scanner.resetComments(); - this.scanner.setErrorHandler(function (message) { - return _this.reportParseError(message); - }); - this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var minChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.pushDeclLists(); - var bod = new TypeScript.ASTList(); - bod.minChar = minChar; - this.state = ParseState.StartScript; - this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); - while(true) { - this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); - if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { - break; - } - var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; - this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); - this.currentToken = this.scanner.scan(); - } - this.state = ParseState.EndScript; - bod.limChar = this.scanner.pos; - var topLevelMod = null; - if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { - var correctedFileName = TypeScript.switchToForwardSlashes(filename); - var id = new TypeScript.Identifier(correctedFileName); - topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), this.topScopeList(), null); - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; - topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; - if(this.parsingDeclareFile) { - topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; - } - topLevelMod.minChar = minChar; - topLevelMod.limChar = this.scanner.pos; - topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); - topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; - topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - topLevelMod.amdDependencies = this.amdDependencies; - bod = new TypeScript.ASTList(); - bod.minChar = topLevelMod.minChar; - bod.limChar = topLevelMod.limChar; - bod.append(topLevelMod); - } - var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); - script.bod = bod; - this.popDeclLists(); - script.minChar = minChar; - script.limChar = this.scanner.pos; - script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); - script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - script.isDeclareFile = this.parsingDeclareFile; - script.topLevelMod = topLevelMod; - script.containsUnicodeChar = this.scanner.seenUnicodeChar; - script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - script.requiresExtendsBlock = this.requiresExtendsBlock; - return script; - }; - return Parser; - })(); - TypeScript.Parser = Parser; - function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { - var fragment = sourceText.getText(minChar, limChar); - logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); - var quickParser = new Parser(); - quickParser.setErrorRecovery(null); - quickParser.errorCallback = errorCapture; - var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); - quickParser.currentClassDecl = quickClassDecl; - var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); - return result; - } - TypeScript.quickParse = quickParse; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var PrintContext = (function () { - function PrintContext(outfile, parser) { - this.outfile = outfile; - this.parser = parser; - this.builder = ""; - this.indent1 = " "; - this.indentStrings = []; - this.indentAmt = 0; - } - PrintContext.prototype.increaseIndent = function () { - this.indentAmt++; - }; - PrintContext.prototype.decreaseIndent = function () { - this.indentAmt--; - }; - PrintContext.prototype.startLine = function () { - if(this.builder.length > 0) { - TypeScript.CompilerDiagnostics.Alert(this.builder); - } - var indentString = this.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i++) { - indentString += this.indent1; - } - this.indentStrings[this.indentAmt] = indentString; - } - this.builder += indentString; - }; - PrintContext.prototype.write = function (s) { - this.builder += s; - }; - PrintContext.prototype.writeLine = function (s) { - this.builder += s; - this.outfile.WriteLine(this.builder); - this.builder = ""; - }; - return PrintContext; - })(); - TypeScript.PrintContext = PrintContext; - function prePrintAST(ast, parent, walker) { - var pc = walker.state; - ast.print(pc); - pc.increaseIndent(); - return ast; - } - TypeScript.prePrintAST = prePrintAST; - function postPrintAST(ast, parent, walker) { - var pc = walker.state; - pc.decreaseIndent(); - return ast; - } - TypeScript.postPrintAST = postPrintAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - TypeScript.LexEOF = (-1); - TypeScript.LexCodeNWL = 10; - TypeScript.LexCodeRET = 13; - TypeScript.LexCodeLS = 8232; - TypeScript.LexCodePS = 8233; - TypeScript.LexCodeTAB = 9; - TypeScript.LexCodeVTAB = 11; - TypeScript.LexCode_e = 'e'.charCodeAt(0); - TypeScript.LexCode_E = 'E'.charCodeAt(0); - TypeScript.LexCode_x = 'x'.charCodeAt(0); - TypeScript.LexCode_X = 'X'.charCodeAt(0); - TypeScript.LexCode_a = 'a'.charCodeAt(0); - TypeScript.LexCode_A = 'A'.charCodeAt(0); - TypeScript.LexCode_f = 'f'.charCodeAt(0); - TypeScript.LexCode_F = 'F'.charCodeAt(0); - TypeScript.LexCode_g = 'g'.charCodeAt(0); - TypeScript.LexCode_m = 'm'.charCodeAt(0); - TypeScript.LexCode_i = 'i'.charCodeAt(0); - TypeScript.LexCode_u = 'u'.charCodeAt(0); - TypeScript.LexCode_0 = '0'.charCodeAt(0); - TypeScript.LexCode_9 = '9'.charCodeAt(0); - TypeScript.LexCode_8 = '8'.charCodeAt(0); - TypeScript.LexCode_7 = '7'.charCodeAt(0); - TypeScript.LexCodeBSL = '\\'.charCodeAt(0); - TypeScript.LexCodeSHP = '#'.charCodeAt(0); - TypeScript.LexCodeBNG = '!'.charCodeAt(0); - TypeScript.LexCodeQUO = '"'.charCodeAt(0); - TypeScript.LexCodeAPO = '\''.charCodeAt(0); - TypeScript.LexCodePCT = '%'.charCodeAt(0); - TypeScript.LexCodeAMP = '&'.charCodeAt(0); - TypeScript.LexCodeLPR = '('.charCodeAt(0); - TypeScript.LexCodeRPR = ')'.charCodeAt(0); - TypeScript.LexCodePLS = '+'.charCodeAt(0); - TypeScript.LexCodeMIN = '-'.charCodeAt(0); - TypeScript.LexCodeMUL = '*'.charCodeAt(0); - TypeScript.LexCodeSLH = '/'.charCodeAt(0); - TypeScript.LexCodeXOR = '^'.charCodeAt(0); - TypeScript.LexCodeCMA = ','.charCodeAt(0); - TypeScript.LexCodeDOT = '.'.charCodeAt(0); - TypeScript.LexCodeLT = '<'.charCodeAt(0); - TypeScript.LexCodeEQ = '='.charCodeAt(0); - TypeScript.LexCodeGT = '>'.charCodeAt(0); - TypeScript.LexCodeQUE = '?'.charCodeAt(0); - TypeScript.LexCodeLBR = '['.charCodeAt(0); - TypeScript.LexCodeRBR = ']'.charCodeAt(0); - TypeScript.LexCodeUSC = '_'.charCodeAt(0); - TypeScript.LexCodeLC = '{'.charCodeAt(0); - TypeScript.LexCodeRC = '}'.charCodeAt(0); - TypeScript.LexCodeBAR = '|'.charCodeAt(0); - TypeScript.LexCodeTIL = '~'.charCodeAt(0); - TypeScript.LexCodeCOL = ':'.charCodeAt(0); - TypeScript.LexCodeSMC = ';'.charCodeAt(0); - TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); - TypeScript.LexCodeDollar = '$'.charCodeAt(0); - TypeScript.LexCodeSpace = 32; - TypeScript.LexCodeAtSign = '@'.charCodeAt(0); - TypeScript.LexCodeASCIIChars = 128; - TypeScript.LexKeywordTable = undefined; - var autoToken = new Array(TypeScript.LexCodeASCIIChars); - var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); - var unicodeES3IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 543, - 546, - 563, - 592, - 685, - 688, - 696, - 699, - 705, - 720, - 721, - 736, - 740, - 750, - 750, - 890, - 890, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 974, - 976, - 983, - 986, - 1011, - 1024, - 1153, - 1164, - 1220, - 1223, - 1224, - 1227, - 1228, - 1232, - 1269, - 1272, - 1273, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1569, - 1594, - 1600, - 1610, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1786, - 1788, - 1808, - 1808, - 1810, - 1836, - 1920, - 1957, - 2309, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2699, - 2701, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2784, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2870, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 2997, - 2999, - 3001, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3294, - 3294, - 3296, - 3297, - 3333, - 3340, - 3342, - 3344, - 3346, - 3368, - 3370, - 3385, - 3424, - 3425, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3805, - 3840, - 3840, - 3904, - 3911, - 3913, - 3946, - 3976, - 3979, - 4096, - 4129, - 4131, - 4135, - 4137, - 4138, - 4176, - 4181, - 4256, - 4293, - 4304, - 4342, - 4352, - 4441, - 4447, - 4514, - 4520, - 4601, - 4608, - 4614, - 4616, - 4678, - 4680, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4742, - 4744, - 4744, - 4746, - 4749, - 4752, - 4782, - 4784, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4814, - 4816, - 4822, - 4824, - 4846, - 4848, - 4878, - 4880, - 4880, - 4882, - 4885, - 4888, - 4894, - 4896, - 4934, - 4936, - 4954, - 5024, - 5108, - 5121, - 5740, - 5743, - 5750, - 5761, - 5786, - 5792, - 5866, - 6016, - 6067, - 6176, - 6263, - 6272, - 6312, - 7680, - 7835, - 7840, - 7929, - 7936, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8319, - 8319, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8497, - 8499, - 8505, - 8544, - 8579, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12346, - 12353, - 12436, - 12445, - 12446, - 12449, - 12538, - 12540, - 12542, - 12549, - 12588, - 12593, - 12686, - 12704, - 12727, - 13312, - 13312, - 19893, - 19893, - 19968, - 19968, - 40869, - 40869, - 40960, - 42124, - 44032, - 44032, - 55203, - 55203, - 63744, - 64045, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65138, - 65140, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500 - ]; - var unicodeES3IdCont = [ - 768, - 846, - 864, - 866, - 1155, - 1158, - 1425, - 1441, - 1443, - 1465, - 1467, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1476, - 1611, - 1621, - 1632, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 2305, - 2307, - 2364, - 2364, - 2366, - 2381, - 2385, - 2388, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2562, - 2562, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2662, - 2673, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2883, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2918, - 2927, - 2946, - 2947, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3047, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3174, - 3183, - 3202, - 3203, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3302, - 3311, - 3330, - 3331, - 3390, - 3395, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3984, - 3991, - 3993, - 4028, - 4038, - 4038, - 4140, - 4146, - 4150, - 4153, - 4160, - 4169, - 4182, - 4185, - 4969, - 4977, - 6068, - 6099, - 6112, - 6121, - 6160, - 6169, - 6313, - 6313, - 8255, - 8256, - 8400, - 8412, - 8417, - 8417, - 12330, - 12335, - 12441, - 12442, - 12539, - 12539, - 64286, - 64286, - 65056, - 65059, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343, - 65381, - 65381 - ]; - var unicodeES5IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 705, - 710, - 721, - 736, - 740, - 748, - 748, - 750, - 750, - 880, - 884, - 886, - 887, - 890, - 893, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 1013, - 1015, - 1153, - 1162, - 1319, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1568, - 1610, - 1646, - 1647, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1774, - 1775, - 1786, - 1788, - 1791, - 1791, - 1808, - 1808, - 1810, - 1839, - 1869, - 1957, - 1969, - 1969, - 1994, - 2026, - 2036, - 2037, - 2042, - 2042, - 2048, - 2069, - 2074, - 2074, - 2084, - 2084, - 2088, - 2088, - 2112, - 2136, - 2208, - 2208, - 2210, - 2220, - 2308, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2417, - 2423, - 2425, - 2431, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2493, - 2493, - 2510, - 2510, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2785, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2869, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2929, - 2929, - 2947, - 2947, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 3001, - 3024, - 3024, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3133, - 3133, - 3160, - 3161, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3261, - 3261, - 3294, - 3294, - 3296, - 3297, - 3313, - 3314, - 3333, - 3340, - 3342, - 3344, - 3346, - 3386, - 3389, - 3389, - 3406, - 3406, - 3424, - 3425, - 3450, - 3455, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3807, - 3840, - 3840, - 3904, - 3911, - 3913, - 3948, - 3976, - 3980, - 4096, - 4138, - 4159, - 4159, - 4176, - 4181, - 4186, - 4189, - 4193, - 4193, - 4197, - 4198, - 4206, - 4208, - 4213, - 4225, - 4238, - 4238, - 4256, - 4293, - 4295, - 4295, - 4301, - 4301, - 4304, - 4346, - 4348, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4744, - 4746, - 4749, - 4752, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4822, - 4824, - 4880, - 4882, - 4885, - 4888, - 4954, - 4992, - 5007, - 5024, - 5108, - 5121, - 5740, - 5743, - 5759, - 5761, - 5786, - 5792, - 5866, - 5870, - 5872, - 5888, - 5900, - 5902, - 5905, - 5920, - 5937, - 5952, - 5969, - 5984, - 5996, - 5998, - 6000, - 6016, - 6067, - 6103, - 6103, - 6108, - 6108, - 6176, - 6263, - 6272, - 6312, - 6314, - 6314, - 6320, - 6389, - 6400, - 6428, - 6480, - 6509, - 6512, - 6516, - 6528, - 6571, - 6593, - 6599, - 6656, - 6678, - 6688, - 6740, - 6823, - 6823, - 6917, - 6963, - 6981, - 6987, - 7043, - 7072, - 7086, - 7087, - 7098, - 7141, - 7168, - 7203, - 7245, - 7247, - 7258, - 7293, - 7401, - 7404, - 7406, - 7409, - 7413, - 7414, - 7424, - 7615, - 7680, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8305, - 8305, - 8319, - 8319, - 8336, - 8348, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8505, - 8508, - 8511, - 8517, - 8521, - 8526, - 8526, - 8544, - 8584, - 11264, - 11310, - 11312, - 11358, - 11360, - 11492, - 11499, - 11502, - 11506, - 11507, - 11520, - 11557, - 11559, - 11559, - 11565, - 11565, - 11568, - 11623, - 11631, - 11631, - 11648, - 11670, - 11680, - 11686, - 11688, - 11694, - 11696, - 11702, - 11704, - 11710, - 11712, - 11718, - 11720, - 11726, - 11728, - 11734, - 11736, - 11742, - 11823, - 11823, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12348, - 12353, - 12438, - 12445, - 12447, - 12449, - 12538, - 12540, - 12543, - 12549, - 12589, - 12593, - 12686, - 12704, - 12730, - 12784, - 12799, - 13312, - 13312, - 19893, - 19893, - 19968, - 19968, - 40908, - 40908, - 40960, - 42124, - 42192, - 42237, - 42240, - 42508, - 42512, - 42527, - 42538, - 42539, - 42560, - 42606, - 42623, - 42647, - 42656, - 42735, - 42775, - 42783, - 42786, - 42888, - 42891, - 42894, - 42896, - 42899, - 42912, - 42922, - 43000, - 43009, - 43011, - 43013, - 43015, - 43018, - 43020, - 43042, - 43072, - 43123, - 43138, - 43187, - 43250, - 43255, - 43259, - 43259, - 43274, - 43301, - 43312, - 43334, - 43360, - 43388, - 43396, - 43442, - 43471, - 43471, - 43520, - 43560, - 43584, - 43586, - 43588, - 43595, - 43616, - 43638, - 43642, - 43642, - 43648, - 43695, - 43697, - 43697, - 43701, - 43702, - 43705, - 43709, - 43712, - 43712, - 43714, - 43714, - 43739, - 43741, - 43744, - 43754, - 43762, - 43764, - 43777, - 43782, - 43785, - 43790, - 43793, - 43798, - 43808, - 43814, - 43816, - 43822, - 43968, - 44002, - 44032, - 44032, - 55203, - 55203, - 55216, - 55238, - 55243, - 55291, - 63744, - 64109, - 64112, - 64217, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500 - ]; - var unicodeES5IdCont = [ - 768, - 879, - 1155, - 1159, - 1425, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1477, - 1479, - 1479, - 1552, - 1562, - 1611, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 1984, - 1993, - 2027, - 2035, - 2070, - 2073, - 2075, - 2083, - 2085, - 2087, - 2089, - 2093, - 2137, - 2139, - 2276, - 2302, - 2304, - 2307, - 2362, - 2364, - 2366, - 2383, - 2385, - 2391, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2561, - 2563, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2641, - 2641, - 2662, - 2673, - 2677, - 2677, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2786, - 2787, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2884, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2914, - 2915, - 2918, - 2927, - 2946, - 2946, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3046, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3170, - 3171, - 3174, - 3183, - 3202, - 3203, - 3260, - 3260, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3298, - 3299, - 3302, - 3311, - 3330, - 3331, - 3390, - 3396, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3426, - 3427, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3981, - 3991, - 3993, - 4028, - 4038, - 4038, - 4139, - 4158, - 4160, - 4169, - 4182, - 4185, - 4190, - 4192, - 4194, - 4196, - 4199, - 4205, - 4209, - 4212, - 4226, - 4237, - 4239, - 4253, - 4957, - 4959, - 5906, - 5908, - 5938, - 5940, - 5970, - 5971, - 6002, - 6003, - 6068, - 6099, - 6109, - 6109, - 6112, - 6121, - 6155, - 6157, - 6160, - 6169, - 6313, - 6313, - 6432, - 6443, - 6448, - 6459, - 6470, - 6479, - 6576, - 6592, - 6600, - 6601, - 6608, - 6617, - 6679, - 6683, - 6741, - 6750, - 6752, - 6780, - 6783, - 6793, - 6800, - 6809, - 6912, - 6916, - 6964, - 6980, - 6992, - 7001, - 7019, - 7027, - 7040, - 7042, - 7073, - 7085, - 7088, - 7097, - 7142, - 7155, - 7204, - 7223, - 7232, - 7241, - 7248, - 7257, - 7376, - 7378, - 7380, - 7400, - 7405, - 7405, - 7410, - 7412, - 7616, - 7654, - 7676, - 7679, - 8204, - 8205, - 8255, - 8256, - 8276, - 8276, - 8400, - 8412, - 8417, - 8417, - 8421, - 8432, - 11503, - 11505, - 11647, - 11647, - 11744, - 11775, - 12330, - 12335, - 12441, - 12442, - 42528, - 42537, - 42607, - 42607, - 42612, - 42621, - 42655, - 42655, - 42736, - 42737, - 43010, - 43010, - 43014, - 43014, - 43019, - 43019, - 43043, - 43047, - 43136, - 43137, - 43188, - 43204, - 43216, - 43225, - 43232, - 43249, - 43264, - 43273, - 43302, - 43309, - 43335, - 43347, - 43392, - 43395, - 43443, - 43456, - 43472, - 43481, - 43561, - 43574, - 43587, - 43587, - 43596, - 43597, - 43600, - 43609, - 43643, - 43643, - 43696, - 43696, - 43698, - 43700, - 43703, - 43704, - 43710, - 43711, - 43713, - 43713, - 43755, - 43759, - 43765, - 43766, - 44003, - 44010, - 44012, - 44013, - 44016, - 44025, - 64286, - 64286, - 65024, - 65039, - 65056, - 65062, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343 - ]; - function LexLookUpUnicodeMap(code, map) { - var lo = 0; - var hi = map.length; - var mid; - while(lo + 1 < hi) { - mid = lo + (hi - lo) / 2; - mid -= mid % 2; - if(map[mid] <= code && code <= map[mid + 1]) { - return true; - } - if(code < map[mid]) { - hi = mid; - } else { - lo = mid + 2; - } - } - return false; - } - TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; - function LexIsUnicodeDigit(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdCont); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdCont); - } - } - TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; - function LexIsUnicodeIdStart(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdStart); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdStart); - } - } - TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; - function LexInitialize() { - TypeScript.initializeStaticTokens(); - autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; - autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; - autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; - autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; - autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; - autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; - autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; - autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; - autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; - autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; - TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); - for(var i in (TypeScript.TokenID)._map) { - if((i) <= TypeScript.TokenID.LimKeyword) { - TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); - } - } - for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { - if(LexIsIdentifierStartChar(j)) { - lexIdStartTable[j] = true; - } else { - lexIdStartTable[j] = false; - } - } - } - TypeScript.LexInitialize = LexInitialize; - function LexAdjustIndent(code, indentAmt) { - if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { - return indentAmt + 1; - } else { - if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { - return indentAmt - 1; - } else { - return indentAmt; - } - } - } - TypeScript.LexAdjustIndent = LexAdjustIndent; - function LexIsIdentifierStartChar(code) { - return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); - } - TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; - function LexIsDigit(code) { - return ((code >= 48) && (code <= 57)); - } - TypeScript.LexIsDigit = LexIsDigit; - function LexIsIdentifierChar(code) { - return lexIdStartTable[code] || LexIsDigit(code); - } - TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; - function LexMatchingOpen(code) { - if(code == TypeScript.LexCodeRBR) { - return TypeScript.LexCodeLBR; - } else { - if(code == TypeScript.LexCodeRC) { - return TypeScript.LexCodeLC; - } else { - if(code == TypeScript.LexCodeRPR) { - return TypeScript.LexCodeLPR; - } else { - return 0; - } - } - } - } - TypeScript.LexMatchingOpen = LexMatchingOpen; - (function (NumberScanState) { - NumberScanState._map = []; - NumberScanState._map[0] = "Start"; - NumberScanState.Start = 0; - NumberScanState._map[1] = "InFraction"; - NumberScanState.InFraction = 1; - NumberScanState._map[2] = "InEmptyFraction"; - NumberScanState.InEmptyFraction = 2; - NumberScanState._map[3] = "InExponent"; - NumberScanState.InExponent = 3; - })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); - var NumberScanState = TypeScript.NumberScanState; - (function (LexState) { - LexState._map = []; - LexState._map[0] = "Start"; - LexState.Start = 0; - LexState._map[1] = "InMultilineComment"; - LexState.InMultilineComment = 1; - LexState._map[2] = "InMultilineSingleQuoteString"; - LexState.InMultilineSingleQuoteString = 2; - LexState._map[3] = "InMultilineDoubleQuoteString"; - LexState.InMultilineDoubleQuoteString = 3; - })(TypeScript.LexState || (TypeScript.LexState = {})); - var LexState = TypeScript.LexState; - (function (LexMode) { - LexMode._map = []; - LexMode._map[0] = "Line"; - LexMode.Line = 0; - LexMode._map[1] = "File"; - LexMode.File = 1; - })(TypeScript.LexMode || (TypeScript.LexMode = {})); - var LexMode = TypeScript.LexMode; - (function (CommentStyle) { - CommentStyle._map = []; - CommentStyle._map[0] = "Line"; - CommentStyle.Line = 0; - CommentStyle._map[1] = "Block"; - CommentStyle.Block = 1; - })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); - var CommentStyle = TypeScript.CommentStyle; - var StringSourceText = (function () { - function StringSourceText(text) { - this.text = text; - } - StringSourceText.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringSourceText.prototype.getLength = function () { - return this.text.length; - }; - return StringSourceText; - })(); - TypeScript.StringSourceText = StringSourceText; - var SourceTextSegment = (function () { - function SourceTextSegment(segmentStart, segmentEnd, segment) { - this.segmentStart = segmentStart; - this.segmentEnd = segmentEnd; - this.segment = segment; - } - SourceTextSegment.prototype.charCodeAt = function (index) { - return this.segment.charCodeAt(index - this.segmentStart); - }; - SourceTextSegment.prototype.substring = function (start, end) { - return this.segment.substring(start - this.segmentStart, end - this.segmentStart); - }; - return SourceTextSegment; - })(); - TypeScript.SourceTextSegment = SourceTextSegment; - var AggerateSourceTextSegment = (function () { - function AggerateSourceTextSegment(seg1, seg2) { - this.seg1 = seg1; - this.seg2 = seg2; - } - AggerateSourceTextSegment.prototype.charCodeAt = function (index) { - if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { - return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); - } - return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); - }; - AggerateSourceTextSegment.prototype.substring = function (start, end) { - if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { - return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); - } - return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); - }; - return AggerateSourceTextSegment; - })(); - TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; - var ScannerTextStream = (function () { - function ScannerTextStream(sourceText) { - this.sourceText = sourceText; - this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); - this.len = this.sourceText.getLength(); - } - ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); - ScannerTextStream.prototype.max = function (a, b) { - return a >= b ? a : b; - }; - ScannerTextStream.prototype.min = function (a, b) { - return a <= b ? a : b; - }; - ScannerTextStream.prototype.fetchSegment = function (start, end) { - if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg.seg1; - } - if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg; - } - var prev = this.agg.seg1; - var s = prev.segmentEnd; - var e = TypeScript.max(s + 512, end); - e = TypeScript.min(e, this.len); - var src = this.sourceText.getText(s, e); - var newSeg = new SourceTextSegment(s, e, src); - this.agg.seg2 = prev; - this.agg.seg1 = newSeg; - return this.agg; - }; - ScannerTextStream.prototype.charCodeAt = function (index) { - return this.fetchSegment(index, index + 1).charCodeAt(index); - }; - ScannerTextStream.prototype.substring = function (start, end) { - return this.fetchSegment(start, end).substring(start, end); - }; - return ScannerTextStream; - })(); - TypeScript.ScannerTextStream = ScannerTextStream; - var SavedTokens = (function () { - function SavedTokens() { - this.prevToken = null; - this.curSavedToken = null; - this.prevSavedToken = null; - this.prevToken = null; - this.currentToken = 0; - this.tokens = new Array(); - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.lexState = LexState.Start; - this.commentStack = new Array(); - this.lineMap = []; - } - SavedTokens.prototype.previousToken = function () { - return this.prevToken; - }; - SavedTokens.prototype.close = function () { - this.currentToken = 0; - }; - SavedTokens.prototype.addToken = function (tok, scanner) { - this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); - }; - SavedTokens.prototype.scan = function () { - this.startLine = this.line; - this.startPos = this.col; - if(this.currentTokenIndex == this.currentTokens.length) { - if(this.line < this.lineMap.length) { - this.line++; - this.col = 0; - this.currentTokenIndex = 0; - this.currentTokens = this.tokensByLine[this.line]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(this.currentTokenIndex < this.currentTokens.length) { - this.prevToken = this.curSavedToken.tok; - this.prevSavedToken = this.curSavedToken; - this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; - var curToken = this.curSavedToken.tok; - this.pos = this.curSavedToken.limChar; - this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); - this.startPos = this.curSavedToken.minChar; - this.prevLine = this.line; - return curToken; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - }; - SavedTokens.prototype.syncToTok = function (offset) { - this.line = getLineNumberFromPosition(this.lineMap, offset); - this.currentTokenIndex = 0; - var tmpCol = offset - this.lineMap[this.line]; - while((this.lexStateByLine[this.line] == LexState.InMultilineComment) && (this.line > 0)) { - this.line--; - tmpCol = 0; - } - var lenMin1 = this.lineMap.length - 1; - this.currentTokens = this.tokensByLine[this.line]; - while((this.currentTokens.length == 0) && (this.line < lenMin1)) { - this.line++; - this.currentTokens = this.tokensByLine[this.line]; - tmpCol = 0; - } - if(this.line <= lenMin1) { - while((this.currentTokenIndex < this.currentTokens.length) && (tmpCol > this.currentTokens[this.currentTokenIndex].limChar)) { - this.currentTokenIndex++; - } - if(this.currentTokenIndex < this.currentTokens.length) { - this.col = this.currentTokens[this.currentTokenIndex].minChar; - return this.col + this.lineMap[this.line]; - } - } - return -1; - }; - SavedTokens.prototype.lastTokenLimChar = function () { - if(this.prevSavedToken !== null) { - return this.prevSavedToken.limChar; - } else { - return 0; - } - }; - SavedTokens.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - SavedTokens.prototype.pushComment = function (comment) { - this.commentStack.push(comment); - }; - SavedTokens.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - SavedTokens.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - SavedTokens.prototype.resetComments = function () { - this.commentStack = []; - }; - SavedTokens.prototype.setSourceText = function (newSrc, textMode) { - }; - SavedTokens.prototype.setErrorHandler = function (reportError) { - }; - SavedTokens.prototype.getLookAheadToken = function () { - throw new Error("Invalid operation."); - }; - return SavedTokens; - })(); - TypeScript.SavedTokens = SavedTokens; - var Scanner = (function () { - function Scanner() { - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.pos = 0; - this.startPos = 0; - this.len = 0; - this.lineMap = []; - this.ch = TypeScript.LexEOF; - this.lexState = LexState.Start; - this.mode = LexMode.File; - this.scanComments = true; - this.interveningWhitespace = false; - this.interveningWhitespacePos = 0; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.commentStack = new Array(); - this.saveScan = null; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - this.startCol = this.col; - this.startLine = this.line; - this.lineMap[1] = 0; - if(!TypeScript.LexKeywordTable) { - LexInitialize(); - } - } - Scanner.prototype.previousToken = function () { - return this.prevTok; - }; - Scanner.prototype.setSourceText = function (newSrc, textMode) { - this.mode = textMode; - this.scanComments = (this.mode === LexMode.Line); - this.pos = 0; - this.interveningWhitespacePos = 0; - this.startPos = 0; - this.line = 1; - this.col = 0; - this.startCol = this.col; - this.startLine = this.line; - this.len = 0; - this.src = newSrc.getText(0, newSrc.getLength()); - this.len = this.src.length; - this.lineMap = []; - this.lineMap[1] = 0; - this.commentStack = []; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - }; - Scanner.prototype.setErrorHandler = function (reportError) { - this.reportError = reportError; - }; - Scanner.prototype.setSaveScan = function (savedTokens) { - this.saveScan = savedTokens; - }; - Scanner.prototype.setText = function (newSrc, textMode) { - this.setSourceText(new StringSourceText(newSrc), textMode); - }; - Scanner.prototype.setScanComments = function (value) { - this.scanComments = value; - }; - Scanner.prototype.getLexState = function () { - return this.lexState; - }; - Scanner.prototype.tokenStart = function () { - this.startPos = this.pos; - this.startLine = this.line; - this.startCol = this.col; - this.interveningWhitespace = false; - }; - Scanner.prototype.peekChar = function () { - if(this.pos < this.len) { - return this.src.charCodeAt(this.pos); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.peekCharAt = function (index) { - if(index < this.len) { - return this.src.charCodeAt(index); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.IsHexDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.IsOctalDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.scanHexDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanOctalDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsOctalDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanDecimalNumber = function (state) { - var atLeastOneDigit = false; - var svPos = this.pos; - var svCol = this.col; - for(; ; ) { - if(LexIsDigit(this.ch)) { - atLeastOneDigit = true; - if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { - state = NumberScanState.InFraction; - } - this.nextChar(); - } else { - if(this.ch == TypeScript.LexCodeDOT) { - if(state == NumberScanState.Start) { - this.nextChar(); - state = NumberScanState.InEmptyFraction; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } else { - if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { - if(state == NumberScanState.Start) { - if(atLeastOneDigit) { - atLeastOneDigit = false; - this.nextChar(); - state = NumberScanState.InExponent; - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else { - if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { - this.nextChar(); - state = NumberScanState.InExponent; - atLeastOneDigit = false; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } - } else { - if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { - if(state == NumberScanState.InExponent) { - if(!atLeastOneDigit) { - this.nextChar(); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else { - if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); - } - } - } - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); - } - } - } - } - } - } - }; - Scanner.prototype.scanNumber = function () { - if(this.peekChar() == TypeScript.LexCode_0) { - switch(this.peekCharAt(this.pos + 1)) { - case TypeScript.LexCode_x: - case TypeScript.LexCode_X: { - this.advanceChar(2); - return this.scanHexDigits(); - - } - case TypeScript.LexCode_8: - case TypeScript.LexCode_9: - case TypeScript.LexCodeDOT: { - return this.scanDecimalNumber(NumberScanState.Start); - - } - default: { - return this.scanOctalDigits(); - - } - } - } else { - return this.scanDecimalNumber(NumberScanState.Start); - } - }; - Scanner.prototype.scanFraction = function () { - return this.scanDecimalNumber(NumberScanState.InFraction); - }; - Scanner.prototype.newLine = function () { - this.col = 0; - if(this.mode == LexMode.File) { - this.line++; - this.lineMap[this.line] = this.pos + 1; - } - }; - Scanner.prototype.finishMultilineComment = function () { - var ch2; - this.lexState = LexState.InMultilineComment; - while(this.pos < this.len) { - if(this.ch == TypeScript.LexCodeMUL) { - ch2 = this.peekCharAt(this.pos + 1); - if(ch2 == TypeScript.LexCodeSLH) { - this.advanceChar(2); - if(this.mode == LexMode.File) { - this.tokenStart(); - } - this.lexState = LexState.Start; - return true; - } - } else { - if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - this.nextChar(); - return false; - } - } else { - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - } - } - this.nextChar(); - } - return false; - }; - Scanner.prototype.pushComment = function (comment) { - this.commentStack.push(comment); - }; - Scanner.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - Scanner.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - Scanner.prototype.resetComments = function () { - this.commentStack = []; - }; - Scanner.prototype.endsLine = function (c) { - return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); - }; - Scanner.prototype.finishSinglelineComment = function () { - while(this.pos < this.len) { - if(this.endsLine(this.ch)) { - break; - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - this.nextChar(); - } - if(this.mode == LexMode.File) { - this.tokenStart(); - } - }; - Scanner.prototype.tokenText = function () { - return this.src.substring(this.startPos, this.pos); - }; - Scanner.prototype.findClosingSLH = function () { - var index = this.pos; - var ch2 = this.src.charCodeAt(index); - var prevCh = 0; - var liveEsc = false; - while(!this.endsLine(ch2) && (index < this.len)) { - if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { - return index; - } - prevCh = ch2; - index++; - if(liveEsc) { - liveEsc = false; - } else { - liveEsc = (prevCh == TypeScript.LexCodeBSL); - } - ch2 = this.src.charCodeAt(index); - } - return -1; - }; - Scanner.prototype.speculateRegex = function () { - if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { - return null; - } - var svPos = this.pos; - var svCol = this.col; - var index = this.findClosingSLH(); - if(index > 0) { - var pattern = this.src.substring(svPos, index); - var flags = ""; - this.pos = index + 1; - this.ch = this.peekChar(); - var flagsStart = this.pos; - while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { - this.nextChar(); - } - if((this.pos - flagsStart) > 3) { - return null; - } else { - flags = this.src.substring(flagsStart, this.pos); - } - var regex = undefined; - try { - regex = new RegExp(pattern, flags); - } catch (regexException) { - } - if(regex) { - this.col = svCol + (this.pos - this.startPos); - return new TypeScript.RegularExpressionLiteralToken(regex); - } - } - this.pos = svPos; - this.col = svCol; - return null; - }; - Scanner.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - Scanner.prototype.lastTokenLimChar = function () { - return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; - }; - Scanner.prototype.advanceChar = function (amt) { - this.pos += amt; - this.col += amt; - this.ch = this.peekChar(); - }; - Scanner.prototype.nextChar = function () { - this.pos++; - this.col++; - this.ch = this.peekChar(); - }; - Scanner.prototype.getLookAheadToken = function () { - var prevLine = this.prevLine; - var line = this.line; - var col = this.col; - var pos = this.pos; - var startPos = this.startPos; - var startCol = this.startCol; - var startLine = this.startLine; - var ch = this.ch; - var prevTok = this.prevTok; - var lexState = this.lexState; - var interveningWhitespace = this.interveningWhitespace; - var interveningWhitespacePos = this.interveningWhitespacePos; - var leftCurlyCount = this.leftCurlyCount; - var rightCurlyCount = this.rightCurlyCount; - var seenUnicodeChar = this.seenUnicodeChar; - var seenUnicodeCharInComment = this.seenUnicodeCharInComment; - var commentStackLength = this.commentStack.length; - var lookAheadToken = this.scan(); - this.prevLine = prevLine; - this.line = line; - this.col = col; - this.pos = pos; - this.startPos = startPos; - this.startCol = startCol; - this.startLine = startLine; - this.ch = ch; - this.prevTok = prevTok; - this.lexState = lexState; - this.interveningWhitespace = interveningWhitespace; - this.interveningWhitespacePos = interveningWhitespacePos; - this.leftCurlyCount = leftCurlyCount; - this.rightCurlyCount = rightCurlyCount; - this.seenUnicodeChar = seenUnicodeChar; - this.seenUnicodeCharInComment = seenUnicodeCharInComment; - this.commentStack.length = commentStackLength; - return lookAheadToken; - }; - Scanner.prototype.scanInLine = function () { - if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { - this.ch = this.peekChar(); - var commentLine = this.line; - this.finishMultilineComment(); - if(this.startPos < this.pos) { - var commentText = this.src.substring(this.startPos, this.pos); - this.tokenStart(); - return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } else { - if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { - this.ch = TypeScript.LexCodeAPO; - this.lexState = LexState.Start; - return this.scanStringConstant(); - } else { - if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { - this.ch = TypeScript.LexCodeQUO; - this.lexState = LexState.Start; - return this.scanStringConstant(); - } - } - } - this.prevLine = this.line; - var prevTok = this.innerScan(); - if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { - this.prevTok = prevTok; - } - return prevTok; - }; - Scanner.prototype.scan = function () { - this.prevLine = this.line; - this.prevTok = this.innerScan(); - if(this.saveScan) { - this.saveScan.addToken(this.prevTok, this); - } - return this.prevTok; - }; - Scanner.prototype.isValidUnicodeIdentifierChar = function () { - var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); - this.seenUnicodeChar = this.seenUnicodeChar || valid; - return valid; - }; - Scanner.prototype.scanStringConstant = function () { - var endCode = this.ch; - this.nextChar(); - scanStringConstantLoop: -for(; ; ) { - switch(this.ch) { - case TypeScript.LexEOF: { - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - - } - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: { - this.seenUnicodeChar = true; - - } - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: { - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - - } - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: { - if(this.ch == endCode) { - this.nextChar(); - break scanStringConstantLoop; - } - break; - - } - case TypeScript.LexCodeBSL: { - this.nextChar(); - switch(this.ch) { - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: - case TypeScript.LexCodeBSL: { - this.nextChar(); - continue scanStringConstantLoop; - - } - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: { - this.seenUnicodeChar = true; - - } - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: { - if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { - this.nextChar(); - } - this.nextChar(); - this.newLine(); - if(this.mode == LexMode.Line) { - this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; - break scanStringConstantLoop; - } - break; - - } - case TypeScript.LexCode_x: - case TypeScript.LexCode_u: { - var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; - this.nextChar(); - for(var i = 0; i < expectedHexDigits; i++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - break; - } - } - continue scanStringConstantLoop; - - } - } - break; - - } - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeChar = true; - } - this.nextChar(); - } - return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); - }; - Scanner.prototype.scanIdentifier = function () { - var hasEscape = false; - var isFirstChar = (this.ch == TypeScript.LexCodeBSL); - var hasUnicode = false; - for(; ; ) { - while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { - this.nextChar(); - } - if(this.ch == TypeScript.LexCodeBSL) { - this.nextChar(); - if(this.ch == TypeScript.LexCode_u) { - this.nextChar(); - for(var h = 0; h < 4; h++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } - var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); - if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { - } else { - this.reportScannerError("Invalid identifier character"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - hasEscape = true; - isFirstChar = false; - continue; - } - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - break; - } - var id; - var text = this.src.substring(this.startPos, this.pos); - if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { - return TypeScript.staticTokens[id]; - } else { - return new TypeScript.IdentifierToken(text, hasEscape); - } - }; - Scanner.prototype.innerScan = function () { - var rtok; - this.tokenStart(); - this.ch = this.peekChar(); - start: -while(this.pos < this.len) { - if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { - return this.scanIdentifier(); - } else { - if(this.ch == TypeScript.LexCodeSpace) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - do { - this.nextChar(); - }while(this.ch == TypeScript.LexCodeSpace) - if(this.mode == LexMode.Line) { - var whitespaceText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); - } else { - this.tokenStart(); - this.interveningWhitespace = true; - } - } else { - if(this.ch == TypeScript.LexCodeSLH) { - this.nextChar(); - var commentText; - if(this.ch == TypeScript.LexCodeSLH) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.finishSinglelineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else { - if(this.ch == TypeScript.LexCodeMUL) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.nextChar(); - this.finishMultilineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var endsLine = this.endsLine(this.peekChar()); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else { - var regexTok = this.speculateRegex(); - if(regexTok) { - return regexTok; - } else { - if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Slash]; - } - } - } - } - } else { - if(this.ch == TypeScript.LexCodeSMC) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - } else { - if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { - return this.scanStringConstant(); - } else { - if(autoToken[this.ch]) { - var atok = autoToken[this.ch]; - if(atok.tokenId == TypeScript.TokenID.OpenBrace) { - this.leftCurlyCount++; - } else { - if(atok.tokenId == TypeScript.TokenID.CloseBrace) { - this.rightCurlyCount++; - } - } - this.nextChar(); - return atok; - } else { - if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { - rtok = this.scanNumber(); - if(rtok) { - return rtok; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } else { - switch(this.ch) { - case TypeScript.LexCodeTAB: - case TypeScript.LexCodeVTAB: { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - if(this.mode == LexMode.Line) { - do { - this.nextChar(); - }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)) - var wsText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); - } else { - this.interveningWhitespace = true; - } - - } - case 255: - case 254: - case 239: - case 187: - case 191: - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - case TypeScript.LexCodeNWL: - case TypeScript.LexCodeRET: { - if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - this.nextChar(); - this.tokenStart(); - this.interveningWhitespace = true; - break; - - } - case TypeScript.LexCodeDOT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } else { - this.nextChar(); - rtok = this.scanFraction(); - if(rtok) { - return rtok; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } - } - - case TypeScript.LexCodeEQ: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; - } - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Equals]; - } - } - - } - case TypeScript.LexCodeBNG: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; - } - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; - } - - } - case TypeScript.LexCodePLS: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Plus]; - } - } - - } - case TypeScript.LexCodeMIN: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Minus]; - } - } - - } - case TypeScript.LexCodeMUL: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; - } - - } - case TypeScript.LexCodePCT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Percent]; - } - - } - case TypeScript.LexCodeLT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; - } - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; - } - } - - } - case TypeScript.LexCodeGT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; - } else { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { - this.advanceChar(4); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; - } else { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; - } - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; - } - } - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; - } - } - - } - case TypeScript.LexCodeXOR: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Caret]; - } - - } - case TypeScript.LexCodeBAR: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Bar]; - } - } - - } - case TypeScript.LexCodeAMP: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.And]; - } - } - - } - default: { - this.reportScannerError("Invalid character"); - this.nextChar(); - continue start; - - } - } - } - } - } - } - } - } - } - } - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - }; - Scanner.prototype.reportScannerError = function (message) { - if(this.reportError) { - this.reportError(message); - } - }; - return Scanner; - })(); - TypeScript.Scanner = Scanner; - function convertTokToIDName(tok) { - return convertTokToIDBase(tok, true, false); - } - TypeScript.convertTokToIDName = convertTokToIDName; - function convertTokToID(tok, strictMode) { - return convertTokToIDBase(tok, false, strictMode); - } - TypeScript.convertTokToID = convertTokToID; - function convertTokToIDBase(tok, identifierName, strictMode) { - if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { - var tokInfo = TypeScript.lookupToken(tok.tokenId); - if(tokInfo != undefined) { - var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; - if(strictMode) { - resFlags |= TypeScript.Reservation.JavascriptFutureStrict; - } - if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { - return true; - } - } else { - return false; - } - } else { - return false; - } - } - function getLineNumberFromPosition(lineMap, position) { - if(position === -1) { - return 0; - } - var min = 0; - var max = lineMap.length - 1; - while(min < max) { - var med = (min + max) >> 1; - if(position < lineMap[med]) { - max = med - 1; - } else { - if(position < lineMap[med + 1]) { - min = max = med; - } else { - min = med + 1; - } - } - } - return min; - } - TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; - function getSourceLineColFromMap(lineCol, minChar, lineMap) { - var line = getLineNumberFromPosition(lineMap, minChar); - if(line > 0) { - lineCol.line = line; - lineCol.col = (minChar - lineMap[line]); - } - } - TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; - function getLineColumnFromPosition(script, position) { - var result = { - line: -1, - col: -1 - }; - getSourceLineColFromMap(result, position, script.locationInfo.lineMap); - if(result.col >= 0) { - result.col++; - } - return result; - } - TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; - function getPositionFromLineColumn(script, line, column) { - return script.locationInfo.lineMap[line] + (column - 1); - } - TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; - function isPrimitiveTypeToken(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.String: { - return true; - - } - } - return false; - } - TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; - function isModifier(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Public: - case TypeScript.TokenID.Private: - case TypeScript.TokenID.Static: { - return true; - - } - } - return false; - } - TypeScript.isModifier = isModifier; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AssignScopeContext = (function () { - function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { - this.scopeChain = scopeChain; - this.typeFlow = typeFlow; - this.modDeclChain = modDeclChain; - } - return AssignScopeContext; - })(); - TypeScript.AssignScopeContext = AssignScopeContext; - function pushAssignScope(scope, context, type, classType, fnc) { - var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); - chain.thisType = type; - chain.classType = classType; - chain.fnc = fnc; - context.scopeChain = chain; - } - TypeScript.pushAssignScope = pushAssignScope; - function popAssignScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popAssignScope = popAssignScope; - function instanceCompare(a, b) { - if(((a == null) || (!a.isInstanceProperty()))) { - return b; - } else { - return a; - } - } - TypeScript.instanceCompare = instanceCompare; - function instanceFilterStop(s) { - return s.isInstanceProperty(); - } - TypeScript.instanceFilterStop = instanceFilterStop; - var ScopeSearchFilter = (function () { - function ScopeSearchFilter(select, stop) { - this.select = select; - this.stop = stop; - this.result = null; - } - ScopeSearchFilter.prototype.reset = function () { - this.result = null; - }; - ScopeSearchFilter.prototype.update = function (b) { - this.result = this.select(this.result, b); - if(this.result) { - return this.stop(this.result); - } else { - return false; - } - }; - return ScopeSearchFilter; - })(); - TypeScript.ScopeSearchFilter = ScopeSearchFilter; - TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); - function preAssignModuleScopes(ast, context) { - var moduleDecl = ast; - var memberScope = null; - var aggScope = null; - if(moduleDecl.name && moduleDecl.mod) { - moduleDecl.name.sym = moduleDecl.mod.symbol; - } - var mod = moduleDecl.mod; - if(!mod) { - return; - } - memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); - mod.memberScope = memberScope; - context.modDeclChain.push(moduleDecl); - context.typeFlow.checker.currentModDecl = moduleDecl; - aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - mod.containedScope = aggScope; - if(mod.symbol) { - context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); - } - } - TypeScript.preAssignModuleScopes = preAssignModuleScopes; - function preAssignClassScopes(ast, context) { - var classDecl = ast; - var memberScope = null; - var aggScope = null; - if(classDecl.name && classDecl.type) { - classDecl.name.sym = classDecl.type.symbol; - } - var classType = ast.type; - if(classType) { - var classSym = classType.symbol; - memberScope = context.typeFlow.checker.scopeOf(classType); - aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - classType.containedScope = aggScope; - classType.memberScope = memberScope; - var instanceType = classType.instanceType; - memberScope = context.typeFlow.checker.scopeOf(instanceType); - instanceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, instanceType, classType, null); - instanceType.containedScope = aggScope; - } else { - ast.type = context.typeFlow.anyType; - } - } - TypeScript.preAssignClassScopes = preAssignClassScopes; - function preAssignInterfaceScopes(ast, context) { - var interfaceDecl = ast; - var memberScope = null; - var aggScope = null; - if(interfaceDecl.name && interfaceDecl.type) { - interfaceDecl.name.sym = interfaceDecl.type.symbol; - } - var interfaceType = ast.type; - memberScope = context.typeFlow.checker.scopeOf(interfaceType); - interfaceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - interfaceType.containedScope = aggScope; - } - TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; - function preAssignWithScopes(ast, context) { - var withStmt = ast; - var withType = withStmt.type; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var withType = new TypeScript.Type(); - var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); - withType.members = members; - withType.ambientMembers = ambientMembers; - withType.symbol = withSymbol; - withType.setHasImplementation(); - withStmt.type = withType; - var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); - pushAssignScope(withScope, context, null, null, null); - withType.containedScope = withScope; - } - TypeScript.preAssignWithScopes = preAssignWithScopes; - function preAssignFuncDeclScopes(ast, context) { - var funcDecl = ast; - var container = null; - var localContainer = null; - if(funcDecl.type) { - localContainer = ast.type.symbol; - } - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isInnerStatic = isStatic && context.scopeChain.fnc != null; - var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; - if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { - var instType = context.scopeChain.thisType; - if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(!funcDecl.isMethod() || isStatic) { - parentScope = instType.constructorScope; - } else { - parentScope = instType.containedScope; - } - } else { - if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { - parentScope = instType.constructorScope; - } else { - if(isStatic && context.scopeChain.classType) { - parentScope = context.scopeChain.classType.containedScope; - } else { - parentScope = instType.containedScope; - } - } - } - container = instType.symbol; - } else { - if(funcDecl.isConstructor && context.scopeChain.thisType) { - container = context.scopeChain.thisType.symbol; - } - } - if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { - if(context.scopeChain.fnc && context.scopeChain.fnc.type) { - container = context.scopeChain.fnc.type.symbol; - } - var funcScope = null; - var outerFnc = context.scopeChain.fnc; - var nameText = funcDecl.name ? funcDecl.name.actualText : null; - var fgSym = null; - if(isStatic) { - if(outerFnc.type.members == null && container.getType().memberScope) { - outerFnc.type.members = ((container).type.memberScope).valueMembers; - } - funcScope = context.scopeChain.fnc.type.memberScope; - outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; - } else { - funcScope = context.scopeChain.scope; - } - if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { - if(isStatic) { - fgSym = funcScope.findLocal(nameText, false, false); - } else { - fgSym = funcScope.findLocal(nameText, false, false); - } - } - context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); - if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); - } - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; - } - if(funcDecl.name && funcDecl.type) { - funcDecl.name.sym = funcDecl.type.symbol; - } - funcDecl.scopeType = funcDecl.type; - if(funcDecl.isOverload) { - return; - } - var funcTable = new TypeScript.StringHashTable(); - var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); - var ambientFuncTable = new TypeScript.StringHashTable(); - var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); - var funcStaticTable = new TypeScript.StringHashTable(); - var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); - var ambientFuncStaticTable = new TypeScript.StringHashTable(); - var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); - funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; - var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); - var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); - if(funcDecl.isConstructor && context.scopeChain.thisType) { - context.scopeChain.thisType.constructorScope = locals; - } - funcDecl.symbols = funcTable; - if(!funcDecl.isSpecialFn()) { - var group = funcDecl.type; - var signature = funcDecl.signature; - if(!funcDecl.isConstructor) { - group.containedScope = locals; - locals.container = group.symbol; - group.memberScope = statics; - statics.container = group.symbol; - } - funcDecl.enclosingFnc = context.scopeChain.fnc; - group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; - var fgSym = ast.type.symbol; - if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { - context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); - context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); - } - if(signature.parameters) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); - } - } - context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); - } - if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; - pushAssignScope(locals, context, thisType, null, funcDecl); - } - if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { - if(funcDecl.name.sym) { - funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); - } - } - } - TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; - function preAssignCatchScopes(ast, context) { - var catchBlock = ast; - if(catchBlock.param) { - var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); - catchBlock.containedScope = catchLocals; - pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); - } - } - TypeScript.preAssignCatchScopes = preAssignCatchScopes; - function preAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - list.enclosingScope = context.scopeChain.scope; - } else { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - preAssignModuleScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - preAssignClassScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - preAssignInterfaceScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - preAssignWithScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - preAssignFuncDeclScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.Catch) { - preAssignCatchScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.TypeRef) { - go = false; - } - } - } - } - } - } - } - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preAssignScopes = preAssignScopes; - function postAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var prevModDecl = ast; - popAssignScope(context); - context.modDeclChain.pop(); - if(context.modDeclChain.length >= 1) { - context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; - } - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - popAssignScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - popAssignScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - popAssignScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { - popAssignScope(context); - } - } else { - if(ast.nodeType == TypeScript.NodeType.Catch) { - var catchBlock = ast; - if(catchBlock.param) { - popAssignScope(context); - } - } else { - go = false; - } - } - } - } - } - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.postAssignScopes = postAssignScopes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var TypeCollectionContext = (function () { - function TypeCollectionContext(scopeChain, checker) { - this.scopeChain = scopeChain; - this.checker = checker; - this.script = null; - } - return TypeCollectionContext; - })(); - TypeScript.TypeCollectionContext = TypeCollectionContext; - var MemberScopeContext = (function () { - function MemberScopeContext(flow, pos, matchFlag) { - this.flow = flow; - this.pos = pos; - this.matchFlag = matchFlag; - this.type = null; - this.ast = null; - this.options = new TypeScript.AstWalkOptions(); - } - return MemberScopeContext; - })(); - TypeScript.MemberScopeContext = MemberScopeContext; - var EnclosingScopeContext = (function () { - function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { - this.logger = logger; - this.script = script; - this.text = text; - this.pos = pos; - this.isMemberCompletion = isMemberCompletion; - this.scopeGetter = null; - this.objectLiteralScopeGetter = null; - this.scopeStartAST = null; - this.skipNextFuncDeclForClass = false; - this.deepestModuleDecl = null; - this.enclosingClassDecl = null; - this.enclosingObjectLit = null; - this.publicsOnly = true; - this.useFullAst = false; - } - EnclosingScopeContext.prototype.getScope = function () { - return this.scopeGetter(); - }; - EnclosingScopeContext.prototype.getObjectLiteralScope = function () { - return this.objectLiteralScopeGetter(); - }; - EnclosingScopeContext.prototype.getScopeAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScopePosition = function () { - return this.scopeStartAST.minChar; - }; - EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { - return this.getScriptFragmentStartAST().minChar; - }; - EnclosingScopeContext.prototype.getScriptFragment = function () { - if(this.scriptFragment == null) { - var ast = this.getScriptFragmentStartAST(); - var minChar = ast.minChar; - var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); - this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; - } - return this.scriptFragment; - }; - return EnclosingScopeContext; - })(); - TypeScript.EnclosingScopeContext = EnclosingScopeContext; - function preFindMemberScope(ast, parent, walker) { - var memScope = walker.state; - if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { - memScope.ast = ast; - if((ast.type == null) && (memScope.pos >= 0)) { - memScope.flow.inScopeTypeCheck(ast, memScope.scope); - } - memScope.type = ast.type; - memScope.options.stopWalk(); - } - return ast; - } - TypeScript.preFindMemberScope = preFindMemberScope; - function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { - var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); - var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); - chain.thisType = thisType; - chain.classType = classType; - chain.moduleDecl = moduleDecl; - context.scopeChain = chain; - } - TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; - function popTypeCollectionScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popTypeCollectionScope = popTypeCollectionScope; - function preFindEnclosingScope(ast, parent, walker) { - var context = walker.state; - var minChar = ast.minChar; - var limChar = ast.limChar; - if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { - limChar = context.pos; - } - if((minChar <= context.pos) && (limChar >= context.pos)) { - switch(ast.nodeType) { - case TypeScript.NodeType.Script: { - var script = ast; - context.scopeGetter = function () { - return script.bod === null ? null : script.bod.enclosingScope; - }; - context.scopeStartAST = script; - break; - - } - case TypeScript.NodeType.ClassDeclaration: { - context.scopeGetter = function () { - return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; - }; - context.scopeStartAST = ast; - context.enclosingClassDecl = ast; - break; - - } - case TypeScript.NodeType.ObjectLit: { - var objectLit = ast; - if(objectLit.targetType) { - context.scopeGetter = function () { - return objectLit.targetType.containedScope; - }; - context.objectLiteralScopeGetter = function () { - return objectLit.targetType.memberScope; - }; - context.enclosingObjectLit = objectLit; - } - break; - - } - case TypeScript.NodeType.ModuleDeclaration: { - context.deepestModuleDecl = ast; - context.scopeGetter = function () { - return ast.type === null ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - - } - case TypeScript.NodeType.InterfaceDeclaration: { - context.scopeGetter = function () { - return (ast.type === null) ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - - } - case TypeScript.NodeType.FuncDecl: { - { - var funcDecl = ast; - if(context.skipNextFuncDeclForClass) { - context.skipNextFuncDeclForClass = false; - } else { - context.scopeGetter = function () { - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(ast.type && ast.type.enclosingType) { - return ast.type.enclosingType.constructorScope; - } - } - if(funcDecl.scopeType) { - return funcDecl.scopeType.containedScope; - } - if(funcDecl.type) { - return funcDecl.type.containedScope; - } - return null; - }; - context.scopeStartAST = ast; - } - } - break; - - } - } - walker.options.goChildren = true; - } else { - walker.options.goChildren = false; - } - return ast; - } - TypeScript.preFindEnclosingScope = preFindEnclosingScope; - function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { - var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); - TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); - if(context.scopeStartAST === null) { - return null; - } - return context; - } - TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Signature = (function () { - function Signature() { - this.hasVariableArgList = false; - this.parameters = null; - this.declAST = null; - this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - this.nonOptionalParameterCount = 0; - } - Signature.prototype.specializeType = function (pattern, replacement, checker) { - var result = new Signature(); - if(this.hasVariableArgList) { - result.hasVariableArgList = true; - } - result.returnType = new TypeScript.TypeLink(); - if(this.returnType.type) { - result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); - } else { - result.returnType.type = checker.anyType; - } - if(this.parameters) { - result.parameters = []; - for(var i = 0, len = this.parameters.length; i < len; i++) { - var oldSym = this.parameters[i]; - var paramDef = new TypeScript.ValueLocation(); - var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); - paramSym.declAST = this.declAST; - paramDef.symbol = paramSym; - paramDef.typeLink = new TypeScript.TypeLink(); - result.parameters[i] = paramSym; - var oldType = oldSym.getType(); - if(oldType) { - paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); - paramSym.declAST.type = paramDef.typeLink.type; - } else { - paramDef.typeLink.type = checker.anyType; - } - } - } - result.nonOptionalParameterCount = this.nonOptionalParameterCount; - result.declAST = this.declAST; - return result; - }; - Signature.prototype.toString = function () { - return this.toStringHelper(false, false, null); - }; - Signature.prototype.toStringHelper = function (shortform, brackets, scope) { - return this.toStringHelperEx(shortform, brackets, scope).toString(); - }; - Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { - if (typeof prefix === "undefined") { prefix = ""; } - var builder = new TypeScript.MemberNameArray(); - if(brackets) { - builder.prefix = prefix + "["; - } else { - builder.prefix = prefix + "("; - } - var paramLen = this.parameters.length; - var len = this.hasVariableArgList ? paramLen - 1 : paramLen; - for(var i = 0; i < len; i++) { - builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - if(i < paramLen - 1) { - builder.add(TypeScript.MemberName.create(", ")); - } - } - if(this.hasVariableArgList) { - builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - } - if(shortform) { - if(brackets) { - builder.add(TypeScript.MemberName.create("] => ")); - } else { - builder.add(TypeScript.MemberName.create(") => ")); - } - } else { - if(brackets) { - builder.add(TypeScript.MemberName.create("]: ")); - } else { - builder.add(TypeScript.MemberName.create("): ")); - } - } - if(this.returnType.type) { - builder.add(this.returnType.type.getScopedTypeNameEx(scope)); - } else { - builder.add(TypeScript.MemberName.create("any")); - } - return builder; - }; - return Signature; - })(); - TypeScript.Signature = Signature; - var SignatureGroup = (function () { - function SignatureGroup() { - this.signatures = []; - this.hasImplementation = true; - this.definitionSignature = null; - this.hasBeenTypechecked = false; - this.flags = TypeScript.SignatureFlags.None; - } - SignatureGroup.prototype.addSignature = function (signature) { - if(this.signatures == null) { - this.signatures = new Array(); - } - this.signatures[this.signatures.length] = signature; - if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Definition)) { - this.definitionSignature = signature; - } - }; - SignatureGroup.prototype.toString = function () { - return this.signatures.toString(); - }; - SignatureGroup.prototype.toStrings = function (prefix, shortform, scope) { - var result = []; - var len = this.signatures.length; - if(len > 1) { - shortform = false; - } - for(var i = 0; i < len; i++) { - if(len > 1 && this.signatures[i] == this.definitionSignature) { - continue; - } - if(this.flags & TypeScript.SignatureFlags.IsIndexer) { - result.push(this.signatures[i].toStringHelperEx(shortform, true, scope)); - } else { - result.push(this.signatures[i].toStringHelperEx(shortform, false, scope, prefix)); - } - } - return result; - }; - SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { - var result = new SignatureGroup(); - if(this.signatures) { - for(var i = 0, len = this.signatures.length; i < len; i++) { - result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); - } - } - return result; - }; - SignatureGroup.prototype.verifySignatures = function (checker) { - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - for(var j = i + 1; j < len; j++) { - if(this.signatures[i].declAST && this.signatures[j].declAST && (!TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Definition) && !TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Definition)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); - } - } - if(this.definitionSignature) { - if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); - } - } - } - } - }; - SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { - if(this.hasBeenTypechecked) { - return; - } - this.hasBeenTypechecked = true; - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); - } - if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); - } - checker.typeFlow.typeCheck(this.signatures[i].declAST); - } - this.verifySignatures(checker); - } - }; - return SignatureGroup; - })(); - TypeScript.SignatureGroup = SignatureGroup; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeCheckStatus) { - TypeCheckStatus._map = []; - TypeCheckStatus._map[0] = "NotStarted"; - TypeCheckStatus.NotStarted = 0; - TypeCheckStatus._map[1] = "Started"; - TypeCheckStatus.Started = 1; - TypeCheckStatus._map[2] = "Finished"; - TypeCheckStatus.Finished = 2; - })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); - var TypeCheckStatus = TypeScript.TypeCheckStatus; - function aLexicallyEnclosesB(a, b) { - if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; - } else { - return false; - } - } - TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; - function aEnclosesB(a, b) { - while(a.container) { - if(a == b || aLexicallyEnclosesB(a.container, b)) { - return true; - } - a = a.container; - } - return false; - } - TypeScript.aEnclosesB = aEnclosesB; - var Symbol = (function () { - function Symbol(name, location, length, unitIndex) { - this.name = name; - this.location = location; - this.length = length; - this.unitIndex = unitIndex; - this.bound = false; - this.flags = TypeScript.SymbolFlags.None; - this.isObjectLitField = false; - this.declAST = null; - this.declModule = null; - this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; - } - Symbol.prototype.instanceScope = function () { - return null; - }; - Symbol.prototype.isVariable = function () { - return false; - }; - Symbol.prototype.isMember = function () { - return false; - }; - Symbol.prototype.isInferenceSymbol = function () { - return false; - }; - Symbol.prototype.isWith = function () { - return false; - }; - Symbol.prototype.writeable = function () { - return false; - }; - Symbol.prototype.isType = function () { - return false; - }; - Symbol.prototype.getType = function () { - return null; - }; - Symbol.prototype.isAccessor = function () { - return false; - }; - Symbol.prototype.isInstanceProperty = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); - }; - Symbol.prototype.getTypeName = function (scope) { - return this.getTypeNameEx(scope).toString(); - }; - Symbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.toString()); - }; - Symbol.prototype.getOptionalNameString = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; - }; - Symbol.prototype.pathToRoot = function () { - var path = new Array(); - var node = this; - while(node && (node.name != TypeScript.globalId)) { - path[path.length] = node; - node = node.container; - } - return path; - }; - Symbol.prototype.findCommonAncestorPath = function (b) { - if(this.container == null) { - return new Array(); - } - var aPath = this.container.pathToRoot(); - var bPath; - if(b) { - bPath = b.pathToRoot(); - } else { - bPath = new Array(); - } - var commonNodeIndex = -1; - for(var i = 0, aLen = aPath.length; i < aLen; i++) { - var aNode = aPath[i]; - for(var j = 0, bLen = bPath.length; j < bLen; j++) { - var bNode = bPath[j]; - if(aNode == bNode) { - commonNodeIndex = i; - break; - } - } - if(commonNodeIndex >= 0) { - break; - } - } - if(commonNodeIndex >= 0) { - return aPath.slice(0, commonNodeIndex); - } else { - return aPath; - } - }; - Symbol.prototype.getPrettyName = function (scopeSymbol) { - return this.name; - }; - Symbol.prototype.scopeRelativeName = function (scope) { - if(scope == null) { - return this.getPrettyName(null) + this.getOptionalNameString(); - } - var lca = this.findCommonAncestorPath(scope.container); - var builder = ""; - for(var i = 0, len = lca.length; i < len; i++) { - var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); - builder = prettyName + "." + builder; - } - builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); - return builder; - }; - Symbol.prototype.fullName = function () { - var builder = this.name; - var ancestor = this.container; - while(ancestor && (ancestor.name != TypeScript.globalId)) { - builder = ancestor.name + "." + builder; - ancestor = ancestor.container; - } - return builder; - }; - Symbol.prototype.isExternallyVisible = function (checker) { - if(this == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return false; - } - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - return this.container == checker.gloMod; - } - return this.container.isExternallyVisible(checker); - }; - Symbol.prototype.visible = function (scope, checker) { - if(checker == null || this.container == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return true; - } else { - return aEnclosesB(this, scope.container); - } - } else { - return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); - } - } else { - var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - var isMethod = isFunction && (this.declAST).isMethod(); - var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); - var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); - var isAlias = this.isType() && (this).aliasLink; - if(this.isMember() || isMethod || isStaticFunction || isAlias) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { - if(scope.container == null && this.container != scope.container) { - return false; - } else { - return this.container == null ? true : aEnclosesB(scope.container, this.container); - } - } else { - return true; - } - } else { - if(this.container) { - return aEnclosesB(this, scope.container); - } else { - return true; - } - } - } - }; - Symbol.prototype.addRef = function (identifier) { - if(!this.refs) { - this.refs = []; - } - this.refs[this.refs.length] = identifier; - }; - Symbol.prototype.toString = function () { - if(this.name) { - return this.name; - } else { - return "_anonymous"; - } - }; - Symbol.prototype.print = function (outfile) { - outfile.Write(this.toString()); - }; - Symbol.prototype.specializeType = function (pattern, replacement, checker) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.setType = function (type) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.kind = function () { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { - if(this.declAST != null) { - if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.declAST; - } else { - if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.container.declAST; - } - } - } - return null; - }; - Symbol.prototype.getVarDeclFromSymbol = function () { - if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { - return this.declAST; - } - return null; - }; - Symbol.prototype.getDocComments = function () { - if(this.declAST != null) { - return this.declAST.getDocComments(); - } - return []; - }; - Symbol.prototype.isStatic = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); - }; - return Symbol; - })(); - TypeScript.Symbol = Symbol; - var ValueLocation = (function () { - function ValueLocation() { } - return ValueLocation; - })(); - TypeScript.ValueLocation = ValueLocation; - var InferenceSymbol = (function (_super) { - __extends(InferenceSymbol, _super); - function InferenceSymbol(name, location, length, unitIndex) { - _super.call(this, name, location, length, unitIndex); - this.typeCheckStatus = TypeCheckStatus.NotStarted; - } - InferenceSymbol.prototype.isInferenceSymbol = function () { - return true; - }; - InferenceSymbol.prototype.transferVarFlags = function (varFlags) { - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { - this.flags |= TypeScript.SymbolFlags.Ambient; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { - this.flags |= TypeScript.SymbolFlags.Constant; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { - this.flags |= TypeScript.SymbolFlags.Static; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { - this.flags |= TypeScript.SymbolFlags.Property; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { - this.flags |= TypeScript.SymbolFlags.Private; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { - this.flags |= TypeScript.SymbolFlags.Public; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { - this.flags |= TypeScript.SymbolFlags.Readonly; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { - this.flags |= TypeScript.SymbolFlags.Exported; - } - }; - return InferenceSymbol; - })(Symbol); - TypeScript.InferenceSymbol = InferenceSymbol; - var TypeSymbol = (function (_super) { - __extends(TypeSymbol, _super); - function TypeSymbol(locName, location, length, unitIndex, type) { - _super.call(this, locName, location, length, unitIndex); - this.type = type; - this.expansions = []; - this.expansionsDeclAST = []; - this.isDynamic = false; - this.isMethod = false; - this.aliasLink = null; - this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; - this.prettyName = this.name; - } - TypeSymbol.prototype.addLocation = function (loc) { - if(this.additionalLocations == null) { - this.additionalLocations = []; - } - this.additionalLocations[this.additionalLocations.length] = loc; - }; - TypeSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Type; - }; - TypeSymbol.prototype.isType = function () { - return true; - }; - TypeSymbol.prototype.getType = function () { - return this.type; - }; - TypeSymbol.prototype.getTypeNameEx = function (scope) { - return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); - }; - TypeSymbol.prototype.instanceScope = function () { - if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { - return this.type.instanceType.constructorScope; - } else { - return this.type.containedScope; - } - }; - TypeSymbol.prototype.toString = function () { - var result = this.type.getTypeName(); - if(this.name) { - result = this.name + ":" + result; - } - return result; - }; - TypeSymbol.prototype.isClass = function () { - return this.instanceType != null; - }; - TypeSymbol.prototype.isFunction = function () { - return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - }; - TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { - if(this.type == pattern) { - return replacement.symbol; - } else { - var replType = this.type.specializeType(pattern, replacement, checker, false); - if(replType != this.type) { - var result = new TypeSymbol(this.name, -1, 0, -1, replType); - return result; - } else { - return this; - } - } - }; - TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { - if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { - var symbolPath = scopeSymbol.pathToRoot(); - var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); - if(prettyName != null) { - return prettyName.name; - } - } - return this.prettyName; - }; - TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { - var scopeSymbolPathLength = scopeSymbolPath.length; - var externalSymbol = null; - if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { - if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - if(externalSymbol == null) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - } - return externalSymbol; - }; - TypeSymbol.prototype.getDocComments = function () { - var comments = []; - if(this.declAST != null) { - comments = comments.concat(this.declAST.getDocComments()); - } - for(var i = 0; i < this.expansionsDeclAST.length; i++) { - comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); - } - return comments; - }; - return TypeSymbol; - })(InferenceSymbol); - TypeScript.TypeSymbol = TypeSymbol; - var WithSymbol = (function (_super) { - __extends(WithSymbol, _super); - function WithSymbol(location, unitIndex, withType) { - _super.call(this, "with", location, 4, unitIndex, withType); - } - WithSymbol.prototype.isWith = function () { - return true; - }; - return WithSymbol; - })(TypeSymbol); - TypeScript.WithSymbol = WithSymbol; - var FieldSymbol = (function (_super) { - __extends(FieldSymbol, _super); - function FieldSymbol(name, location, unitIndex, canWrite, field) { - _super.call(this, name, location, name.length, unitIndex); - this.canWrite = canWrite; - this.field = field; - this.getter = null; - this.setter = null; - this.hasBeenEmitted = false; - this.name = name; - this.location = location; - } - FieldSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Field; - }; - FieldSymbol.prototype.writeable = function () { - return this.isAccessor() ? this.setter != null : this.canWrite; - }; - FieldSymbol.prototype.getType = function () { - return this.field.typeLink.type; - }; - FieldSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.field.typeLink.type.getScopedTypeNameEx(scope), this.name + this.getOptionalNameString() + ": ", ""); - }; - FieldSymbol.prototype.isMember = function () { - return true; - }; - FieldSymbol.prototype.setType = function (type) { - this.field.typeLink.type = type; - }; - FieldSymbol.prototype.isAccessor = function () { - return this.getter != null || this.setter != null; - }; - FieldSymbol.prototype.isVariable = function () { - return true; - }; - FieldSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); - if(rType != this.field.typeLink.type) { - var fieldDef = new ValueLocation(); - var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); - result.flags = this.flags; - fieldDef.symbol = result; - fieldDef.typeLink = new TypeScript.TypeLink(); - result.setType(rType); - result.typeCheckStatus = TypeCheckStatus.Finished; - return result; - } else { - return this; - } - }; - FieldSymbol.prototype.getDocComments = function () { - if(this.getter != null || this.setter != null) { - var comments = []; - if(this.getter != null) { - comments = comments.concat(this.getter.getDocComments()); - } - if(this.setter != null) { - comments = comments.concat(this.setter.getDocComments()); - } - return comments; - } else { - if(this.declAST != null) { - return this.declAST.getDocComments(); - } - } - return []; - }; - return FieldSymbol; - })(InferenceSymbol); - TypeScript.FieldSymbol = FieldSymbol; - var ParameterSymbol = (function (_super) { - __extends(ParameterSymbol, _super); - function ParameterSymbol(name, location, unitIndex, parameter) { - _super.call(this, name, location, name.length, unitIndex); - this.parameter = parameter; - this.paramDocComment = null; - this.funcDecl = null; - this.argsOffset = (-1); - this.name = name; - this.location = location; - } - ParameterSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Parameter; - }; - ParameterSymbol.prototype.writeable = function () { - return true; - }; - ParameterSymbol.prototype.getType = function () { - return this.parameter.typeLink.type; - }; - ParameterSymbol.prototype.setType = function (type) { - this.parameter.typeLink.type = type; - }; - ParameterSymbol.prototype.isVariable = function () { - return true; - }; - ParameterSymbol.prototype.isOptional = function () { - if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { - return (this.parameter.symbol.declAST).isOptional; - } else { - return false; - } - }; - ParameterSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); - }; - ParameterSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); - if(this.parameter.typeLink.type != rType) { - var paramDef = new ValueLocation(); - var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); - paramDef.symbol = result; - result.setType(rType); - return result; - } else { - return this; - } - }; - ParameterSymbol.prototype.getParameterDocComments = function () { - if(!this.paramDocComment) { - var parameterComments = []; - if(this.funcDecl) { - var fncDocComments = this.funcDecl.getDocComments(); - var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); - if(paramComment != "") { - parameterComments.push(paramComment); - } - } - var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); - if(docComments != "") { - parameterComments.push(docComments); - } - this.paramDocComment = parameterComments.join("\n"); - } - return this.paramDocComment; - }; - return ParameterSymbol; - })(InferenceSymbol); - TypeScript.ParameterSymbol = ParameterSymbol; - var VariableSymbol = (function (_super) { - __extends(VariableSymbol, _super); - function VariableSymbol(name, location, unitIndex, variable) { - _super.call(this, name, location, name.length, unitIndex); - this.variable = variable; - } - VariableSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Variable; - }; - VariableSymbol.prototype.writeable = function () { - return true; - }; - VariableSymbol.prototype.getType = function () { - return this.variable.typeLink.type; - }; - VariableSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); - }; - VariableSymbol.prototype.setType = function (type) { - this.variable.typeLink.type = type; - }; - VariableSymbol.prototype.isVariable = function () { - return true; - }; - return VariableSymbol; - })(InferenceSymbol); - TypeScript.VariableSymbol = VariableSymbol; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopedMembers = (function () { - function ScopedMembers(dualMembers) { - this.dualMembers = dualMembers; - this.allMembers = this.dualMembers; - this.publicMembers = this.dualMembers.primaryTable; - this.privateMembers = this.dualMembers.secondaryTable; - } - ScopedMembers.prototype.addPublicMember = function (key, data) { - return this.dualMembers.primaryTable.add(key, data); - }; - ScopedMembers.prototype.addPrivateMember = function (key, data) { - return this.dualMembers.secondaryTable.add(key, data); - }; - return ScopedMembers; - })(); - TypeScript.ScopedMembers = ScopedMembers; - (function (SymbolKind) { - SymbolKind._map = []; - SymbolKind._map[0] = "None"; - SymbolKind.None = 0; - SymbolKind._map[1] = "Type"; - SymbolKind.Type = 1; - SymbolKind._map[2] = "Field"; - SymbolKind.Field = 2; - SymbolKind._map[3] = "Parameter"; - SymbolKind.Parameter = 3; - SymbolKind._map[4] = "Variable"; - SymbolKind.Variable = 4; - })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); - var SymbolKind = TypeScript.SymbolKind; - var SymbolScope = (function () { - function SymbolScope(container) { - this.container = container; - } - SymbolScope.prototype.printLabel = function () { - return "base"; - }; - SymbolScope.prototype.getAllSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllTypeSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllValueSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.find = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.print = function (outfile) { - if(this.container) { - outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); - } else { - outfile.WriteLine(this.printLabel() + " scope..."); - } - }; - SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { - throw new Error("please implement in derived class"); - }; - SymbolScope.prototype.getTable = function () { - throw new Error("please implement in derived class"); - }; - return SymbolScope; - })(); - TypeScript.SymbolScope = SymbolScope; - function symbolCanBeUsed(sym, publicOnly) { - return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; - } - var SymbolAggregateScope = (function (_super) { - __extends(SymbolAggregateScope, _super); - function SymbolAggregateScope(container) { - _super.call(this, container); - this.valueCache = null; - this.valueImplCache = null; - this.valueAmbientCache = null; - this.typeCache = null; - this.typeImplCache = null; - this.typeAmbientCache = null; - this.parents = null; - this.container = container; - } - SymbolAggregateScope.prototype.printLabel = function () { - return "agg"; - }; - SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var sym = this.parents[i].search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - } - return filter.result; - }; - SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - this.parents[i].print(outfile); - } - } - }; - SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var implCache = this.valueImplCache; - if(typespace) { - implCache = this.typeImplCache; - } - if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findImplementation(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(implCache) { - if(typespace) { - this.typeImplCache = new TypeScript.StringHashTable(); - implCache = this.typeImplCache; - } else { - this.valueImplCache = new TypeScript.StringHashTable(); - implCache = this.valueImplCache; - } - } - implCache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueCache; - if(typespace) { - cache = this.typeCache; - } - if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].find(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeCache = new TypeScript.StringHashTable(); - cache = this.typeCache; - } else { - this.valueCache = new TypeScript.StringHashTable(); - cache = this.valueCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueAmbientCache; - if(typespace) { - cache = this.typeAmbientCache; - } - if(cache && ((sym = cache.lookup(name)) != null)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findAmbient(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeAmbientCache = new TypeScript.StringHashTable(); - cache = this.typeAmbientCache; - } else { - this.valueAmbientCache = new TypeScript.StringHashTable(); - cache = this.valueAmbientCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.addParentScope = function (parent) { - if(this.parents == null) { - this.parents = new Array(); - } - this.parents[this.parents.length] = parent; - }; - return SymbolAggregateScope; - })(SymbolScope); - TypeScript.SymbolAggregateScope = SymbolAggregateScope; - var SymbolTableScope = (function (_super) { - __extends(SymbolTableScope, _super); - function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.container = container; - } - SymbolTableScope.prototype.printLabel = function () { - return "table"; - }; - SymbolTableScope.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - filter.update(sym); - return filter.result; - }; - SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { - var table = null; - var ambientTable = null; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } else { - table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - if(table) { - var s = table.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - }; - SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - if(sym) { - if(sym.kind() == SymbolKind.Type) { - var typeSym = sym; - if(!typeSym.type.hasImplementation()) { - sym = null; - } - } else { - if(sym.container) { - if(sym.container.kind() == SymbolKind.Type) { - var ctypeSym = sym.container; - if(!ctypeSym.type.hasImplementation()) { - sym = null; - } - } - } - } - } - return sym; - }; - SymbolTableScope.prototype.getTable = function () { - return this.valueMembers.publicMembers; - }; - return SymbolTableScope; - })(SymbolScope); - TypeScript.SymbolTableScope = SymbolTableScope; - var SymbolScopeBuilder = (function (_super) { - __extends(SymbolScopeBuilder, _super); - function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.parent = parent; - this.container = container; - } - SymbolScopeBuilder.prototype.printLabel = function () { - return "builder"; - }; - SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(this.parent) { - sym = this.parent.search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - return filter.result; - }; - SymbolScopeBuilder.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.parent) { - this.parent.print(outfile); - } - }; - SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(table && ((sym = table.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.find(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.findAmbient(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - return null; - }; - SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { - var table = null; - if(ambient) { - if(typespace) { - table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; - } else { - table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; - } - } else { - if(typespace) { - table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; - } else { - table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; - } - } - if(table) { - if(!table.add(symbol.name, symbol)) { - errorReporter.duplicateIdentifier(ast, symbol.name); - } - } else { - TypeScript.CompilerDiagnostics.Alert("YYYYY"); - } - symbol.container = container; - }; - SymbolScopeBuilder.prototype.getTable = function () { - return this.valueMembers.allMembers; - }; - return SymbolScopeBuilder; - })(SymbolScope); - TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; - var FilteredSymbolScope = (function (_super) { - __extends(FilteredSymbolScope, _super); - function FilteredSymbolScope(scope, container, filter) { - _super.call(this, container); - this.scope = scope; - this.filter = filter; - } - FilteredSymbolScope.prototype.print = function (outfile) { - this.scope.print(outfile); - }; - FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { - this.filter.reset(); - return this.scope.search(this.filter, name, publicOnly, typespace); - }; - FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return this.scope.findLocal(name, publicOnly, typespace); - }; - return FilteredSymbolScope; - })(SymbolScope); - TypeScript.FilteredSymbolScope = FilteredSymbolScope; - var FilteredSymbolScopeBuilder = (function (_super) { - __extends(FilteredSymbolScopeBuilder, _super); - function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { - _super.call(this, valueMembers, null, null, null, parent, container); - this.filter = filter; - } - FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return sym; - }; - FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - throw new Error("please implement"); - }; - FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return _super.prototype.find.call(this, name, publicOnly, typespace); - }; - return FilteredSymbolScopeBuilder; - })(SymbolScopeBuilder); - TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TokenID) { - TokenID._map = []; - TokenID._map[0] = "Any"; - TokenID.Any = 0; - TokenID._map[1] = "Bool"; - TokenID.Bool = 1; - TokenID._map[2] = "Break"; - TokenID.Break = 2; - TokenID._map[3] = "Case"; - TokenID.Case = 3; - TokenID._map[4] = "Catch"; - TokenID.Catch = 4; - TokenID._map[5] = "Class"; - TokenID.Class = 5; - TokenID._map[6] = "Const"; - TokenID.Const = 6; - TokenID._map[7] = "Continue"; - TokenID.Continue = 7; - TokenID._map[8] = "Debugger"; - TokenID.Debugger = 8; - TokenID._map[9] = "Default"; - TokenID.Default = 9; - TokenID._map[10] = "Delete"; - TokenID.Delete = 10; - TokenID._map[11] = "Do"; - TokenID.Do = 11; - TokenID._map[12] = "Else"; - TokenID.Else = 12; - TokenID._map[13] = "Enum"; - TokenID.Enum = 13; - TokenID._map[14] = "Export"; - TokenID.Export = 14; - TokenID._map[15] = "Extends"; - TokenID.Extends = 15; - TokenID._map[16] = "Declare"; - TokenID.Declare = 16; - TokenID._map[17] = "False"; - TokenID.False = 17; - TokenID._map[18] = "Finally"; - TokenID.Finally = 18; - TokenID._map[19] = "For"; - TokenID.For = 19; - TokenID._map[20] = "Function"; - TokenID.Function = 20; - TokenID._map[21] = "Constructor"; - TokenID.Constructor = 21; - TokenID._map[22] = "Get"; - TokenID.Get = 22; - TokenID._map[23] = "If"; - TokenID.If = 23; - TokenID._map[24] = "Implements"; - TokenID.Implements = 24; - TokenID._map[25] = "Import"; - TokenID.Import = 25; - TokenID._map[26] = "In"; - TokenID.In = 26; - TokenID._map[27] = "InstanceOf"; - TokenID.InstanceOf = 27; - TokenID._map[28] = "Interface"; - TokenID.Interface = 28; - TokenID._map[29] = "Let"; - TokenID.Let = 29; - TokenID._map[30] = "Module"; - TokenID.Module = 30; - TokenID._map[31] = "New"; - TokenID.New = 31; - TokenID._map[32] = "Number"; - TokenID.Number = 32; - TokenID._map[33] = "Null"; - TokenID.Null = 33; - TokenID._map[34] = "Package"; - TokenID.Package = 34; - TokenID._map[35] = "Private"; - TokenID.Private = 35; - TokenID._map[36] = "Protected"; - TokenID.Protected = 36; - TokenID._map[37] = "Public"; - TokenID.Public = 37; - TokenID._map[38] = "Return"; - TokenID.Return = 38; - TokenID._map[39] = "Set"; - TokenID.Set = 39; - TokenID._map[40] = "Static"; - TokenID.Static = 40; - TokenID._map[41] = "String"; - TokenID.String = 41; - TokenID._map[42] = "Super"; - TokenID.Super = 42; - TokenID._map[43] = "Switch"; - TokenID.Switch = 43; - TokenID._map[44] = "This"; - TokenID.This = 44; - TokenID._map[45] = "Throw"; - TokenID.Throw = 45; - TokenID._map[46] = "True"; - TokenID.True = 46; - TokenID._map[47] = "Try"; - TokenID.Try = 47; - TokenID._map[48] = "TypeOf"; - TokenID.TypeOf = 48; - TokenID._map[49] = "Var"; - TokenID.Var = 49; - TokenID._map[50] = "Void"; - TokenID.Void = 50; - TokenID._map[51] = "With"; - TokenID.With = 51; - TokenID._map[52] = "While"; - TokenID.While = 52; - TokenID._map[53] = "Yield"; - TokenID.Yield = 53; - TokenID._map[54] = "Semicolon"; - TokenID.Semicolon = 54; - TokenID._map[55] = "OpenParen"; - TokenID.OpenParen = 55; - TokenID._map[56] = "CloseParen"; - TokenID.CloseParen = 56; - TokenID._map[57] = "OpenBracket"; - TokenID.OpenBracket = 57; - TokenID._map[58] = "CloseBracket"; - TokenID.CloseBracket = 58; - TokenID._map[59] = "OpenBrace"; - TokenID.OpenBrace = 59; - TokenID._map[60] = "CloseBrace"; - TokenID.CloseBrace = 60; - TokenID._map[61] = "Comma"; - TokenID.Comma = 61; - TokenID._map[62] = "Equals"; - TokenID.Equals = 62; - TokenID._map[63] = "PlusEquals"; - TokenID.PlusEquals = 63; - TokenID._map[64] = "MinusEquals"; - TokenID.MinusEquals = 64; - TokenID._map[65] = "AsteriskEquals"; - TokenID.AsteriskEquals = 65; - TokenID._map[66] = "SlashEquals"; - TokenID.SlashEquals = 66; - TokenID._map[67] = "PercentEquals"; - TokenID.PercentEquals = 67; - TokenID._map[68] = "AmpersandEquals"; - TokenID.AmpersandEquals = 68; - TokenID._map[69] = "CaretEquals"; - TokenID.CaretEquals = 69; - TokenID._map[70] = "BarEquals"; - TokenID.BarEquals = 70; - TokenID._map[71] = "LessThanLessThanEquals"; - TokenID.LessThanLessThanEquals = 71; - TokenID._map[72] = "GreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanEquals = 72; - TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; - TokenID._map[74] = "Question"; - TokenID.Question = 74; - TokenID._map[75] = "Colon"; - TokenID.Colon = 75; - TokenID._map[76] = "BarBar"; - TokenID.BarBar = 76; - TokenID._map[77] = "AmpersandAmpersand"; - TokenID.AmpersandAmpersand = 77; - TokenID._map[78] = "Bar"; - TokenID.Bar = 78; - TokenID._map[79] = "Caret"; - TokenID.Caret = 79; - TokenID._map[80] = "And"; - TokenID.And = 80; - TokenID._map[81] = "EqualsEquals"; - TokenID.EqualsEquals = 81; - TokenID._map[82] = "ExclamationEquals"; - TokenID.ExclamationEquals = 82; - TokenID._map[83] = "EqualsEqualsEquals"; - TokenID.EqualsEqualsEquals = 83; - TokenID._map[84] = "ExclamationEqualsEquals"; - TokenID.ExclamationEqualsEquals = 84; - TokenID._map[85] = "LessThan"; - TokenID.LessThan = 85; - TokenID._map[86] = "LessThanEquals"; - TokenID.LessThanEquals = 86; - TokenID._map[87] = "GreaterThan"; - TokenID.GreaterThan = 87; - TokenID._map[88] = "GreaterThanEquals"; - TokenID.GreaterThanEquals = 88; - TokenID._map[89] = "LessThanLessThan"; - TokenID.LessThanLessThan = 89; - TokenID._map[90] = "GreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThan = 90; - TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThanGreaterThan = 91; - TokenID._map[92] = "Plus"; - TokenID.Plus = 92; - TokenID._map[93] = "Minus"; - TokenID.Minus = 93; - TokenID._map[94] = "Asterisk"; - TokenID.Asterisk = 94; - TokenID._map[95] = "Slash"; - TokenID.Slash = 95; - TokenID._map[96] = "Percent"; - TokenID.Percent = 96; - TokenID._map[97] = "Tilde"; - TokenID.Tilde = 97; - TokenID._map[98] = "Exclamation"; - TokenID.Exclamation = 98; - TokenID._map[99] = "PlusPlus"; - TokenID.PlusPlus = 99; - TokenID._map[100] = "MinusMinus"; - TokenID.MinusMinus = 100; - TokenID._map[101] = "Dot"; - TokenID.Dot = 101; - TokenID._map[102] = "DotDotDot"; - TokenID.DotDotDot = 102; - TokenID._map[103] = "Error"; - TokenID.Error = 103; - TokenID._map[104] = "EndOfFile"; - TokenID.EndOfFile = 104; - TokenID._map[105] = "EqualsGreaterThan"; - TokenID.EqualsGreaterThan = 105; - TokenID._map[106] = "Identifier"; - TokenID.Identifier = 106; - TokenID._map[107] = "StringLiteral"; - TokenID.StringLiteral = 107; - TokenID._map[108] = "RegularExpressionLiteral"; - TokenID.RegularExpressionLiteral = 108; - TokenID._map[109] = "NumberLiteral"; - TokenID.NumberLiteral = 109; - TokenID._map[110] = "Whitespace"; - TokenID.Whitespace = 110; - TokenID._map[111] = "Comment"; - TokenID.Comment = 111; - TokenID._map[112] = "Lim"; - TokenID.Lim = 112; - TokenID.LimFixed = TokenID.EqualsGreaterThan; - TokenID.LimKeyword = TokenID.Yield; - })(TypeScript.TokenID || (TypeScript.TokenID = {})); - var TokenID = TypeScript.TokenID; - TypeScript.tokenTable = new Array(); - TypeScript.nodeTypeTable = new Array(); - TypeScript.nodeTypeToTokTable = new Array(); - TypeScript.noRegexTable = new Array(); - TypeScript.noRegexTable[TokenID.Identifier] = true; - TypeScript.noRegexTable[TokenID.StringLiteral] = true; - TypeScript.noRegexTable[TokenID.NumberLiteral] = true; - TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; - TypeScript.noRegexTable[TokenID.This] = true; - TypeScript.noRegexTable[TokenID.PlusPlus] = true; - TypeScript.noRegexTable[TokenID.MinusMinus] = true; - TypeScript.noRegexTable[TokenID.CloseParen] = true; - TypeScript.noRegexTable[TokenID.CloseBracket] = true; - TypeScript.noRegexTable[TokenID.CloseBrace] = true; - TypeScript.noRegexTable[TokenID.True] = true; - TypeScript.noRegexTable[TokenID.False] = true; - (function (OperatorPrecedence) { - OperatorPrecedence._map = []; - OperatorPrecedence._map[0] = "None"; - OperatorPrecedence.None = 0; - OperatorPrecedence._map[1] = "Comma"; - OperatorPrecedence.Comma = 1; - OperatorPrecedence._map[2] = "Assignment"; - OperatorPrecedence.Assignment = 2; - OperatorPrecedence._map[3] = "Conditional"; - OperatorPrecedence.Conditional = 3; - OperatorPrecedence._map[4] = "LogicalOr"; - OperatorPrecedence.LogicalOr = 4; - OperatorPrecedence._map[5] = "LogicalAnd"; - OperatorPrecedence.LogicalAnd = 5; - OperatorPrecedence._map[6] = "BitwiseOr"; - OperatorPrecedence.BitwiseOr = 6; - OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; - OperatorPrecedence.BitwiseExclusiveOr = 7; - OperatorPrecedence._map[8] = "BitwiseAnd"; - OperatorPrecedence.BitwiseAnd = 8; - OperatorPrecedence._map[9] = "Equality"; - OperatorPrecedence.Equality = 9; - OperatorPrecedence._map[10] = "Relational"; - OperatorPrecedence.Relational = 10; - OperatorPrecedence._map[11] = "Shift"; - OperatorPrecedence.Shift = 11; - OperatorPrecedence._map[12] = "Additive"; - OperatorPrecedence.Additive = 12; - OperatorPrecedence._map[13] = "Multiplicative"; - OperatorPrecedence.Multiplicative = 13; - OperatorPrecedence._map[14] = "Unary"; - OperatorPrecedence.Unary = 14; - OperatorPrecedence._map[15] = "Lim"; - OperatorPrecedence.Lim = 15; - })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); - var OperatorPrecedence = TypeScript.OperatorPrecedence; - (function (Reservation) { - Reservation._map = []; - Reservation.None = 0; - Reservation.Javascript = 1; - Reservation.JavascriptFuture = 2; - Reservation.TypeScript = 4; - Reservation.JavascriptFutureStrict = 8; - Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; - Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; - Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; - })(TypeScript.Reservation || (TypeScript.Reservation = {})); - var Reservation = TypeScript.Reservation; - var TokenInfo = (function () { - function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - this.tokenId = tokenId; - this.reservation = reservation; - this.binopPrecedence = binopPrecedence; - this.binopNodeType = binopNodeType; - this.unopPrecedence = unopPrecedence; - this.unopNodeType = unopNodeType; - this.text = text; - this.ers = ers; - } - return TokenInfo; - })(); - TypeScript.TokenInfo = TokenInfo; - function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - if(tokenId !== undefined) { - TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); - if(binopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[binopNodeType] = text; - TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; - } - if(unopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[unopNodeType] = text; - } - } - } - setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); - setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); - setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); - setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); - setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); - setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); - setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); - setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); - setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); - setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); - setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); - setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); - setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); - setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); - setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); - setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); - setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); - function lookupToken(tokenId) { - return TypeScript.tokenTable[tokenId]; - } - TypeScript.lookupToken = lookupToken; - (function (TokenClass) { - TokenClass._map = []; - TokenClass._map[0] = "Punctuation"; - TokenClass.Punctuation = 0; - TokenClass._map[1] = "Keyword"; - TokenClass.Keyword = 1; - TokenClass._map[2] = "Operator"; - TokenClass.Operator = 2; - TokenClass._map[3] = "Comment"; - TokenClass.Comment = 3; - TokenClass._map[4] = "Whitespace"; - TokenClass.Whitespace = 4; - TokenClass._map[5] = "Identifier"; - TokenClass.Identifier = 5; - TokenClass._map[6] = "NumberLiteral"; - TokenClass.NumberLiteral = 6; - TokenClass._map[7] = "StringLiteral"; - TokenClass.StringLiteral = 7; - TokenClass._map[8] = "RegExpLiteral"; - TokenClass.RegExpLiteral = 8; - })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); - var TokenClass = TypeScript.TokenClass; - var SavedToken = (function () { - function SavedToken(tok, minChar, limChar) { - this.tok = tok; - this.minChar = minChar; - this.limChar = limChar; - } - return SavedToken; - })(); - TypeScript.SavedToken = SavedToken; - var Token = (function () { - function Token(tokenId) { - this.tokenId = tokenId; - } - Token.prototype.toString = function () { - return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; - }; - Token.prototype.print = function (line, outfile) { - outfile.WriteLine(this.toString() + ",on line" + line); - }; - Token.prototype.getText = function () { - return TypeScript.tokenTable[this.tokenId].text; - }; - Token.prototype.classification = function () { - if(this.tokenId <= TokenID.LimKeyword) { - return TokenClass.Keyword; - } else { - var tokenInfo = lookupToken(this.tokenId); - if(tokenInfo != undefined) { - if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { - return TokenClass.Operator; - } - } - } - return TokenClass.Punctuation; - }; - return Token; - })(); - TypeScript.Token = Token; - var NumberLiteralToken = (function (_super) { - __extends(NumberLiteralToken, _super); - function NumberLiteralToken(value, hasEmptyFraction) { - _super.call(this, TokenID.NumberLiteral); - this.value = value; - this.hasEmptyFraction = hasEmptyFraction; - } - NumberLiteralToken.prototype.getText = function () { - return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); - }; - NumberLiteralToken.prototype.classification = function () { - return TokenClass.NumberLiteral; - }; - return NumberLiteralToken; - })(Token); - TypeScript.NumberLiteralToken = NumberLiteralToken; - var StringLiteralToken = (function (_super) { - __extends(StringLiteralToken, _super); - function StringLiteralToken(value) { - _super.call(this, TokenID.StringLiteral); - this.value = value; - } - StringLiteralToken.prototype.getText = function () { - return this.value; - }; - StringLiteralToken.prototype.classification = function () { - return TokenClass.StringLiteral; - }; - return StringLiteralToken; - })(Token); - TypeScript.StringLiteralToken = StringLiteralToken; - var IdentifierToken = (function (_super) { - __extends(IdentifierToken, _super); - function IdentifierToken(value, hasEscapeSequence) { - _super.call(this, TokenID.Identifier); - this.value = value; - this.hasEscapeSequence = hasEscapeSequence; - } - IdentifierToken.prototype.getText = function () { - return this.value; - }; - IdentifierToken.prototype.classification = function () { - return TokenClass.Identifier; - }; - return IdentifierToken; - })(Token); - TypeScript.IdentifierToken = IdentifierToken; - var WhitespaceToken = (function (_super) { - __extends(WhitespaceToken, _super); - function WhitespaceToken(tokenId, value) { - _super.call(this, tokenId); - this.value = value; - } - WhitespaceToken.prototype.getText = function () { - return this.value; - }; - WhitespaceToken.prototype.classification = function () { - return TokenClass.Whitespace; - }; - return WhitespaceToken; - })(Token); - TypeScript.WhitespaceToken = WhitespaceToken; - var CommentToken = (function (_super) { - __extends(CommentToken, _super); - function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { - _super.call(this, tokenID); - this.value = value; - this.isBlock = isBlock; - this.startPos = startPos; - this.line = line; - this.endsLine = endsLine; - } - CommentToken.prototype.getText = function () { - return this.value; - }; - CommentToken.prototype.classification = function () { - return TokenClass.Comment; - }; - return CommentToken; - })(Token); - TypeScript.CommentToken = CommentToken; - var RegularExpressionLiteralToken = (function (_super) { - __extends(RegularExpressionLiteralToken, _super); - function RegularExpressionLiteralToken(regex) { - _super.call(this, TokenID.RegularExpressionLiteral); - this.regex = regex; - } - RegularExpressionLiteralToken.prototype.getText = function () { - return this.regex.toString(); - }; - RegularExpressionLiteralToken.prototype.classification = function () { - return TokenClass.RegExpLiteral; - }; - return RegularExpressionLiteralToken; - })(Token); - TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; - TypeScript.staticTokens = new Array(); - function initializeStaticTokens() { - for(var i = 0; i <= TokenID.LimFixed; i++) { - TypeScript.staticTokens[i] = new Token(i); - } - } - TypeScript.initializeStaticTokens = initializeStaticTokens; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ArrayCache = (function () { - function ArrayCache() { - this.arrayBase = null; - } - ArrayCache.prototype.specialize = function (arrInstType, checker) { - if(this.arrayBase == null) { - this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); - } - return this.arrayBase; - }; - return ArrayCache; - })(); - TypeScript.ArrayCache = ArrayCache; - var TypeComparisonInfo = (function () { - function TypeComparisonInfo() { - this.onlyCaptureFirstError = false; - this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; - this.message = ""; - } - TypeComparisonInfo.prototype.addMessageToFront = function (message) { - if(!this.onlyCaptureFirstError) { - this.message = this.message ? message + ":\n\t" + this.message : message; - } else { - this.setMessage(message); - } - }; - TypeComparisonInfo.prototype.setMessage = function (message) { - this.message = message; - }; - return TypeComparisonInfo; - })(); - TypeScript.TypeComparisonInfo = TypeComparisonInfo; - (function (TypeCheckCollectionMode) { - TypeCheckCollectionMode._map = []; - TypeCheckCollectionMode._map[0] = "Resident"; - TypeCheckCollectionMode.Resident = 0; - TypeCheckCollectionMode._map[1] = "Transient"; - TypeCheckCollectionMode.Transient = 1; - })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); - var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; - var PersistentGlobalTypeState = (function () { - function PersistentGlobalTypeState(errorReporter) { - this.errorReporter = errorReporter; - this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.globals = null; - this.globalTypes = null; - this.ambientGlobals = null; - this.ambientGlobalTypes = null; - this.residentGlobalValues = new TypeScript.StringHashTable(); - this.residentGlobalTypes = new TypeScript.StringHashTable(); - this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); - this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); - this.residentTypeCheck = true; - this.mod = null; - this.gloMod = null; - this.wildElm = null; - this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); - this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); - this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); - this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); - this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); - var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); - this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); - this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); - this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); - this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); - this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); - this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); - this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); - this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); - this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); - this.setCollectionMode(TypeCheckCollectionMode.Resident); - this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); - this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); - this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); - this.mod.members = dualGlobalScopedMembers; - this.mod.ambientMembers = dualGlobalScopedAmbientMembers; - this.mod.containedScope = this.globalScope; - this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); - this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); - this.defineGlobalValue("undefined", this.undefinedType); - } - PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { - var primitive = new TypeScript.Type(); - primitive.primitiveTypeClass = flags; - var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); - symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - primitive.symbol = symbol; - this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); - return primitive; - }; - PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { - this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; - }; - PersistentGlobalTypeState.prototype.refreshPersistentState = function () { - this.globals = new TypeScript.StringHashTable(); - this.globalTypes = new TypeScript.StringHashTable(); - this.ambientGlobals = new TypeScript.StringHashTable(); - this.ambientGlobalTypes = new TypeScript.StringHashTable(); - this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); - this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); - this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); - this.globalTypes.add("number", this.doubleType.symbol); - this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); - this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); - this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); - this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); - this.dualGlobalValues.secondaryTable = this.globals; - this.dualGlobalTypes.secondaryTable = this.globalTypes; - this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; - this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; - }; - PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { - var valueLocation = new TypeScript.ValueLocation(); - valueLocation.typeLink = new TypeScript.TypeLink(); - var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); - sym.setType(type); - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - sym.container = this.gloMod; - this.importedGlobalsTable.addPublicMember(name, sym); - }; - return PersistentGlobalTypeState; - })(); - TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; - var ContextualTypeContext = (function () { - function ContextualTypeContext(contextualType, provisional, contextID) { - this.contextualType = contextualType; - this.provisional = provisional; - this.contextID = contextID; - this.targetSig = null; - this.targetThis = null; - this.targetAccessorType = null; - } - return ContextualTypeContext; - })(); - TypeScript.ContextualTypeContext = ContextualTypeContext; - var ContextualTypingContextStack = (function () { - function ContextualTypingContextStack(checker) { - this.checker = checker; - this.contextStack = []; - this.hadProvisionalErrors = false; - } - ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; - ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { - this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); - this.checker.errorReporter.pushToErrorSink = provisional; - }; - ContextualTypingContextStack.prototype.popContextualType = function () { - var tc = this.contextStack.pop(); - this.checker.errorReporter.pushToErrorSink = this.isProvisional(); - this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); - this.checker.errorReporter.freeCapturedErrors(); - return tc; - }; - ContextualTypingContextStack.prototype.getContextualType = function () { - return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); - }; - ContextualTypingContextStack.prototype.getContextID = function () { - return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); - }; - ContextualTypingContextStack.prototype.isProvisional = function () { - return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); - }; - return ContextualTypingContextStack; - })(); - TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; - var TypeChecker = (function () { - function TypeChecker(persistentState) { - this.persistentState = persistentState; - this.errorReporter = null; - this.checkControlFlow = false; - this.printControlFlowGraph = false; - this.checkControlFlowUseDef = false; - this.styleSettings = null; - this.units = null; - this.anon = "_anonymous"; - this.locationInfo = null; - this.typeFlow = null; - this.currentCompareA = null; - this.currentCompareB = null; - this.currentModDecl = null; - this.inBind = false; - this.inWith = false; - this.errorsOnWith = true; - this.currentContextualTypeContext = null; - this.resolvingBases = false; - this.canCallDefinitionSignature = false; - this.assignableCache = { - }; - this.subtypeCache = { - }; - this.identicalCache = { - }; - this.provisionalStartedTypecheckObjects = []; - this.mustCaptureGlobalThis = false; - this.voidType = this.persistentState.voidType; - this.booleanType = this.persistentState.booleanType; - this.numberType = this.persistentState.doubleType; - this.stringType = this.persistentState.stringType; - this.anyType = this.persistentState.anyType; - this.nullType = this.persistentState.nullType; - this.undefinedType = this.persistentState.undefinedType; - this.globals = this.persistentState.dualGlobalValues; - this.globalTypes = this.persistentState.dualGlobalTypes; - this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; - this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; - this.gloModType = this.persistentState.mod; - this.gloMod = this.persistentState.gloMod; - this.wildElm = this.persistentState.wildElm; - this.globalScope = this.persistentState.globalScope; - this.typingContextStack = new ContextualTypingContextStack(this); - } - TypeChecker.prototype.setStyleOptions = function (style) { - this.styleSettings = style; - }; - TypeChecker.prototype.setContextualType = function (type, provisional) { - this.typingContextStack.pushContextualType(type, provisional); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.unsetContextualType = function () { - var lastTC = this.typingContextStack.popContextualType(); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - return lastTC; - }; - TypeChecker.prototype.hadProvisionalErrors = function () { - return this.typingContextStack.hadProvisionalErrors; - }; - TypeChecker.prototype.resetProvisionalErrors = function () { - if(!this.typingContextStack.getContextualType()) { - this.typingContextStack.hadProvisionalErrors = false; - } - }; - TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { - if(condition) { - this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); - } - this.typeFlow.typeCheck(ast); - if(condition) { - this.unsetContextualType(); - } - }; - TypeChecker.prototype.resetTargetType = function () { - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.killCurrentContextualType = function () { - this.currentContextualTypeContext = null; - this.errorReporter.pushToErrorSink = false; - }; - TypeChecker.prototype.hasTargetType = function () { - return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; - }; - TypeChecker.prototype.getTargetTypeContext = function () { - return this.currentContextualTypeContext; - }; - TypeChecker.prototype.inProvisionalTypecheckMode = function () { - return this.typingContextStack.isProvisional(); - }; - TypeChecker.prototype.getTypeCheckFinishedStatus = function () { - if(this.inProvisionalTypecheckMode()) { - return this.typingContextStack.getContextID(); - } - return TypeScript.TypeCheckStatus.Finished; - }; - TypeChecker.prototype.typeStatusIsFinished = function (status) { - return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); - }; - TypeChecker.prototype.addStartedPTO = function (pto) { - if(this.inProvisionalTypecheckMode()) { - this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; - } - }; - TypeChecker.prototype.cleanStartedPTO = function () { - for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { - if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { - this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - } - } - this.provisionalStartedTypecheckObjects = []; - }; - TypeChecker.prototype.collectTypes = function (ast) { - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - this.locationInfo = script.locationInfo; - } - var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); - var context = new TypeScript.TypeCollectionContext(globalChain, this); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); - }; - TypeChecker.prototype.makeArrayType = function (type) { - if(type.arrayCache == null) { - type.arrayCache = new ArrayCache(); - type.arrayCache.arrayType = new TypeScript.Type(); - type.arrayCache.arrayType.elementType = type; - type.arrayCache.arrayType.symbol = type.symbol; - } - return type.arrayCache.arrayType; - }; - TypeChecker.prototype.getParameterList = function (funcDecl, container) { - var args = funcDecl.arguments; - var parameterTable = null; - var parameterBuilder = null; - var len = args.members.length; - var nonOptionalParams = 0; - var result = []; - if(len > 0) { - parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); - for(var i = 0; i < len; i++) { - var parameter = args.members[i]; - var paramDef = new TypeScript.ValueLocation(); - var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); - parameterSymbol.declAST = parameter; - parameterSymbol.funcDecl = funcDecl; - parameter.id.sym = parameterSymbol; - parameter.sym = parameterSymbol; - paramDef.symbol = parameterSymbol; - paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); - parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); - result[result.length] = parameterSymbol; - if(!parameter.isOptionalArg()) { - nonOptionalParams++; - } - } - } - return { - parameters: result, - nonOptionalParameterCount: nonOptionalParams - }; - }; - TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isDefinition = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition); - var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var isGlobal = container == this.gloMod; - var signature = new TypeScript.Signature(); - var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; - if(funcDecl.returnTypeAnnotation || isDefinition) { - signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); - } else { - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = this.anyType; - } - signature.hasVariableArgList = funcDecl.variableArgList; - var sigData = this.getParameterList(funcDecl, container); - signature.parameters = sigData.parameters; - signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; - funcDecl.signature = signature; - signature.declAST = funcDecl; - var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); - if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); - } - var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); - if(isConstructor) { - if(groupType.construct == null) { - groupType.construct = new TypeScript.SignatureGroup(); - } - groupType.construct.addSignature(signature); - groupType.construct.hasImplementation = !(funcDecl.isSignature()); - if(groupType.construct.hasImplementation) { - groupType.setHasImplementation(); - } - } else { - if(funcDecl.isIndexerMember()) { - if(groupType.index == null) { - groupType.index = new TypeScript.SignatureGroup(); - groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; - } - groupType.index.addSignature(signature); - groupType.index.hasImplementation = !(funcDecl.isSignature()); - if(groupType.index.hasImplementation) { - groupType.setHasImplementation(); - } - } else { - if(groupType.call == null) { - groupType.call = new TypeScript.SignatureGroup(); - } - groupType.call.addSignature(signature); - groupType.call.hasImplementation = !(funcDecl.isSignature()); - if(groupType.call.hasImplementation) { - groupType.setHasImplementation(); - } - } - } - var instanceType = groupType.instanceType; - var funcName = null; - var usedHint = false; - if(funcDecl.name && !funcDecl.name.isMissing()) { - funcName = funcDecl.name.text; - } else { - if(funcDecl.hint) { - funcName = funcDecl.hint; - usedHint = true; - } - } - if(groupType.symbol == null) { - groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); - if(!useOverloadGroupSym) { - groupType.symbol.declAST = funcDecl; - } - } - if(isStatic) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Static; - } - if(isAmbient) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; - } - if(isPrivate) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Private; - } - groupType.symbol.isMethod = funcDecl.isMethod(); - if(groupType.symbol.isMethod) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Property; - } - funcDecl.type = groupType; - if(!isConstructor) { - if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { - if(addToScope) { - if(funcDecl.isMethod() && isStatic) { - if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { - this.errorReporter.duplicateIdentifier(funcDecl, funcName); - } - groupType.symbol.container = container; - } else { - if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { - scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); - } - } - } else { - if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } - } else { - if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } - } - if(useOverloadGroupSym) { - var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; - var classType = groupType; - if(classType != overloadGroupType) { - if(classType.construct == null) { - if(overloadGroupType && overloadGroupType.construct) { - classType.construct = overloadGroupType.construct; - } else { - classType.construct = new TypeScript.SignatureGroup(); - } - } else { - if(overloadGroupType) { - if(overloadGroupType.construct) { - classType.construct.signatures.concat(overloadGroupType.construct.signatures); - } - } - } - if(overloadGroupType) { - if(classType.call == null) { - classType.call = overloadGroupType.call; - } else { - if(overloadGroupType.call) { - classType.call.signatures.concat(overloadGroupType.call.signatures); - } - } - if(!isStatic) { - if(classType.instanceType == null) { - classType.instanceType = overloadGroupType.instanceType; - } - var instanceType = classType.instanceType; - if(instanceType) { - if(instanceType.call == null) { - instanceType.call = overloadGroupType.call; - } else { - if(overloadGroupType.call) { - instanceType.call.signatures.concat(overloadGroupType.call.signatures); - } - } - } - } - if(classType.index == null) { - classType.index = overloadGroupType.index; - } else { - if(overloadGroupType.index) { - classType.index.signatures.concat(overloadGroupType.index.signatures); - } - } - } - } - } - return signature; - }; - TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { - var accessorSym = null; - var sig = funcDecl.signature; - var nameText = funcDecl.name.text; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - if(fgSym == null) { - var field = new TypeScript.ValueLocation(); - accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); - field.symbol = accessorSym; - accessorSym.declAST = funcDecl; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = sig.declAST.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = sig.declAST.type.symbol; - } - field.typeLink = TypeScript.getTypeLink(null, this, false); - if(addToMembers) { - if(enclosingClass) { - if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { - this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); - } - accessorSym.container = enclosingClass.symbol; - } else { - this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); - } - } else { - scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); - } - if(isClassProperty) { - accessorSym.flags |= TypeScript.SymbolFlags.Property; - } - if(isStatic) { - accessorSym.flags |= TypeScript.SymbolFlags.Static; - } - if(isPrivate) { - accessorSym.flags |= TypeScript.SymbolFlags.Private; - } else { - accessorSym.flags |= TypeScript.SymbolFlags.Public; - } - } else { - accessorSym = (fgSym); - if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = funcDecl.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = funcDecl.type.symbol; - } - } - return accessorSym; - }; - TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { - resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); - var i = 0; - var parent; - if(type.extendsList) { - for(var len = type.extendsList.length; i < len; i++) { - parent = type.extendsList[i]; - if(baseContext.baseId == parent.typeID) { - this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); - parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - break; - } - this.addBases(resultScope, parent, baseContext); - } - } - }; - TypeChecker.prototype.scopeOf = function (type) { - var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); - var baseContext = { - base: type.symbol && type.symbol.name ? type.symbol.name : "{}", - baseId: type.typeID - }; - this.addBases(resultScope, type, baseContext); - return resultScope; - }; - TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { - var symbol = null; - if(containingType.containedScope) { - symbol = containingType.containedScope.find(name, false, true); - } else { - if(containingType.members) { - symbol = containingType.members.allMembers.lookup(name); - if(symbol == null && containingType.ambientMembers) { - symbol = containingType.ambientMembers.allMembers.lookup(name); - } - } - } - if(symbol == null) { - var typeMembers = containingType.getAllEnclosedTypes(); - var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); - if(typeMembers) { - symbol = typeMembers.allMembers.lookup(name); - if(symbol == null && ambientTypeMembers) { - symbol = ambientTypeMembers.allMembers.lookup(name); - } - } - } - if(symbol && symbol.isType()) { - return symbol; - } else { - return null; - } - }; - TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { - var originalIdText = idText; - var symbol = search(idText); - if(symbol == null) { - if(!symbol) { - idText = TypeScript.swapQuotes(originalIdText); - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".str"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; - symbol = search(idText); - } - if(!symbol && !TypeScript.isRelative(originalIdText)) { - idText = originalIdText; - var strippedIdText = TypeScript.stripQuotes(idText); - var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); - while(symbol == null && path != "") { - idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); - symbol = search(idText); - if(symbol == null) { - idText = TypeScript.changePathToSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDTS(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - if(path === '/') { - path = ''; - } else { - path = TypeScript.normalizePath(path + ".."); - path = path && path != '/' ? path + '/' : path; - } - } - } - } - } - return symbol; - }; - TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { - var lhs = dotNode.operand1; - var rhs = dotNode.operand2; - var resultType = this.anyType; - var lhsType = this.anyType; - if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { - if(lhs.nodeType == TypeScript.NodeType.Dot) { - lhsType = this.resolveTypeMember(scope, lhs); - } else { - if(lhs.nodeType == TypeScript.NodeType.Name) { - var identifier = lhs; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else { - if(symbol.isType()) { - var typeSymbol = symbol; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(TypeScript.optimizeModuleCodeGen && symbol) { - var symType = symbol.getType(); - if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; - } - } - } - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - lhsType = symbol.getType(); - identifier.sym = symbol; - } else { - this.errorReporter.simpleError(lhs, "Expected type"); - } - } - } - } - if(!lhsType) { - lhsType = this.anyType; - } - if(lhsType != this.anyType) { - var rhsIdentifier = rhs; - var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); - if(resultSymbol == null) { - resultType = this.anyType; - this.errorReporter.simpleError(dotNode, "Expected type"); - } else { - resultType = resultSymbol.getType(); - if(!resultSymbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); - } - } - rhsIdentifier.sym = resultType.symbol; - } - } - if(resultType.isClass()) { - resultType = resultType.instanceType; - } - return resultType; - }; - TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { - var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; - var signatures; - if(funcDecl.isConstructMember()) { - signatures = functionGroupSymbol.type.construct.signatures; - } else { - if(funcDecl.isIndexerMember()) { - signatures = functionGroupSymbol.type.getInstanceType().index.signatures; - } else { - signatures = functionGroupSymbol.type.call.signatures; - } - } - var signature = signatures[signatures.length - 1]; - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); - } - if(len && funcDecl.variableArgList) { - if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { - this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); - signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); - } - } - this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); - return functionGroupSymbol; - }; - TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = varDecl; - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); - this.resolveTypeLink(scope, field.typeLink, true); - varDecl.sym = fieldSymbol; - varDecl.type = field.typeLink.type; - return fieldSymbol; - }; - TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { - var arrayCount = 0; - if(typeLink.type == null) { - var ast = typeLink.ast; - if(ast) { - while(typeLink.type == null) { - switch(ast.nodeType) { - case TypeScript.NodeType.Name: { - var identifier = ast; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - typeLink.type = this.anyType; - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else { - if(symbol.isType()) { - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - identifier.sym = symbol; - typeLink.type = symbol.getType(); - if(typeLink.type) { - if(typeLink.type.isClass()) { - typeLink.type = typeLink.type.instanceType; - } - } else { - typeLink.type = this.anyType; - } - } else { - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - } - } - break; - - } - case TypeScript.NodeType.Dot: { - typeLink.type = this.resolveTypeMember(scope, ast); - break; - - } - case TypeScript.NodeType.TypeRef: { - var typeRef = ast; - arrayCount = typeRef.arrayCount; - ast = typeRef.term; - if(ast == null) { - typeLink.type = this.anyType; - } - break; - - } - case TypeScript.NodeType.InterfaceDeclaration: { - var interfaceDecl = ast; - var interfaceType = new TypeScript.Type(); - var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); - interfaceType.containedScope.container = interfaceSymbol; - interfaceType.memberScope = interfaceType.containedScope; - var memberList = interfaceDecl.members; - var props = memberList.members; - var propsLen = props.length; - for(var j = 0; j < propsLen; j++) { - var propDecl = props[j]; - var propSym = null; - var addMember = true; - var id = null; - if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = propDecl; - id = funcDecl.name; - propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); - addMember = (propSym == null); - if(funcDecl.isSpecialFn()) { - addMember = false; - propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); - } else { - propSym = this.resolveFuncDecl(funcDecl, scope, propSym); - } - funcDecl.type = (propSym).type; - } else { - id = (propDecl).id; - propSym = this.resolveVarDecl(propDecl, scope); - addMember = !id.isMissing(); - } - if(addMember) { - if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { - propSym.flags |= TypeScript.SymbolFlags.Optional; - } - if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { - this.errorReporter.duplicateIdentifier(ast, propSym.name); - } - } - } - ast.type = interfaceType; - typeLink.type = interfaceType; - break; - - } - case TypeScript.NodeType.FuncDecl: { - var tsym = this.resolveFuncDecl(ast, scope, null); - typeLink.type = tsym.type; - break; - - } - default: { - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - break; - - } - } - } - } - for(var count = arrayCount; count > 0; count--) { - typeLink.type = this.makeArrayType(typeLink.type); - } - if(supplyVar && (typeLink.type == null)) { - typeLink.type = this.anyType; - } - if(typeLink.ast) { - typeLink.ast.type = typeLink.type; - } - } - }; - TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { - this.resolvingBases = true; - this.resolveTypeLink(scope, typeLink, true); - this.resolvingBases = false; - var extendsType = null; - if(typeLink.type.isClass()) { - extendsType = typeLink.type.instanceType; - } else { - extendsType = typeLink.type; - } - return extendsType; - }; - TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { - if(signatures.length == 1) { - return { - sig: signatures[0].signature, - ambiguous: false - }; - } - var best = signatures[0]; - var Q = null; - var AType = null; - var PType = null; - var QType = null; - var ambiguous = false; - for(var qSig = 1; qSig < signatures.length; qSig++) { - Q = signatures[qSig]; - var i = 0; - for(i = 0; args && i < args.members.length; i++) { - AType = args.members[i].type; - PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; - QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; - if(this.typesAreIdentical(PType, QType)) { - continue; - } else { - if(this.typesAreIdentical(AType, PType)) { - break; - } else { - if(this.typesAreIdentical(AType, QType)) { - best = Q; - break; - } else { - if(this.sourceIsSubtypeOfTarget(PType, QType)) { - break; - } else { - if(this.sourceIsSubtypeOfTarget(QType, PType)) { - best = Q; - break; - } else { - if(Q.hadProvisionalErrors) { - break; - } else { - if(best.hadProvisionalErrors) { - best = Q; - break; - } - } - } - } - } - } - } - } - if(!args || i == args.members.length) { - var collection = { - getLength: function () { - return 2; - }, - setTypeAtIndex: function (index, type) { - }, - getTypeAtIndex: function (index) { - return index ? Q.signature.returnType.type : best.signature.returnType.type; - } - }; - var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); - ambiguous = !bct; - } else { - ambiguous = false; - } - } - return { - sig: best.signature, - ambiguous: ambiguous - }; - }; - TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { - var applicableSigs = []; - var memberType = null; - var miss = false; - var cxt = null; - var hadProvisionalErrors = false; - for(var i = 0; i < signatures.length; i++) { - miss = false; - for(var j = 0; j < args.members.length; j++) { - if(j >= signatures[i].parameters.length) { - continue; - } - memberType = signatures[i].parameters[j].getType(); - if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { - memberType = memberType.elementType; - } - if(memberType == this.anyType) { - continue; - } else { - if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { - if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { - continue; - } - if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { - if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { - this.typeFlow.typeCheck(args.members[j]); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - break; - } - } else { - break; - } - } else { - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } else { - if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { - if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } else { - if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { - if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - break; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } - } - } - } - if(j == args.members.length) { - applicableSigs[applicableSigs.length] = { - signature: signatures[i], - hadProvisionalErrors: hadProvisionalErrors - }; - } - hadProvisionalErrors = false; - } - return applicableSigs; - }; - TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { - if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { - return false; - } - beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); - if(!beStringent) { - return true; - } - if(!funcDecl.signature) { - this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); - this.typeFlow.typeCheck(funcDecl); - } - var signature = funcDecl.signature; - var paramLen = signature.parameters.length; - for(var i = 0; i < paramLen; i++) { - var param = signature.parameters[i]; - var symbol = param; - var argDecl = symbol.declAST; - if(beStringent && argDecl.typeExpr) { - return false; - } - } - if(candidateType.construct && candidateType.call) { - return false; - } - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - if(!candidateSigs || candidateSigs.signatures.length > 1) { - return false; - } - return true; - }; - TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { - if(targetType == this.typeFlow.objectInterfaceType) { - return true; - } - var memberDecls = objectLit.operand; - if(!(memberDecls && targetType.memberScope)) { - return false; - } - var id = null; - var targetMember = null; - var text = ""; - var foundSyms = { - }; - for(var i = 0; i < memberDecls.members.length; i++) { - id = (memberDecls.members[i]).operand1; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else { - if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - return false; - } - } - targetMember = targetType.memberScope.find(text, true, false); - if(!targetMember) { - return false; - } - foundSyms[text] = true; - } - var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); - for(var i = 0; i < targetMembers.length; i++) { - var memberName = targetMembers[i]; - var memberSym = targetType.memberScope.find(memberName, true, false); - if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.widenType = function (t) { - if(t == this.undefinedType || t == this.nullType) { - return this.anyType; - } - return t; - }; - TypeChecker.prototype.isNullOrUndefinedType = function (t) { - return t == this.undefinedType || t == this.nullType; - }; - TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { - var i = 0; - var len = collection.getLength(); - var nlastChecked = 0; - var bestCommonType = initialType; - if(targetType) { - bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; - } - var convergenceType = bestCommonType; - while(nlastChecked < len) { - for(i = 0; i < len; i++) { - if(i == nlastChecked) { - continue; - } - if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { - convergenceType = bestCommonType; - } - if(bestCommonType == this.anyType || bestCommonType == null) { - break; - } else { - if(targetType) { - collection.setTypeAtIndex(i, targetType); - } - } - } - if(convergenceType && bestCommonType) { - break; - } - nlastChecked++; - if(nlastChecked < len) { - convergenceType = collection.getTypeAtIndex(nlastChecked); - } - } - return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); - }; - TypeChecker.prototype.typesAreIdentical = function (t1, t2) { - if(t1 == t2) { - return true; - } - if(!t1 || !t2) { - return false; - } - if(t1.isClass() || t1.isClassInstance()) { - return false; - } - var comboId = (t2.typeID << 16) | t1.typeID; - if(this.identicalCache[comboId]) { - return true; - } - if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(t1.isArray() || t2.isArray()) { - if(!(t1.isArray() && t2.isArray())) { - return false; - } - this.identicalCache[comboId] = false; - var ret = this.typesAreIdentical(t1.elementType, t2.elementType); - if(ret) { - this.subtypeCache[comboId] = true; - } else { - this.subtypeCache[comboId] = undefined; - } - return ret; - } - if(t1.primitiveTypeClass != t2.primitiveTypeClass) { - return false; - } - this.identicalCache[comboId] = false; - if(t1.memberScope && t2.memberScope) { - var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); - var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); - if(t1MemberKeys.length != t2MemberKeys.length) { - this.identicalCache[comboId] = undefined; - return false; - } - var t1MemberSymbol = null; - var t2MemberSymbol = null; - var t1MemberType = null; - var t2MemberType = null; - for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { - if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); - t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); - if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberType = t1MemberSymbol.getType(); - t2MemberType = t2MemberSymbol.getType(); - if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { - continue; - } - if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { - this.identicalCache[comboId] = undefined; - return false; - } - } - } else { - if(t1.memberScope || t2.memberScope) { - this.identicalCache[comboId] = undefined; - return false; - } - } - if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { - this.identicalCache[comboId] = undefined; - return false; - } - this.identicalCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { - if(sg1 == sg2) { - return true; - } - if(!sg1 || !sg2) { - return false; - } - if(sg1.signatures.length != sg2.signatures.length) { - return false; - } - var sig1 = null; - var sig2 = null; - var sigsMatch = false; - for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { - sig1 = sg1.signatures[iSig1]; - for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { - sig2 = sg2.signatures[iSig2]; - if(this.signaturesAreIdentical(sig1, sig2)) { - sigsMatch = true; - break; - } - } - if(sigsMatch) { - sigsMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { - if(s1.hasVariableArgList != s2.hasVariableArgList) { - return false; - } - if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { - return false; - } - if(s1.parameters.length != s2.parameters.length) { - return false; - } - if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { - return false; - } - for(var iParam = 0; iParam < s1.parameters.length; iParam++) { - if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { - if(source == target) { - return true; - } - if(!(source && target)) { - return true; - } - var comboId = (source.typeID << 16) | target.typeID; - if(comparisonCache[comboId] != undefined) { - return true; - } - if(assignableTo) { - if(source == this.anyType || target == this.anyType) { - return true; - } - } else { - if(target == this.anyType) { - return true; - } - } - if(source == this.undefinedType) { - return true; - } - if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { - return true; - } - if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(source.isArray() || target.isArray()) { - if(!(source.isArray() && target.isArray())) { - return false; - } - comparisonCache[comboId] = false; - var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); - if(ret) { - comparisonCache[comboId] = true; - } else { - comparisonCache[comboId] = undefined; - } - return ret; - } - if(source.primitiveTypeClass != target.primitiveTypeClass) { - if(target.primitiveTypeClass == TypeScript.Primitive.None) { - if(source == this.numberType && this.typeFlow.numberInterfaceType) { - source = this.typeFlow.numberInterfaceType; - } else { - if(source == this.stringType && this.typeFlow.stringInterfaceType) { - source = this.typeFlow.stringInterfaceType; - } else { - if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { - source = this.typeFlow.booleanInterfaceType; - } else { - return false; - } - } - } - } else { - return false; - } - } - comparisonCache[comboId] = false; - if(source.hasBase(target)) { - comparisonCache[comboId] = true; - return true; - } - if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { - return true; - } - if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { - return true; - } - if(target.isClass() || target.isClassInstance()) { - comparisonCache[comboId] = undefined; - return false; - } - if(target.memberScope && source.memberScope) { - var mPropKeys = target.memberScope.getAllValueSymbolNames(true); - var mProp = null; - var nProp = null; - var mPropType = null; - var nPropType = null; - var inferenceSymbol = null; - for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { - mProp = target.memberScope.find(mPropKeys[iMProp], false, false); - nProp = source.memberScope.find(mPropKeys[iMProp], false, false); - if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { - continue; - } - if(mProp.isInferenceSymbol()) { - inferenceSymbol = mProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(mProp.declAST); - } - } - mPropType = mProp.getType(); - if(!nProp) { - if(this.typeFlow.objectInterfaceType) { - nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { - nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; - comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); - } - return false; - } else { - continue; - } - } - } - } - if(nProp.isInferenceSymbol()) { - inferenceSymbol = nProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(nProp.declAST); - } - } - nPropType = nProp.getType(); - if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { - continue; - } - if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; - comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } - return false; - } - } - } - if(source.call || target.call) { - if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.call && target.call) { - comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.call ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(source.construct || target.construct) { - if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.construct && target.construct) { - comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(target.index) { - var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; - var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; - if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - comparisonCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { - if(sourceSG == targetSG) { - return true; - } - if(!(sourceSG && targetSG)) { - return false; - } - var mSig = null; - var nSig = null; - var foundMatch = false; - for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { - mSig = targetSG.signatures[iMSig]; - for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { - nSig = sourceSG.signatures[iNSig]; - if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { - foundMatch = true; - break; - } - } - if(foundMatch) { - foundMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { - if(!sourceSig.parameters || !targetSig.parameters) { - return false; - } - var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; - var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; - if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; - comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); - } - return false; - } - var sourceReturnType = sourceSig.returnType.type; - var targetReturnType = targetSig.returnType.type; - if(targetReturnType != this.voidType) { - if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; - } - return false; - } - } - var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; - var sourceParamType = null; - var targetParamType = null; - var sourceParamName = ""; - var targetParamName = ""; - for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { - if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } else { - if(iSource == sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - if(sourceParamType.elementType) { - sourceParamType = sourceParamType.elementType; - } - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } - } - if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } else { - if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - if(targetParamType.elementType) { - targetParamType = targetParamType.elementType; - } - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } - } - if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; - } - return false; - } - } - return true; - }; - return TypeChecker; - })(); - TypeScript.TypeChecker = TypeChecker; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Continuation = (function () { - function Continuation(normalBlock) { - this.normalBlock = normalBlock; - this.exceptionBlock = -1; - } - return Continuation; - })(); - TypeScript.Continuation = Continuation; - function getBaseTypeLinks(bases, baseTypeLinks) { - if(bases) { - var len = bases.members.length; - if(baseTypeLinks == null) { - baseTypeLinks = new Array(); - } - for(var i = 0; i < len; i++) { - var baseExpr = bases.members[i]; - var name = baseExpr; - var typeLink = new TypeScript.TypeLink(); - typeLink.ast = name; - baseTypeLinks[baseTypeLinks.length] = typeLink; - } - } - return baseTypeLinks; - } - function getBases(type, typeDecl) { - type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); - type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); - } - function addPrototypeField(classType, ast, context) { - var field = new TypeScript.ValueLocation(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.ast = ast; - field.typeLink.type = classType.instanceType; - var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - classType.members.addPublicMember("prototype", fieldSymbol); - } - function createNewConstructGroupForType(type) { - var signature = new TypeScript.Signature(); - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = type.instanceType; - signature.parameters = []; - type.construct = new TypeScript.SignatureGroup(); - type.construct.addSignature(signature); - } - TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; - function cloneParentConstructGroupForChildType(child, parent) { - child.construct = new TypeScript.SignatureGroup(); - var sig = null; - if(!parent.construct) { - createNewConstructGroupForType(parent); - } - for(var i = 0; i < parent.construct.signatures.length; i++) { - sig = new TypeScript.Signature(); - sig.parameters = parent.construct.signatures[i].parameters; - sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; - sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; - sig.declAST = parent.construct.signatures[i].declAST; - sig.returnType = new TypeScript.TypeLink(); - sig.returnType.type = child.instanceType; - child.construct.addSignature(sig); - } - } - TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; - TypeScript.globalId = "__GLO"; - function findTypeSymbolInScopeChain(name, scopeChain) { - var symbol = scopeChain.scope.find(name, false, true); - if(symbol == null && scopeChain.previous) { - symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); - } - return symbol; - } - function findSymbolFromAlias(alias, context) { - var symbol = null; - switch(alias.nodeType) { - case TypeScript.NodeType.Name: { - var name = (alias).text; - var isDynamic = TypeScript.isQuoted(name); - var findSym = function (id) { - if(context.members) { - return context.members.lookup(name); - } else { - return findTypeSymbolInScopeChain(name, context.topLevelScope); - } - }; - if(isDynamic) { - symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); - } else { - symbol = findSym(name); - } - break; - - } - case TypeScript.NodeType.Dot: { - var dottedExpr = alias; - var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); - if(op1Sym && op1Sym.getType()) { - symbol = findSymbolFromAlias(dottedExpr.operand2, context); - } - break; - - } - default: { - break; - - } - } - if(symbol) { - var symType = symbol.getType(); - if(symType) { - var members = symType.members; - if(members) { - context.members = members.publicMembers; - } - } - } - return symbol; - } - function preCollectImportTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var typeSymbol = null; - var modType = null; - var importDecl = ast; - var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { - topLevelScope: scopeChain, - members: null, - tcContext: context - }); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - if(aliasedModSymbol) { - var aliasedModType = aliasedModSymbol.getType(); - if(aliasedModType) { - modType = aliasedModType; - } - } - typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); - typeSymbol.aliasLink = importDecl; - if(context.scopeChain.moduleDecl) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = importDecl; - importDecl.id.sym = typeSymbol; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); - return true; - } - TypeScript.preCollectImportTypes = preCollectImportTypes; - function preCollectModuleTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var moduleDecl = ast; - var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); - var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - var modName = (moduleDecl.name).text; - var isDynamic = TypeScript.isQuoted(modName); - var symbol = scopeChain.scope.findLocal(modName, false, false); - var typeSymbol = null; - var modType = null; - if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { - if(modType == null) { - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.setHasImplementation(); - } - typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); - typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); - if(context.scopeChain.moduleDecl) { - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = moduleDecl; - typeSymbol.prettyName = moduleDecl.prettyName; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - modType.symbol = typeSymbol; - } else { - if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { - context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); - } - typeSymbol = symbol; - var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; - var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; - var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicMembers = typeSymbol.type.members.publicMembers; - var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); - var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; - var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = members; - modType.ambientMembers = ambientMembers; - modType.setHasImplementation(); - modType.symbol = typeSymbol; - typeSymbol.addLocation(moduleDecl.minChar); - typeSymbol.expansions.push(modType); - typeSymbol.expansionsDeclAST.push(moduleDecl); - } - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - moduleDecl.mod = modType; - TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); - return true; - } - TypeScript.preCollectModuleTypes = preCollectModuleTypes; - function preCollectClassTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var classDecl = ast; - var classType; - var instanceType; - var typeSymbol = null; - var className = (classDecl.name).text; - var alreadyInScope = false; - var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var containerMod = scopeChain.container; - var foundValSymbol = false; - typeSymbol = scopeChain.scope.findLocal(className, false, true); - if(!typeSymbol) { - var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); - if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { - typeSymbol = valTypeSymbol; - foundValSymbol = true; - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - } - } - if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { - typeSymbol = null; - } - if(typeSymbol == null) { - var valueSymbol = scopeChain.scope.findLocal(className, false, false); - classType = new TypeScript.Type(); - classType.setHasImplementation(); - instanceType = new TypeScript.Type(); - instanceType.setHasImplementation(); - classType.instanceType = instanceType; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - addPrototypeField(classType, classDecl, context); - instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); - typeSymbol.declAST = classDecl; - typeSymbol.instanceType = instanceType; - classType.symbol = typeSymbol; - instanceType.symbol = typeSymbol; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - typeSymbol.declModule = context.scopeChain.moduleDecl; - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - ast.type = classType; - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - if(valueSymbol == null) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - } - } else { - classType = typeSymbol.type; - if(classType.instanceType == null) { - classType.instanceType = new TypeScript.Type(); - classType.instanceType.setHasImplementation(); - classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.instanceType.symbol = classType.symbol; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - } - instanceType = classType.instanceType; - ast.type = classType; - } - if(!classDecl.constructorDecl) { - if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { - context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); - } - createNewConstructGroupForType(classDecl.type); - } - classType.typeFlags |= TypeScript.TypeFlags.IsClass; - instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; - getBases(instanceType, classDecl); - TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); - return true; - } - TypeScript.preCollectClassTypes = preCollectClassTypes; - function preCollectInterfaceTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var interfaceDecl = ast; - var interfaceSymbol = null; - var interfaceType = null; - var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var alreadyInScope = true; - alreadyInScope = false; - var interfaceName = (interfaceDecl.name).text; - interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); - if(interfaceSymbol == null) { - interfaceType = new TypeScript.Type(); - interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceSymbol.declAST = interfaceDecl; - interfaceSymbol.declModule = context.scopeChain.moduleDecl; - } else { - alreadyInScope = true; - interfaceType = interfaceSymbol.type; - } - if(!interfaceType) { - interfaceType = context.checker.anyType; - } - ast.type = interfaceType; - getBases(interfaceType, interfaceDecl); - if(isExported) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(context.scopeChain.moduleDecl) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(!alreadyInScope) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); - } - TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); - return true; - } - TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; - function preCollectArgDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var argDecl = ast; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { - var field = new TypeScript.ValueLocation(); - var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); - var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); - fieldSymbol.transferVarFlags(argDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - argDecl.parameterPropertySym = fieldSymbol; - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); - field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); - argDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; - function preCollectVarDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var varDecl = ast; - var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); - var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); - var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); - var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { - if(isAmbient) { - var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); - if(existingSym) { - varDecl.sym = existingSym; - return false; - } - } - if(varDecl.id == null) { - context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); - return false; - } - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - if(isOptional) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; - } - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - fieldSymbol.declModule = context.scopeChain.moduleDecl; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { - if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { - context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); - } - fieldSymbol.container = context.scopeChain.classType.symbol; - } else { - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); - varDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; - function preCollectFuncDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - var funcDecl = ast; - var fgSym = null; - var nameText = funcDecl.getNameText(); - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); - var containerScope = context.scopeChain.scope; - var isGlobal = containerSym == context.checker.gloMod; - var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); - var go = false; - var foundSymbol = false; - if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - containerSym = containerSym.container; - containerScope = scopeChain.previous.scope; - } - funcDecl.unitIndex = context.checker.locationInfo.unitIndex; - if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { - return go; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { - var instType = context.scopeChain.thisType; - if(nameText && nameText != "__missing") { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - fgSym = containerScope.findLocal(nameText, false, false); - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, true); - } - } - if(fgSym) { - foundSymbol = true; - if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { - fgSym = null; - } - } - } - if(fgSym == null) { - if(!(funcDecl.isSpecialFn())) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; - } else { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; - } - if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { - fgSym.declAST = ast; - } - } else { - if((fgSym.kind() == TypeScript.SymbolKind.Type)) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; - } else { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - } - } - if(funcDecl.isSpecialFn() && !isStatic) { - funcDecl.type = instType ? instType : fgSym.type; - } else { - funcDecl.type = fgSym.type; - } - } else { - if(nameText) { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - if(funcDecl.isConstructor && context.scopeChain.previous) { - fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); - } - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, false); - } - } - if(fgSym) { - foundSymbol = true; - if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { - fgSym = null; - foundSymbol = false; - } - } - } - if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); - } - if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - fgSym.type = context.checker.anyType; - } - var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); - if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); - } - funcDecl.type.symbol.declAST = ast; - if(funcDecl.isConstructor) { - go = true; - } - ; ; - } - if(isExported) { - if(funcDecl.type.call) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { - fgSym.flags |= TypeScript.SymbolFlags.Exported; - } - } - if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; - funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; - } - if(fgSym && isOptional) { - fgSym.flags |= TypeScript.SymbolFlags.Optional; - } - return go; - } - TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; - function preCollectTypes(ast, parent, walker) { - var context = walker.state; - var go = false; - var scopeChain = context.scopeChain; - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - context.script = script; - go = true; - } else { - if(ast.nodeType == TypeScript.NodeType.List) { - go = true; - } else { - if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { - go = preCollectImportTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - go = false; - } else { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - go = preCollectModuleTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - go = preCollectClassTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.Block) { - go = true; - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - go = preCollectInterfaceTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - go = preCollectArgDeclTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.VarDecl) { - go = preCollectVarDeclTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - go = preCollectFuncDeclTypes(ast, parent, context); - } else { - if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - } - } - } - } - } - } - } - } - } - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preCollectTypes = preCollectTypes; - function postCollectTypes(ast, parent, walker) { - var context = walker.state; - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - TypeScript.popTypeCollectionScope(context); - } - } - } - return ast; - } - TypeScript.postCollectTypes = postCollectTypes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopeChain = (function () { - function ScopeChain(container, previous, scope) { - this.container = container; - this.previous = previous; - this.scope = scope; - } - return ScopeChain; - })(); - TypeScript.ScopeChain = ScopeChain; - var BBUseDefInfo = (function () { - function BBUseDefInfo(bb) { - this.bb = bb; - this.defsBySymbol = new Array(); - this.useIndexBySymbol = new Array(); - } - BBUseDefInfo.prototype.updateTop = function () { - var temp = new BitVector(this.top.bitCount); - for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { - var succ = this.bb.successors[i]; - if(succ.useDef) { - temp.union(succ.useDef.top); - } - } - temp.difference(this.kill); - temp.union(this.gen); - var changed = temp.notEq(this.top); - this.top = temp; - return changed; - }; - BBUseDefInfo.prototype.initialize = function (useDefContext) { - var _this = this; - var defSym = function (sym, context) { - if(context.isLocalSym(sym)) { - var index = context.getSymbolIndex(sym); - _this.useIndexBySymbol[index] = new Array(); - _this.defsBySymbol[index] = true; - } - }; - var useSym = function (sym, context, ast) { - if(context.isLocalSym(sym)) { - var symIndex = context.getSymbolIndex(sym); - if(_this.useIndexBySymbol[symIndex] == undefined) { - _this.useIndexBySymbol[symIndex] = new Array(); - } - var symUses = _this.useIndexBySymbol[symIndex]; - var astIndex = context.getUseIndex(ast); - context.addUse(symIndex, astIndex); - symUses.push(astIndex); - } - }; - function initUseDefPre(cur, parent, walker) { - var context = walker.state; - if(cur == null) { - cur = null; - } - if(cur.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = cur; - if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { - defSym(varDecl.sym, context); - } - } else { - if(cur.nodeType == TypeScript.NodeType.Name) { - if(parent) { - if(parent.nodeType == TypeScript.NodeType.Asg) { - var asg = parent; - if(asg.operand1 == cur) { - return cur; - } - } else { - if(parent.nodeType == TypeScript.NodeType.VarDecl) { - var parentDecl = parent; - if(parentDecl.id == cur) { - return cur; - } - } - } - } - var id = cur; - useSym(id.sym, context, cur); - } else { - if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { - var asg = cur; - if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { - var id = asg.operand1; - defSym(id.sym, context); - } - } else { - if(cur.nodeType == TypeScript.NodeType.FuncDecl) { - walker.options.goChildren = false; - } - } - } - } - return cur; - } - var options = new TypeScript.AstWalkOptions(); - options.reverseSiblings = true; - TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); - }; - BBUseDefInfo.prototype.initializeGen = function (useDefContext) { - var symbolLen = this.useIndexBySymbol.length; - var bitCount = useDefContext.uses.length; - this.gen = new BitVector(bitCount); - for(var s = 0; s < symbolLen; s++) { - var symUses = this.useIndexBySymbol[s]; - if((symUses != undefined) && (symUses.length > 0)) { - for(var u = 0, uLen = symUses.length; u < uLen; u++) { - this.gen.set(symUses[u], true); - } - } - } - this.top = this.gen; - }; - BBUseDefInfo.prototype.initializeKill = function (useDefContext) { - this.kill = new BitVector(this.gen.bitCount); - for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { - if(this.defsBySymbol[s]) { - var globalSymUses = useDefContext.useIndexBySymbol[s]; - if(globalSymUses) { - for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { - this.kill.set(globalSymUses[u], true); - } - } - } - } - }; - return BBUseDefInfo; - })(); - TypeScript.BBUseDefInfo = BBUseDefInfo; - var UseDefContext = (function () { - function UseDefContext() { - this.useIndexBySymbol = new Array(); - this.uses = new Array(); - this.symbols = new Array(); - this.symbolMap = new TypeScript.StringHashTable(); - this.symbolCount = 0; - } - UseDefContext.prototype.getSymbolIndex = function (sym) { - var name = sym.name; - var index = (this.symbolMap.lookup(name)); - if(index == null) { - index = this.symbolCount++; - this.symbols[index] = sym; - this.symbolMap.add(name, index); - } - return index; - }; - UseDefContext.prototype.addUse = function (symIndex, astIndex) { - var useBySym = this.useIndexBySymbol[symIndex]; - if(useBySym == undefined) { - useBySym = new Array(); - this.useIndexBySymbol[symIndex] = useBySym; - } - useBySym[useBySym.length] = astIndex; - }; - UseDefContext.prototype.getUseIndex = function (ast) { - this.uses[this.uses.length] = ast; - return this.uses.length - 1; - }; - UseDefContext.prototype.isLocalSym = function (sym) { - return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); - }; - UseDefContext.prototype.killSymbol = function (sym, bbUses) { - var index = this.symbolMap.lookup(sym.name); - var usesOfSym = this.useIndexBySymbol[index]; - for(var k = 0, len = usesOfSym.length; k < len; k++) { - bbUses.set(usesOfSym[k], true); - } - }; - return UseDefContext; - })(); - TypeScript.UseDefContext = UseDefContext; - var BitVector = (function () { - function BitVector(bitCount) { - this.bitCount = bitCount; - this.firstBits = 0; - this.restOfBits = null; - if(this.bitCount > BitVector.packBits) { - this.restOfBits = new Array(); - var len = Math.floor(this.bitCount / BitVector.packBits); - for(var i = 0; i < len; i++) { - this.restOfBits[i] = 0; - } - } - } - BitVector.packBits = 30; - BitVector.prototype.set = function (bitIndex, value) { - if(bitIndex < BitVector.packBits) { - if(value) { - this.firstBits |= (1 << bitIndex); - } else { - this.firstBits &= (~(1 << bitIndex)); - } - } else { - var offset = Math.floor(bitIndex / BitVector.packBits) - 1; - var localIndex = bitIndex % BitVector.packBits; - if(value) { - this.restOfBits[offset] |= (1 << localIndex); - } else { - this.restOfBits[offset] &= (~(1 << localIndex)); - } - } - }; - BitVector.prototype.map = function (fn) { - var k; - for(k = 0; k < BitVector.packBits; k++) { - if(k == this.bitCount) { - return; - } - if(((1 << k) & this.firstBits) != 0) { - fn(k); - } - } - if(this.restOfBits) { - var len; - var cumu = BitVector.packBits; - for(k = 0 , len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - for(var j = 0; j < BitVector.packBits; j++) { - if(((1 << j) & myBits) != 0) { - fn(cumu); - } - cumu++; - if(cumu == this.bitCount) { - return; - } - } - } - } - }; - BitVector.prototype.union = function (b) { - this.firstBits |= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits | bBits; - } - } - }; - BitVector.prototype.intersection = function (b) { - this.firstBits &= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits & bBits; - } - } - }; - BitVector.prototype.notEq = function (b) { - if(this.firstBits != b.firstBits) { - return true; - } - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - if(myBits != bBits) { - return true; - } - } - } - return false; - }; - BitVector.prototype.difference = function (b) { - var oldFirstBits = this.firstBits; - this.firstBits &= (~b.firstBits); - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] &= (~bBits); - } - } - }; - return BitVector; - })(); - TypeScript.BitVector = BitVector; - var BasicBlock = (function () { - function BasicBlock() { - this.predecessors = new Array(); - this.index = -1; - this.markValue = 0; - this.successors = new Array(); - this.useDef = null; - this.content = new TypeScript.ASTList(); - } - BasicBlock.prototype.marked = function (markBase) { - return this.markValue > markBase; - }; - BasicBlock.prototype.mark = function () { - this.markValue++; - }; - BasicBlock.prototype.addSuccessor = function (successor) { - this.successors[this.successors.length] = successor; - successor.predecessors[successor.predecessors.length] = this; - }; - return BasicBlock; - })(); - TypeScript.BasicBlock = BasicBlock; - var ControlFlowContext = (function () { - function ControlFlowContext(current, exit) { - this.current = current; - this.exit = exit; - this.entry = null; - this.unreachable = null; - this.noContinuation = false; - this.statementStack = new Array(); - this.currentSwitch = new Array(); - this.markBase = 0; - this.linearBBs = new Array(); - this.entry = this.current; - } - ControlFlowContext.prototype.walk = function (ast, parent) { - return this.walker.walk(ast, parent); - }; - ControlFlowContext.prototype.pushSwitch = function (bb) { - this.currentSwitch.push(bb); - }; - ControlFlowContext.prototype.popSwitch = function () { - return this.currentSwitch.pop(); - }; - ControlFlowContext.prototype.reportUnreachable = function (er) { - if(this.unreachable && (this.unreachable.length > 0)) { - var len = this.unreachable.length; - for(var i = 0; i < len; i++) { - var unreachableAST = this.unreachable[i]; - if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { - er.simpleError(unreachableAST, "unreachable code"); - } - } - } - }; - ControlFlowContext.prototype.printAST = function (ast, outfile) { - var printContext = new TypeScript.PrintContext(outfile, null); - printContext.increaseIndent(); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); - printContext.decreaseIndent(); - }; - ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { - var content = bb.content; - for(var i = 0, len = content.members.length; i < len; i++) { - var ast = content.members[i]; - this.printAST(ast, outfile); - } - }; - ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { - var markValue = this.markBase++; - var q = new Array(); - q[q.length] = this.entry; - while(q.length > 0) { - var bb = q.pop(); - if(!(bb.marked(markValue))) { - bb.mark(); - if(nodeFunc) { - nodeFunc(bb); - } - var succLen = bb.successors.length; - if(succLen > 0) { - if(preEdges) { - preEdges(); - } - for(var j = succLen - 1; j >= 0; j--) { - var successor = bb.successors[j]; - if(!(successor.marked(this.markBase))) { - if(edgeFunc) { - edgeFunc(bb, successor); - } - q[q.length] = successor; - } - } - if(postEdges) { - postEdges(); - } - } - } - } - }; - ControlFlowContext.prototype.useDef = function (er, funcSym) { - var _this = this; - var useDefContext = new UseDefContext(); - useDefContext.func = funcSym; - var useDefInit = function (bb) { - bb.useDef = new BBUseDefInfo(bb); - bb.useDef.initialize(useDefContext); - _this.linearBBs[_this.linearBBs.length] = bb; - }; - this.bfs(useDefInit, null, null, null); - var i, bbLen; - for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { - this.linearBBs[i].useDef.initializeGen(useDefContext); - this.linearBBs[i].useDef.initializeKill(useDefContext); - } - var changed = true; - while(changed) { - changed = false; - for(i = 0; i < bbLen; i++) { - changed = this.linearBBs[i].useDef.updateTop() || changed; - } - } - var top = this.entry.useDef.top; - top.map(function (index) { - var ast = useDefContext.uses[index]; - er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); - }); - }; - ControlFlowContext.prototype.print = function (outfile) { - var _this = this; - var index = 0; - var node = function (bb) { - if(bb.index < 0) { - bb.index = index++; - } - if(bb == _this.exit) { - outfile.WriteLine("Exit block with index " + bb.index); - } else { - outfile.WriteLine("Basic block with index " + bb.index); - _this.printBlockContent(bb, outfile); - } - }; - function preEdges() { - outfile.Write(" Branches to "); - } - function postEdges() { - outfile.WriteLine(""); - } - function edge(node1, node2) { - if(node2.index < 0) { - node2.index = index++; - } - outfile.Write(node2.index + " "); - } - this.bfs(node, edge, preEdges, postEdges); - if(this.unreachable != null) { - for(var i = 0, len = this.unreachable.length; i < len; i++) { - outfile.WriteLine("Unreachable basic block ..."); - this.printAST(this.unreachable[i], outfile); - } - } - }; - ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { - this.statementStack.push({ - stmt: stmt, - continueBB: continueBB, - breakBB: breakBB - }); - }; - ControlFlowContext.prototype.popStatement = function () { - return this.statementStack.pop(); - }; - ControlFlowContext.prototype.returnStmt = function () { - this.current.addSuccessor(this.exit); - this.setUnreachable(); - }; - ControlFlowContext.prototype.setUnreachable = function () { - this.current = null; - this.noContinuation = true; - }; - ControlFlowContext.prototype.addUnreachable = function (ast) { - if(this.unreachable === null) { - this.unreachable = new Array(); - } - this.unreachable[this.unreachable.length] = ast; - }; - ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { - var targetBB = null; - for(var i = 0, len = this.statementStack.length; i < len; i++) { - var targetInfo = this.statementStack[i]; - if(targetInfo.stmt == target) { - if(isContinue) { - targetBB = targetInfo.continueBB; - } else { - targetBB = targetInfo.breakBB; - } - break; - } - } - if(targetBB) { - this.current.addSuccessor(targetBB); - } - this.setUnreachable(); - }; - ControlFlowContext.prototype.addContent = function (ast) { - if(this.current) { - this.current.content.append(ast); - } - }; - return ControlFlowContext; - })(); - TypeScript.ControlFlowContext = ControlFlowContext; - var ResolutionDataCache = (function () { - function ResolutionDataCache() { - this.cacheSize = 16; - this.rdCache = []; - this.nextUp = 0; - for(var i = 0; i < this.cacheSize; i++) { - this.rdCache[i] = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: i - }; - } - } - ResolutionDataCache.prototype.getResolutionData = function () { - var rd = null; - if(this.nextUp < this.cacheSize) { - rd = this.rdCache[this.nextUp]; - } - if(rd == null) { - this.cacheSize++; - rd = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: this.cacheSize - }; - this.rdCache[this.cacheSize] = rd; - } - this.nextUp++; - return rd; - }; - ResolutionDataCache.prototype.returnResolutionData = function (rd) { - rd.actuals.length = 0; - rd.exactCandidates.length = 0; - rd.conversionCandidates.length = 0; - this.nextUp = rd.id; - }; - return ResolutionDataCache; - })(); - TypeScript.ResolutionDataCache = ResolutionDataCache; - var TypeFlow = (function () { - function TypeFlow(logger, initScope, parser, checker) { - this.logger = logger; - this.initScope = initScope; - this.parser = parser; - this.checker = checker; - this.thisFnc = null; - this.thisClassNode = null; - this.enclosingFncIsMethod = false; - this.arrayInterfaceType = null; - this.stringInterfaceType = null; - this.objectInterfaceType = null; - this.functionInterfaceType = null; - this.numberInterfaceType = null; - this.booleanInterfaceType = null; - this.iargumentsInterfaceType = null; - this.currentScript = null; - this.inImportTypeCheck = false; - this.inTypeRefTypeCheck = false; - this.inArrayElementTypeCheck = false; - this.resolutionDataCache = new ResolutionDataCache(); - this.nestingLevel = 0; - this.inSuperCall = false; - this.checker.typeFlow = this; - this.scope = this.initScope; - this.globalScope = this.initScope; - this.doubleType = this.checker.numberType; - this.booleanType = this.checker.booleanType; - this.stringType = this.checker.stringType; - this.anyType = this.checker.anyType; - this.regexType = this.anyType; - this.nullType = this.checker.nullType; - this.voidType = this.checker.voidType; - this.arrayAnyType = this.checker.makeArrayType(this.anyType); - } - TypeFlow.prototype.initLibs = function () { - var arraySym = this.globalScope.find("Array", false, true); - if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { - this.arrayInterfaceType = (arraySym).type; - } - var stringSym = this.globalScope.find("String", false, true); - if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { - this.stringInterfaceType = (stringSym).type; - } - var objectSym = this.globalScope.find("Object", false, true); - if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { - this.objectInterfaceType = (objectSym).type; - } - var fnSym = this.globalScope.find("Function", false, true); - if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { - this.functionInterfaceType = (fnSym).type; - } - var numberSym = this.globalScope.find("Number", false, true); - if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { - this.numberInterfaceType = (numberSym).type; - } - var booleanSym = this.globalScope.find("Boolean", false, true); - if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { - this.booleanInterfaceType = (booleanSym).type; - } - var regexSym = this.globalScope.find("RegExp", false, true); - if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { - this.regexType = (regexSym).type; - } - }; - TypeFlow.prototype.cast = function (ast, type) { - return this.castWithCoercion(ast, type, true, false); - }; - TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { - if(applyCoercion) { - if(type == null) { - ast.type = this.anyType; - } else { - if(type.isClass()) { - ast.type = type.instanceType; - } else { - ast.type = type; - } - } - } - return ast; - } else { - this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); - return ast; - } - }; - TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { - var prevScope = this.scope; - this.scope = enclosingScope; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var svThisClassNode = this.thisClassNode; - var svCurrentModDecl = this.checker.currentModDecl; - var prevMethodStatus = this.enclosingFncIsMethod; - var container = this.scope.container; - var fnc = null; - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - if(fnc == null) { - this.enclosingFncIsMethod = typeSym.isMethod; - fnc = container.declAST; - } - } - if(type.isClass()) { - this.thisType = type.instanceType; - if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { - this.thisClassNode = typeSym.declAST; - } - break; - } - if(type.isModuleType()) { - this.checker.currentModDecl = typeSym.declAST; - break; - } - } - container = container.container; - } - this.thisFnc = fnc; - var updated = this.typeCheck(ast); - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.thisClassNode = svThisClassNode; - this.checker.currentModDecl = svCurrentModDecl; - this.enclosingFncIsMethod = prevMethodStatus; - this.scope = prevScope; - return updated; - }; - TypeFlow.prototype.typeCheck = function (ast) { - if(ast) { - return ast.typeCheck(this); - } else { - return null; - } - }; - TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { - if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { - this.inScopeTypeCheckBoundDecl(ast); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if(funcDecl.isAccessor()) { - this.typeCheckFunction(funcDecl); - } - } - } - }; - TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { - var sym = varDecl.sym; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevLocationInfo = this.checker.locationInfo; - if(sym && sym.container) { - var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - this.thisFnc = sym.container.declAST; - } - if(instanceScope) { - var prevScope = this.scope; - this.scope = instanceScope; - var container = sym.container; - if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[sym.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - this.enclosingFncIsMethod = typeSym.isMethod; - } - if(type.isClass()) { - this.thisType = type.instanceType; - break; - } - } - container = container.container; - } - this.typeCheckBoundDecl(varDecl); - this.scope = prevScope; - } - } - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.checker.locationInfo = prevLocationInfo; - this.enclosingFncIsMethod = prevMethodStatus; - }; - TypeFlow.prototype.resolveBoundDecl = function (varDecl) { - if(varDecl.typeExpr) { - if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { - this.typeCheck(varDecl.typeExpr); - } - varDecl.type = varDecl.typeExpr.type; - if(varDecl.sym) { - varDecl.sym.setType(varDecl.type); - } - } else { - if(varDecl.init == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - if(varDecl.sym) { - if(varDecl.sym.isType()) { - var tsym = varDecl.sym; - if(tsym.isMethod) { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); - return; - } else { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); - return; - } - } - varDecl.sym.setType(varDecl.type); - } - } - } - }; - TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { - var _this = this; - var infSym = varDecl.sym; - if(infSym == null) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = this.checker.widenType(varDecl.init.type); - } else { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - } - } else { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - infSym.setType(this.anyType); - } else { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(infSym); - var resolved = false; - if(varDecl.type == null) { - if(varDecl.typeExpr) { - this.resolveBoundDecl(varDecl); - resolved = true; - varDecl.type = varDecl.typeExpr.type; - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } - } - if(varDecl.init) { - var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); - var prevScope = this.scope; - var applyTargetType = !varDecl.init.isParenthesized; - if(isLocalStatic) { - this.scope = varDecl.sym.container.getType().memberScope; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { - TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { - if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; - } - walker.options.goChildren = false; - } - return ast; - }); - } - this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); - this.scope = prevScope; - if(varDecl.type) { - var preserveScope = false; - var preservedContainedScope = null; - if(varDecl.init.type) { - preservedContainedScope = varDecl.init.type.containedScope; - preserveScope = true; - if(varDecl.init.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - } - } - varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && varDecl.init.type.containedScope == null) { - varDecl.init.type.containedScope = preservedContainedScope; - } - } else { - varDecl.type = this.checker.widenType(varDecl.init.type); - if(varDecl.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - varDecl.type = this.anyType; - } - } - infSym.setType(varDecl.type); - } else { - if(!resolved) { - this.resolveBoundDecl(varDecl); - } - } - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else { - if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = infSym.getType(); - varDecl.init = this.cast(varDecl.init, varDecl.type); - } - } - } - } - } - if(varDecl.id && varDecl.sym) { - varDecl.id.sym = varDecl.sym; - } - if(varDecl.sym && varDecl.sym.container) { - this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { - return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); - }); - } - return varDecl; - }; - TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); - } else { - this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); - } - } else { - this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); - } - }; - TypeFlow.prototype.typeCheckSuper = function (ast) { - if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { - ast.type = this.thisType.baseClass(); - } else { - if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - var enclosingFnc = this.thisFnc.enclosingFnc; - while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - enclosingFnc = enclosingFnc.enclosingFnc; - } - if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { - ast.type = this.thisType.baseClass(); - enclosingFnc.setHasSuperReferenceInFatArrowFunction(); - return ast; - } - } - ast.type = this.anyType; - this.checker.errorReporter.invalidSuperReference(ast); - } - return ast; - }; - TypeFlow.prototype.typeCheckThis = function (ast) { - ast.type = this.anyType; - var illegalThisRef = false; - if(this.thisFnc == null) { - if(this.thisType) { - if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { - illegalThisRef = true; - } else { - ast.type = this.thisType; - } - } else { - if(this.checker.currentModDecl) { - this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); - } - } - } else { - if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { - illegalThisRef = true; - } - if(this.thisFnc.isMethod() || this.thisFnc.isConstructor || this.thisFnc.isTargetTypedAsMethod) { - if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - if(this.thisFnc.boundToProperty) { - var container = this.thisFnc.boundToProperty.sym.container; - if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - (container.declAST).setHasSelfReference(); - } - } else { - var encFnc = this.thisFnc.enclosingFnc; - var firstEncFnc = encFnc; - while(encFnc) { - if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { - illegalThisRef = true; - } - if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { - encFnc.setHasSelfReference(); - break; - } - encFnc = encFnc.enclosingFnc; - } - if(!encFnc && firstEncFnc) { - encFnc = firstEncFnc; - encFnc.setHasSelfReference(); - } else { - if(!encFnc) { - if(this.thisClassNode) { - (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; - } else { - if(this.checker.currentModDecl) { - this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; - } else { - this.checker.mustCaptureGlobalThis = true; - } - } - } - } - if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(illegalThisRef) { - this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); - } - return ast; - }; - TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - this.inScopeTypeCheckDecl(infSym.declAST); - } - if(!this.checker.styleSettings.innerScopeDeclEscape) { - if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { - if(this.nestingLevel < (infSym.declAST).nestingLevel) { - this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); - } - } - } - } - ast.type = symbol.getType(); - if(!symbol.writeable()) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } - } else { - if(symbol.isType()) { - ast.type = symbol.getType(); - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } else { - ast.type = this.anyType; - this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); - } - } - }; - TypeFlow.prototype.typeCheckName = function (ast) { - var _this = this; - var identifier = ast; - if(this.checker.inWith) { - identifier.type = this.anyType; - } else { - var typespace = this.inTypeRefTypeCheck; - var idText = identifier.text; - var originalIdText = idText; - var isDynamicModuleName = TypeScript.isQuoted(identifier.text); - var symbol = this.scope.find(idText, false, typespace); - if(symbol == null && isDynamicModuleName) { - symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { - return _this.scope.find(id, false, typespace); - }); - } - if(!symbol) { - if(!identifier.isMissing()) { - this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); - } - identifier.type = this.anyType; - } else { - if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { - var symType = symbol.getType(); - if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; - } - } - } - if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - (symbol.declAST).signature.returnType.type = this.anyType; - } - this.setTypeFromSymbol(ast, symbol); - identifier.sym = symbol; - if(this.thisFnc) { - if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { - this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; - } - } - } - } - return ast; - }; - TypeFlow.prototype.typeCheckScript = function (script) { - this.checker.locationInfo = script.locationInfo; - this.scope = this.checker.globalScope; - if(!script.topLevelMod) { - this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); - } - this.currentScript = script; - script.bod = this.typeCheck(script.bod); - this.currentScript = null; - return script; - }; - TypeFlow.prototype.typeCheckBitNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return unex; - }; - TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return ast; - }; - TypeFlow.prototype.typeCheckLogNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.booleanType; - return unex; - }; - TypeFlow.prototype.astIsWriteable = function (ast) { - return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); - }; - TypeFlow.prototype.typeCheckIncOrDec = function (ast) { - var unex = ast; - var lval = unex.operand; - if(!this.astIsWriteable(unex)) { - this.checker.errorReporter.valueCannotBeModified(unex); - unex.type = this.doubleType; - } else { - unex = this.typeCheckUnaryNumberOperator(ast); - if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { - this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); - } - } - return unex; - }; - TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { - var binex = ast; - var resultType = null; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { - resultType = this.doubleType; - } else { - if((leftType == this.booleanType) && (rightType == this.booleanType)) { - resultType = this.booleanType; - } else { - if(leftType == this.anyType) { - if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { - resultType = this.anyType; - } - } else { - if(rightType == this.anyType) { - if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { - resultType = this.anyType; - } - } - } - } - } - if(resultType == null) { - resultType = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = resultType; - return binex; - }; - TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - if(leftType == null || rightType == null) { - this.checker.errorReporter.simpleError(binex, "Could not typecheck arithmetic operation. Possible recursive typecheck error?"); - binex.type = this.anyType; - return binex; - } - var nodeType = binex.nodeType; - if(this.checker.isNullOrUndefinedType(leftType)) { - leftType = rightType; - } - if(this.checker.isNullOrUndefinedType(rightType)) { - rightType = leftType; - } - leftType = this.checker.widenType(leftType); - rightType = this.checker.widenType(rightType); - if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { - if(leftType == this.checker.stringType || rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else { - if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else { - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } - } - } - } else { - if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else { - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } - } - } - return binex; - }; - TypeFlow.prototype.typeCheckDotOperator = function (ast) { - var binex = ast; - var leftIsFnc = false; - binex.operand1 = this.typeCheck(binex.operand1); - var leftType = binex.operand1.type; - var leftScope = null; - if(leftType) { - if(leftType == this.anyType) { - binex.type = this.anyType; - return binex; - } else { - if(leftType == this.stringType) { - if(this.stringInterfaceType) { - leftScope = this.stringInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if(leftType == this.doubleType) { - if(this.numberInterfaceType) { - leftScope = this.numberInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if(leftType == this.booleanType) { - if(this.booleanInterfaceType) { - leftScope = this.booleanInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if((leftType.call || leftType.construct) && leftType.members == null) { - if(this.functionInterfaceType) { - leftScope = this.functionInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if(leftType.elementType) { - if(this.arrayInterfaceType) { - var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); - leftScope = arrInstType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - leftScope = leftType.memberScope; - } - } - } - } - } - } - } - if(leftScope == null) { - this.checker.errorReporter.expectedClassOrInterface(binex); - binex.type = this.anyType; - } else { - var propertyName = binex.operand2; - var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; - var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); - if(!symbol) { - if(this.objectInterfaceType && leftType) { - if(leftType.isReferenceType()) { - symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - if(!symbol) { - if(this.functionInterfaceType && (leftType.call || leftType.construct)) { - symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - } - } - } - if(!symbol || (!symbol.visible(leftScope, this.checker))) { - binex.type = this.anyType; - if(symbol == null) { - this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); - } else { - if(!this.inTypeRefTypeCheck) { - this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); - } - } - } else { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - this.inScopeTypeCheckDecl(infSym.declAST); - } - } - } - propertyName.sym = symbol; - binex.type = symbol.getType(); - } - } - if(binex.type == null) { - binex.type = this.anyType; - } - return binex; - }; - TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckAsgOperator = function (ast) { - var binex = ast; - var applyTargetType = !binex.operand2.isParenthesized; - binex.operand1 = this.typeCheck(binex.operand1); - this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(!(this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(binex.operand1.nodeType == TypeScript.NodeType.Call) { - var callEx = binex.operand1; - } - var preserveScope = false; - var preservedContainedScope = null; - if(binex.operand2.type) { - preservedContainedScope = binex.operand2.type.containedScope; - preserveScope = true; - } - binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && binex.operand2.type.containedScope == null) { - binex.operand2.type.containedScope = preservedContainedScope; - } - binex.type = rightType; - return binex; - }; - TypeFlow.prototype.typeCheckIndex = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!this.checker.styleSettings.literalSubscript) { - if(binex.operand2.nodeType == TypeScript.NodeType.QString) { - this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); - } - } - var objExprType = binex.operand1.type; - var indexExprType = binex.operand2.type; - if(objExprType.elementType) { - if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { - binex.type = objExprType.elementType; - } else { - if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } - } else { - if(objExprType.index) { - if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - var sig = this.resolveOverload(ast, objExprType.index); - if(sig) { - binex.type = sig.returnType.type; - } else { - binex.type = this.checker.anyType; - } - } else { - if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } - } else { - if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } - } - return binex; - }; - TypeFlow.prototype.typeCheckInOperator = function (binex) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { - this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckShift = function (binex, assignment) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); - binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); - if(assignment && (!(this.astIsWriteable(binex.operand1)))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - binex.type = this.doubleType; - return binex; - }; - TypeFlow.prototype.typeCheckQMark = function (trinex) { - trinex.operand1 = this.typeCheck(trinex.operand1); - trinex.operand2 = this.typeCheck(trinex.operand2); - trinex.operand3 = this.typeCheck(trinex.operand3); - var leftType = trinex.operand2.type; - var rightType = trinex.operand3.type; - if(leftType == rightType) { - trinex.type = leftType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - trinex.type = rightType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - trinex.type = leftType; - } else { - trinex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); - } - } - } - return trinex; - }; - TypeFlow.prototype.addFormals = function (container, signature, table) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var symbol = signature.parameters[i]; - symbol.container = container; - table.add(symbol.name, symbol); - } - }; - TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { - var len = vars.members.length; - var hasArgsDef = false; - for(var i = 0; i < len; i++) { - var local = vars.members[i]; - if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = null; - if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { - local.varFlags |= TypeScript.VarFlags.LocalStatic; - varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); - } else { - varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - } - varSym.transferVarFlags(local.varFlags); - localVar.symbol = varSym; - varSym.declAST = local; - localVar.typeLink.ast = local.typeExpr; - this.checker.resolveTypeLink(scope, localVar.typeLink, false); - if((local.type == null) && (local.init == null)) { - local.type = this.anyType; - } - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - if(local.id.text == "arguments") { - hasArgsDef = true; - } - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - if(!isModContainer) { - if(!hasArgsDef) { - var argLoc = new TypeScript.ValueLocation(); - argLoc.typeLink = new TypeScript.TypeLink(); - var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); - if(!this.iargumentsInterfaceType) { - var argumentsSym = scope.find("IArguments", false, true); - if(argumentsSym) { - argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; - this.iargumentsInterfaceType = argumentsSym.getType(); - } else { - this.iargumentsInterfaceType = this.anyType; - } - } - argLoc.typeLink.type = this.iargumentsInterfaceType; - table.add("arguments", theArgSym); - } - } - }; - TypeFlow.prototype.addConstructorLocalArgs = function (container, args, table, isClass) { - if(args) { - var len = args.members.length; - for(var i = 0; i < len; i++) { - var local = args.members[i]; - if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - this.resolveBoundDecl(local); - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - varSym.declAST = local; - localVar.symbol = varSym; - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - } - }; - TypeFlow.prototype.checkInitSelf = function (funcDecl) { - if(!funcDecl.isMethod()) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if(sym.isInstanceProperty()) { - return true; - } - } - } - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - for(var j = 0; j < fnsLen; j++) { - var fn = fns.members[j]; - if(this.checkInitSelf(fn)) { - return true; - } - } - return false; - }; - TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { - TypeScript.instanceFilter.reset(); - if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); - } - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); - } - } - }; - TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { - var allReturnsAreVoid = true; - if(funcDecl.signature.returnType.type == null) { - var preFindReturnExpressionTypes = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: { - go = false; - break; - - } - case TypeScript.NodeType.Return: { - var returnStmt = ast; - if(returnStmt.returnExpression) { - allReturnsAreVoid = false; - go = false; - } - - } - default: { - break; - - } - } - walker.options.goChildren = go; - walker.options.goNextSibling = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); - } - return allReturnsAreVoid; - }; - TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { - var foundSuper = false; - var preFindSuperCall = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: { - go = false; - break; - - } - case TypeScript.NodeType.Call: { - var call = ast; - if(call.target.nodeType == TypeScript.NodeType.Super) { - go = false; - foundSuper = true; - break; - } - break; - - } - default: { - break; - - } - } - walker.options.goChildren = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); - return foundSuper; - }; - TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { - var baseSymbol = bases.members[i].type.symbol; - var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var baseListTypeString = extendsList ? "extends" : "implements"; - var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module "; - baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; - } else { - baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; - } - this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); - }; - TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { - var _this = this; - if(bases) { - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { - continue; - } - this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { - return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); - }); - } - } - }; - TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { - var externalModuleSymbol = null; - var declSymbolPath = null; - if(typeSymbol.isExternallyVisible(this.checker)) { - var typeSymbolPath = typeSymbol.pathToRoot(); - declSymbolPath = declSymbol.pathToRoot(); - var typeSymbolLength = typeSymbolPath.length; - var declSymbolPathLength = declSymbolPath.length; - if(typeSymbolLength > 0) { - if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; - } else { - if(typeSymbolLength > 1) { - if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; - } - } - } - } - if(externalModuleSymbol == null) { - return; - } - } - var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); - if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { - return; - } - var checkVisibilitySymbol = declSymbol; - var varDecl = declSymbol.getVarDeclFromSymbol(); - if(varDecl) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { - return; - } else { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - checkVisibilitySymbol = declSymbol.container; - } - } - } - if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { - var privateSymbolName = typeSymbol.name; - if(externalModuleSymbol != null) { - var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); - if(prettyName != null) { - this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); - return; - } else { - privateSymbolName = externalModuleSymbol.prettyName; - } - } - errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); - } - }; - TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { - var _this = this; - if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { - return; - } - if(type.isArray()) { - return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); - } - if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { - return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); - } - if(type.members) { - type.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); - } - }, null); - } - this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); - }; - TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { - if(sgroup) { - var len = sgroup.signatures.length; - for(var i = 0; i < sgroup.signatures.length; i++) { - var signature = sgroup.signatures[i]; - if(len > 1 && signature == sgroup.definitionSignature) { - continue; - } - if(signature.returnType) { - this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - var param = signature.parameters[j]; - this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); - } - } - } - }; - TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(funcDecl.isConstructor) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(isSetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(!isGetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); - } - } - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(!funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); - } - } - } - } - }; - TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(isGetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); - } else { - if(!isSetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); - } - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); - } else { - if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); - } else { - if(funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); - } else { - this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); - } - } - } - } - }; - TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { - var reportOnFuncDecl = false; - if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); - } - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); - } else { - reportOnFuncDecl = true; - } - } - if(reportOnFuncDecl) { - this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); - } - }; - TypeFlow.prototype.typeCheckFunction = function (funcDecl) { - var _this = this; - this.nestingLevel = 0; - var fnType = funcDecl.type; - var fgSym = fnType.symbol; - var signature = funcDecl.signature; - if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { - return funcDecl; - } else { - if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { - signature.returnType.type = this.voidType; - return funcDecl; - } else { - if(funcDecl.returnTypeAnnotation == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - } - return funcDecl; - } - } - } - signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(signature); - var prevScope = this.scope; - var prevFnc = this.thisFnc; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevClassNode = this.thisClassNode; - this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; - this.thisFnc = funcDecl; - var container = funcDecl.type.symbol; - var prevThisType = this.thisType; - var prevLocationInfo = this.checker.locationInfo; - var funcTable = null; - var acceptedContextualType = false; - var targetParams = null; - var targetReturnType = null; - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; - var prevModDecl = this.checker.currentModDecl; - if(funcDecl.isConstructor && !funcDecl.isOverload) { - if(fnType.instanceType == null) { - this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); - return funcDecl; - } - this.scope = fnType.instanceType.constructorScope; - var ssb = this.scope; - funcTable = ssb.valueMembers.allMembers; - } else { - if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { - funcTable = funcDecl.symbols; - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { - this.scope = fnType.containedScope; - } - } else { - if(funcDecl.bod) { - this.scope = fnType.containedScope; - } - var ssb = this.scope; - if(ssb && ssb.valueMembers) { - funcTable = ssb.valueMembers.allMembers; - } - } - } - if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); - var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); - } else { - if(hasBaseType) { - if(superCallMustBeFirst) { - if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { - this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); - } - } else { - if(!this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); - } - } - } - } - } - if(funcDecl.isMethod() && funcDecl.type.enclosingType) { - var enclosingClassNode = null; - if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; - } else { - if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { - enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; - } - } - if(enclosingClassNode) { - this.thisClassNode = enclosingClassNode; - } - } - if(fnType.enclosingType) { - ; ; - var enclosingSym = fnType.symbol.container; - if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { - enclosingSym = enclosingSym.container; - } - if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { - this.checker.currentModDecl = enclosingSym.declAST; - } - } - if(funcDecl.unitIndex > 0) { - if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - } - if(fnType.enclosingType) { - this.thisType = fnType.enclosingType; - } else { - this.thisType = prevThisType; - } - var paramLen = signature.parameters.length; - if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { - var tmpParamScope = this.scope; - var ssb = this.scope; - if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { - if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { - var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); - if(considerSym && considerSym.declAST && considerSym.declAST.type) { - this.checker.setContextualType(considerSym.declAST.type, false); - } - } - if(this.checker.hasTargetType()) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var candidateType = candidateTypeContext.contextualType; - if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - candidateTypeContext.targetSig = candidateSigs.signatures[0]; - var candidateParams = candidateTypeContext.targetSig.parameters; - targetParams = candidateParams; - targetReturnType = candidateTypeContext.targetSig.returnType.type; - if(candidateTypeContext.targetSig.declAST) { - if(candidateTypeContext.targetSig.declAST.isConstructor) { - funcDecl.isTargetTypedAsMethod = true; - } else { - if(candidateTypeContext.targetSig.declAST.isMethod()) { - funcDecl.isTargetTypedAsMethod = true; - } - } - } - fgSym.type = candidateTypeContext.contextualType; - acceptedContextualType = true; - } else { - if(candidateType && funcDecl.isAccessor()) { - accessorType = candidateType; - candidateTypeContext.targetAccessorType = accessorType; - } else { - this.checker.killCurrentContextualType(); - } - } - } - } - var paramTable = ssb.valueMembers; - this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); - for(var p = 0; p < paramLen; p++) { - var symbol = signature.parameters[p]; - var ast = symbol.declAST; - if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; - ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); - ast.sym.setType(ast.type); - (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else { - this.typeCheck(ast); - } - if(isSetter && accessorType) { - ast = this.cast(ast, accessorType); - } - symbol.container = container; - this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); - }); - paramTable.publicMembers.add(symbol.name, symbol); - } - this.scope = tmpParamScope; - } else { - this.typeCheck(funcDecl.arguments); - for(var p = 0; p < paramLen; p++) { - signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; - this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); - }); - if((funcDecl.arguments.members[p]).parameterPropertySym) { - (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); - } - } - if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { - if(!paramLen || paramLen > 1) { - this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); - } else { - if(funcDecl.arguments.members[0].type == this.checker.numberType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; - } else { - if(funcDecl.arguments.members[0].type == this.checker.stringType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; - } else { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); - } - } - } - } - } - if(funcDecl.bod && (!funcDecl.isSignature())) { - if(!(funcDecl.isConstructor)) { - this.addFormals(container, signature, funcTable); - } else { - this.addConstructorLocalArgs(funcDecl.type.symbol, funcDecl.arguments, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); - if(this.thisClassNode && this.thisClassNode.extendsList) { - var tmpScope = this.scope; - var funcMembers = new TypeScript.ScopedMembers(funcTable); - this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { - return sym.kind() == TypeScript.SymbolKind.Parameter; - }); - this.typeCheckBaseCalls(this.thisClassNode.extendsList); - this.scope = tmpScope; - } - } - var prevMod = this.checker.currentModDecl; - if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { - this.checker.currentModDecl = funcDecl.type.symbol.declModule; - } - if(acceptedContextualType) { - this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); - } - this.typeCheck(funcDecl.bod); - if(acceptedContextualType) { - this.checker.unsetContextualType(); - } - this.checker.currentModDecl = prevMod; - if(this.checker.checkControlFlow) { - var cfg = funcDecl.buildControlFlow(); - if(this.checker.printControlFlowGraph) { - cfg.print(this.checker.errorReporter.outfile); - } - cfg.reportUnreachable(this.checker.errorReporter); - if(this.checker.checkControlFlowUseDef) { - cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); - } - } - if(funcDecl.isConstructor) { - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - var freeVars; - var sym; - var j = 0; - for(; j < fnsLen; j++) { - var fn = fns.members[j]; - if(!fn.isSignature()) { - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { - this.checkPromoteFreeVars(fn, funcDecl.type.symbol); - } - } - } - } - } - this.scope = prevScope; - this.thisFnc = prevFnc; - this.thisClassNode = prevClassNode; - this.enclosingFncIsMethod = prevMethodStatus; - this.thisType = prevThisType; - this.checker.locationInfo = prevLocationInfo; - this.checker.currentModDecl = prevModDecl; - signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - if(funcDecl.returnTypeAnnotation) { - this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); - if(signature.returnType.type == null) { - this.checker.resolveTypeLink(this.scope, signature.returnType, false); - } - } else { - if(targetReturnType) { - signature.returnType.type = targetReturnType; - } - } - if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { - var collection = { - getLength: function () { - return funcDecl.returnStatementsWithExpressions.length; - }, - setTypeAtIndex: function (index, type) { - funcDecl.returnStatementsWithExpressions[index].type = type; - }, - getTypeAtIndex: function (index) { - return funcDecl.returnStatementsWithExpressions[index].type; - } - }; - var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; - bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); - if(bestCommonReturnType) { - signature.returnType.type = this.checker.widenType(bestCommonReturnType); - } else { - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); - } - signature.returnType.type = this.anyType; - } - } - var onlyHasThrow = false; - if(signature.returnType.type == null) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - } else { - signature.returnType.type = this.voidType; - } - } else { - if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { - signature.returnType.type = this.anyType; - } else { - if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { - if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); - if(!onlyHasThrow) { - this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); - } - } - this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { - return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); - }); - } - } - } - if(funcDecl.accessorSymbol) { - var accessorType = funcDecl.accessorSymbol.getType(); - if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); - } - if(accessorType) { - if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { - this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); - } - } else { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - funcDecl.accessorSymbol.setType(signature.returnType.type); - } else { - if(funcDecl.arguments.members.length != 1) { - this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); - } else { - funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); - } - } - } - } - this.typeCheckOverloadSignatures(fnType, funcDecl); - return funcDecl; - }; - TypeFlow.prototype.typeCheckBases = function (type) { - var seenInterface = false; - var bases = type.extendsList; - var baseLinks = type.extendsTypeLinks; - if(bases) { - var len = bases.length; - if(len > 0) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseType; - } - for(var i = 0; i < len; i++) { - if(bases[i] == this.checker.anyType) { - baseLinks[i].type = null; - var oldErrors = this.checker.errorReporter.getCapturedErrors(); - TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); - this.checker.errorReporter.pushToErrorSink = true; - bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); - this.checker.errorReporter.pushToErrorSink = false; - this.checker.errorReporter.freeCapturedErrors(); - } - var base = bases[i]; - var baseRef = baseLinks[i].ast; - var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; - if(baseTypeOfObject) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; - } - if(base.isClassInstance()) { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - if(seenInterface) { - this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); - } - } - } else { - if(base.isModuleType()) { - this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); - } else { - if(base.members) { - if(!seenInterface) { - seenInterface = true; - } - } else { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); - } - break; - } - } - } - } - } - }; - TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { - var instanceType = implementingType.getInstanceType(); - if(instanceType.implementsList) { - var len = instanceType.implementsList.length; - for(var i = 0; i < len; i++) { - var interfaceType = instanceType.implementsList[i]; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { - var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); - } else { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); - } - } - } - } - }; - TypeFlow.prototype.typeCheckBaseCalls = function (bases) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.typeCheckNew(baseExpr); - } - } - }; - TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { - var _this = this; - if(type) { - if(type.members) { - type.members.publicMembers.map(function (key, s, c) { - var sym = s; - var dup = names.lookup(sym.name); - if(dup) { - if(checkUnique) { - _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); - } - } else { - names.add(sym.name, sym); - } - }, null); - } - if(type.extendsList) { - var len = type.extendsList.length; - for(var i = 0; i < len; i++) { - if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { - this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); - } - } - } - } - }; - TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { - var _this = this; - var instanceType = derivedType.getInstanceType(); - if(instanceType.extendsList == null) { - return; - } - var len = instanceType.extendsList.length; - if(len > 0) { - var names = new TypeScript.StringHashTable(); - if(instanceType.isClassInstance()) { - for(var i = 0; i < len; i++) { - this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); - } - } - if(instanceType.members) { - instanceType.members.publicMembers.map(function (key, s, c) { - var sym = s; - for(var j = 0; j < len; j++) { - var base = instanceType.extendsList[j]; - if(base.memberScope == null) { - _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); - } else { - var bSym = base.memberScope.find(sym.name, false, false); - if(bSym) { - var aType = sym.getType(); - var bType = bSym.getType(); - if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); - } else { - if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); - } - } - } - } - } - }, null); - } - } - }; - TypeFlow.prototype.typeCheckClass = function (classDecl) { - var typeSymbol = classDecl.type.symbol; - if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { - return classDecl; - } else { - if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - return classDecl; - } else { - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(typeSymbol); - } - } - var prevScope = this.scope; - var svClassNode = this.thisClassNode; - this.thisClassNode = classDecl; - var classType = classDecl.type; - this.typeCheckBases(classType.instanceType); - this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); - this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); - var prevThisType = this.thisType; - this.thisType = classType.instanceType; - this.scope = classType.instanceType.containedScope; - if(classDecl.constructorDecl) { - this.scope = classType.instanceType.constructorScope; - var ssb = this.scope; - var funcTable = ssb.valueMembers.allMembers; - this.addConstructorLocalArgs(classDecl.constructorDecl.type.symbol, classDecl.constructorDecl.arguments, funcTable, true); - } - this.typeCheck(classDecl.members); - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - this.checkBaseTypeMemberInheritance(classType, classDecl); - this.checkMembersImplementInterfaces(classType); - this.typeCheckOverloadSignatures(classType, classDecl); - this.typeCheckOverloadSignatures(classType.instanceType, classDecl); - if(!classDecl.constructorDecl) { - if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { - TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); - } - } - this.thisType = prevThisType; - this.thisClassNode = svClassNode; - this.scope = prevScope; - return classDecl; - }; - TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { - if(type.call) { - type.call.typeCheck(this.checker, ast, type.construct != null); - } - if(type.construct) { - type.construct.typeCheck(this.checker, ast, false); - } - if(type.index) { - type.index.typeCheck(this.checker, ast, false); - } - }; - TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { - this.typeCheckBases(interfaceDecl.type); - this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); - this.typeCheck(interfaceDecl.members); - this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); - if(interfaceDecl.extendsList) { - for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { - if(interfaceDecl.extendsList.members[i].type.call) { - if(interfaceDecl.type.call) { - interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); - } else { - interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; - } - } - if(interfaceDecl.extendsList.members[i].type.construct) { - if(interfaceDecl.type.construct) { - interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); - } else { - interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; - } - } - if(interfaceDecl.extendsList.members[i].type.index) { - if(interfaceDecl.type.index) { - interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); - } else { - interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; - } - } - } - } - return interfaceDecl; - }; - TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { - var mod = importDecl.alias.type; - var sym = null; - var prevInImportTC = this.inImportTypeCheck; - this.inImportTypeCheck = true; - this.typeCheck(importDecl.alias); - mod = importDecl.alias.type; - if(mod == null) { - this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); - mod = this.checker.anyType; - (importDecl.id.sym).type = mod; - } - importDecl.id.type = mod; - sym = mod.symbol; - if(!mod.isModuleType()) { - this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); - } else { - sym.type = mod; - if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { - this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); - } - (importDecl.id.sym).type = mod; - if(mod.symbol && mod.symbol.declAST) { - (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - } - } - this.inImportTypeCheck = prevInImportTC; - return importDecl; - }; - TypeFlow.prototype.typeCheckModule = function (moduleDecl) { - if(!moduleDecl.mod) { - return moduleDecl; - } - if(this.currentScript) { - this.currentScript.requiresGlobal = true; - } - var mod = moduleDecl.mod; - var sym = null; - var prevScope = this.scope; - var prevThisType = this.thisType; - var prevCurrentModDecl = this.checker.currentModDecl; - this.checker.currentModDecl = moduleDecl; - this.thisType = null; - this.scope = mod.containedScope; - this.typeCheck(moduleDecl.members); - sym = mod.symbol; - this.checker.currentModDecl = prevCurrentModDecl; - this.thisType = prevThisType; - this.scope = prevScope; - moduleDecl.type = mod; - if(sym) { - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - } - return moduleDecl; - }; - TypeFlow.prototype.typeCheckFor = function (forStmt) { - forStmt.init = this.typeCheck(forStmt.init); - this.nestingLevel++; - forStmt.cond = this.typeCheck(forStmt.cond); - this.typeCheckCondExpr(forStmt.cond); - forStmt.incr = this.typeCheck(forStmt.incr); - this.nestingLevel--; - forStmt.body = this.typeCheck(forStmt.body); - this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); - forStmt.type = this.voidType; - return forStmt; - }; - TypeFlow.prototype.typeCheckWith = function (withStmt) { - if(this.checker.errorsOnWith) { - this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); - } - withStmt.expr = this.typeCheck(withStmt.expr); - this.checker.inWith = true; - withStmt.body = this.typeCheck(withStmt.body); - this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); - this.checker.inWith = false; - return withStmt; - }; - TypeFlow.prototype.typeCheckForIn = function (forInStmt) { - forInStmt.obj = this.typeCheck(forInStmt.obj); - forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); - if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = forInStmt.lval; - if(varDecl.typeExpr) { - this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); - } - if(varDecl.sym) { - varDecl.sym.setType(this.checker.stringType); - } - } - forInStmt.body = this.typeCheck(forInStmt.body); - this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); - return forInStmt; - }; - TypeFlow.prototype.typeCheckWhile = function (whileStmt) { - whileStmt.cond = this.typeCheck(whileStmt.cond); - this.typeCheckCondExpr(whileStmt.cond); - whileStmt.body = this.typeCheck(whileStmt.body); - this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); - whileStmt.type = this.voidType; - return whileStmt; - }; - TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { - doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); - this.typeCheckCondExpr(doWhileStmt.cond); - doWhileStmt.body = this.typeCheck(doWhileStmt.body); - this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); - doWhileStmt.type = this.voidType; - return doWhileStmt; - }; - TypeFlow.prototype.typeCheckCondExpr = function (cond) { - if(this.checker.styleSettings.assignmentInCond) { - if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { - this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); - } - } - }; - TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { - if(this.checker.styleSettings.blockInCompoundStmt && stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); - } - } - }; - TypeFlow.prototype.typeCheckIf = function (ifStmt) { - ifStmt.cond = this.typeCheck(ifStmt.cond); - this.typeCheckCondExpr(ifStmt.cond); - ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); - ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); - this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); - this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); - ifStmt.type = this.voidType; - return ifStmt; - }; - TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { - if(!funcDecl.isAccessor()) { - return null; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - return funcDecl.type.call.signatures[0].returnType.type; - } else { - return funcDecl.type.call.signatures[0].parameters[0].getType(); - } - }; - TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { - var resultType = new TypeScript.Type(); - resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); - resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); - var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); - aggScope.addParentScope(resultType.memberScope); - aggScope.addParentScope(this.scope); - resultType.containedScope = aggScope; - var memberDecls = objectLit.operand; - var prevThisType = this.thisType; - var acceptTargetType = false; - var targetType = null; - if(this.checker.hasTargetType()) { - targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { - if(targetType.symbol.declAST) { - this.typeCheck(targetType.symbol.declAST); - } - } - acceptTargetType = true; - } - if(memberDecls) { - for(var i = 0, len = memberDecls.members.length; i < len; i++) { - var binex = memberDecls.members[i]; - var id = binex.operand1; - var text; - var targetMember = null; - var fieldSymbol = null; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else { - if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); - resultType = this.anyType; - break; - } - } - if(acceptTargetType && targetType.memberScope) { - targetMember = targetType.memberScope.find(text, false, false); - } - if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { - var funcDecl = binex.operand2; - var accessorSym = resultType.members.publicMembers.lookup(text); - accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); - funcDecl.accessorSymbol = accessorSym; - fieldSymbol = accessorSym; - if(id.nodeType == TypeScript.NodeType.Name) { - (id).sym = accessorSym; - } - } - this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); - if(acceptTargetType && targetMember) { - if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { - binex.operand1.type = targetMember.getType(); - } - } else { - binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; - } - if(fieldSymbol == null) { - var memberType = binex.operand2.type; - var field = new TypeScript.ValueLocation(); - fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= TypeScript.SymbolFlags.Property; - field.symbol = fieldSymbol; - fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.type = memberType; - resultType.members.publicMembers.add(text, fieldSymbol); - } - fieldSymbol.isObjectLitField = true; - } - } - this.thisType = prevThisType; - objectLit.type = resultType; - if(targetType) { - objectLit.targetType = targetType; - } - }; - TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { - var elements = arrayLit.operand; - var elementType = this.anyType; - var targetElementType = null; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - comparisonInfo.onlyCaptureFirstError = true; - if(this.checker.hasTargetType()) { - var targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType.elementType) { - targetElementType = targetType.elementType; - } - } - if(elements) { - var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; - this.inArrayElementTypeCheck = true; - this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); - this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; - elementType = elements.members[0].type; - var collection = { - getLength: function () { - return elements.members.length; - }, - setTypeAtIndex: function (index, type) { - elements.members[index].type = type; - }, - getTypeAtIndex: function (index) { - return elements.members[index].type; - } - }; - elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); - if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { - elementType = this.anyType; - } - } - if(!elementType) { - var emsg = "Incompatible types in array literal expression"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleError(arrayLit, emsg); - } else { - this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); - } - elementType = this.anyType; - } else { - if(targetElementType) { - if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { - elementType = targetElementType; - } - } - } - arrayLit.type = this.checker.makeArrayType(elementType); - }; - TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { - if(type && type.construct && type.construct.signatures.length > 0) { - for(var i = 0; i < type.construct.signatures.length; i++) { - if(type.construct.signatures[i].returnType.type == this.checker.voidType) { - this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); - break; - } - } - } - }; - TypeFlow.prototype.typeCheckReturn = function (returnStmt) { - if(this.thisFnc) { - var targetType = null; - if(this.checker.hasTargetType()) { - var tcContext = this.checker.getTargetTypeContext(); - var accessorType = tcContext.targetAccessorType; - if(accessorType) { - targetType = accessorType; - } else { - var targetSig = this.checker.getTargetTypeContext().targetSig; - if(targetSig && targetSig.returnType.type != this.voidType) { - targetType = targetSig.returnType.type; - } - } - } - if(returnStmt.returnExpression) { - this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; - if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { - targetType = this.thisFnc.returnTypeAnnotation.type; - } - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); - var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; - if(expectedReturnType) { - if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { - this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); - returnStmt.type = returnStmt.returnExpression.type; - } else { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); - returnStmt.type = expectedReturnType; - } - } else { - if(targetType) { - if(returnStmt.returnExpression.type != this.voidType) { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); - } else { - returnStmt.returnExpression.type = targetType; - } - } - returnStmt.type = returnStmt.returnExpression.type; - } - this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; - } else { - returnStmt.type = targetType == null ? this.checker.voidType : targetType; - } - } - return returnStmt; - }; - TypeFlow.prototype.typeCheckInstOf = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { - this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckCommaOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.typeCheckLogOr = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else { - if(leftType == this.checker.booleanType) { - if(rightType == this.checker.booleanType) { - binex.type = this.checker.booleanType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(leftType == this.checker.numberType) { - if(rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(leftType == this.checker.stringType) { - if(rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - binex.type = rightType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - binex.type = leftType; - } else { - binex.type = this.checker.anyType; - } - } - } - } - } - } - return binex; - }; - TypeFlow.prototype.typeCheckLogAnd = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { - var lowerBound = signature.nonOptionalParameterCount; - var upperBound = signature.parameters.length; - var formalLen = lowerBound; - var acceptable = false; - if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { - formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); - acceptable = true; - } - var repeatType = null; - if(acceptable || signature.hasVariableArgList) { - if(signature.hasVariableArgList) { - formalLen -= 1; - repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; - repeatType = repeatType.elementType; - acceptable = actuals.length >= formalLen; - } - var len = actuals.length; - var exact = acceptable; - var convert = acceptable; - for(var i = 0; i < len; i++) { - var typeA; - if(i < formalLen) { - typeA = (signature.parameters[i]).parameter.typeLink.type; - } else { - typeA = repeatType; - } - var typeB = actuals[i]; - if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { - exact = false; - } - if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { - convert = false; - } - if(!(exact || convert)) { - break; - } - } - if(exact) { - exactCandidates[exactCandidates.length] = signature; - } else { - if(convert && (exactCandidates.length == 0)) { - conversionCandidates[conversionCandidates.length] = signature; - } - } - } - }; - TypeFlow.prototype.resolveOverload = function (application, group) { - var rd = this.resolutionDataCache.getResolutionData(); - var actuals = rd.actuals; - var exactCandidates = rd.exactCandidates; - var conversionCandidates = rd.conversionCandidates; - var candidate = null; - var hasOverloads = group.signatures.length > 1; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - var args = null; - var target = null; - if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { - var callEx = application; - args = callEx.arguments; - target = callEx.target; - if(callEx.arguments) { - var len = callEx.arguments.members.length; - for(var i = 0; i < len; i++) { - actuals[i] = callEx.arguments.members[i].type; - } - } - } else { - if(application.nodeType == TypeScript.NodeType.Index) { - var binExp = application; - target = binExp.operand1; - args = new TypeScript.ASTList(); - args.members[0] = binExp.operand2; - actuals[0] = binExp.operand2.type; - } - } - for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { - var signature = group.signatures[j]; - if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { - continue; - } - if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { - this.typeCheckFunction(signature.declAST); - } - this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); - } - if(exactCandidates.length == 0) { - var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); - if(applicableCandidates.length > 0) { - var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - var emsg = "Supplied parameters do not match any signature of call target"; - if(comparisonInfo.message) { - this.checker.errorReporter.simpleError(target, emsg + ":\n\t" + comparisonInfo.message); - } else { - this.checker.errorReporter.simpleError(target, emsg); - } - } - } else { - if(exactCandidates.length > 1) { - var applicableSigs = []; - for(var i = 0; i < exactCandidates.length; i++) { - applicableSigs[i] = { - signature: exactCandidates[i], - hadProvisionalErrors: false - }; - } - var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - candidate = exactCandidates[0]; - } - } - this.resolutionDataCache.returnResolutionData(rd); - return candidate; - }; - TypeFlow.prototype.typeCheckNew = function (ast) { - var callEx = ast; - callEx.target = this.typeCheck(callEx.target); - var target = callEx.target; - if(target.type.construct || target.type.call) { - this.preTypeCheckCallArgs(callEx.arguments); - } else { - callEx.arguments = this.typeCheck(callEx.arguments); - } - if(target.type == this.anyType) { - callEx.type = this.anyType; - callEx.arguments = this.typeCheck(callEx.arguments); - } else { - if(target.type.construct) { - var signature = this.resolveOverload(callEx, target.type.construct); - if(signature == null) { - callEx.type = this.anyType; - } else { - if(signature.returnType.type == this.voidType) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } - } else { - if(target.type.call) { - var signature = this.resolveOverload(callEx, target.type.call); - if(signature == null) { - callEx.type = this.anyType; - } else { - if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); - } - } - } else { - if(target.type.elementType) { - callEx.type = target.type; - } else { - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - callEx.type = this.anyType; - } - } - } - } - this.postTypeCheckCallArgs(callEx); - return callEx; - }; - TypeFlow.prototype.preTypeCheckCallArgs = function (args) { - if(!args) { - return; - } - for(var i = 0; i < args.members.length; i++) { - switch(args.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - continue; - - } - default: { - this.typeCheck(args.members[i]); - break; - - } - } - } - }; - TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { - var acceptedTargetType = false; - var i = 0; - if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { - var sig = callEx.signature; - if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { - acceptedTargetType = true; - var targetType = null; - var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; - var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; - for(i = 0; i < nonVarArgActualParamLength; i++) { - targetType = sig.parameters[i].getType(); - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); - break; - - } - } - } - if(sig.hasVariableArgList) { - var varArgParamIndex = sig.nonOptionalParameterCount - 1; - targetType = sig.parameters[varArgParamIndex].getType(); - if(targetType) { - targetType = targetType.elementType; - } - var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; - for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); - break; - - } - } - } - } - } - } - if(!acceptedTargetType && callEx.arguments) { - this.checker.killCurrentContextualType(); - for(i = 0; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - this.typeCheck(callEx.arguments.members[i]); - break; - - } - default: { - continue; - - } - } - } - } - }; - TypeFlow.prototype.typeCheckCall = function (ast) { - var callEx = ast; - if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { - this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); - } - } else { - if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { - if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { - this.checker.errorReporter.styleError(callEx, "eval not permitted"); - } - } - } - if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { - (callEx.target).isInlineCallLiteral = true; - } - var prevInSuperCall = this.inSuperCall; - if(callEx.target.nodeType == TypeScript.NodeType.Super) { - this.inSuperCall = true; - } - callEx.target = this.typeCheck(callEx.target); - this.preTypeCheckCallArgs(callEx.arguments); - var target = callEx.target; - if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { - callEx.type = this.anyType; - } else { - var fnType = target.type; - if(fnType.call) { - var signature = this.resolveOverload(callEx, fnType.call); - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - callEx.type = this.anyType; - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - } - } - } - this.postTypeCheckCallArgs(callEx); - this.inSuperCall = prevInSuperCall; - return callEx; - }; - TypeFlow.prototype.assignScopes = function (ast) { - var script = ast; - this.checker.locationInfo = script.locationInfo; - var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); - var context = new TypeScript.AssignScopeContext(globalChain, this, [ - this.checker.currentModDecl - ]); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); - }; - TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { - var enclosingScope = enclosingScopeContext.getScope(); - var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); - var scriptFragment = enclosingScopeContext.getScriptFragment(); - var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); - memContext.scope = enclosingScope; - if(scriptFragment.nodeType == TypeScript.NodeType.Name) { - return scriptFragment.type.getMemberScope(this); - } else { - TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); - if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(memContext.type) { - return memContext.type.getMemberScope(this); - } else { - return null; - } - } - }; - TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { - return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); - }; - TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { - var matchFlag = TypeScript.ASTFlags.DotLHS; - var pos = enclosingScopeContext.pos; - var astResult = null; - var preFindMemberScopeFullAst = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { - astResult = ast; - walker.options.stopWalk(); - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { - astResult = ast; - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); - if(astResult == null) { - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); - } - if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(astResult && astResult.type) { - return astResult.type.getMemberScope(this); - } else { - return null; - } - }; - return TypeFlow; - })(); - TypeScript.TypeFlow = TypeFlow; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (Primitive) { - Primitive._map = []; - Primitive.None = 0; - Primitive.Void = 1; - Primitive.Double = 2; - Primitive.String = 4; - Primitive.Boolean = 8; - Primitive.Any = 16; - Primitive.Null = 32; - Primitive.Undefined = 64; - })(TypeScript.Primitive || (TypeScript.Primitive = {})); - var Primitive = TypeScript.Primitive; - var MemberName = (function () { - function MemberName() { - this.prefix = ""; - this.suffix = ""; - } - MemberName.prototype.isString = function () { - return false; - }; - MemberName.prototype.isArray = function () { - return false; - }; - MemberName.prototype.toString = function () { - return MemberName.memberNameToString(this); - }; - MemberName.memberNameToString = function memberNameToString(memberName) { - var result = memberName.prefix; - if(memberName.isString()) { - result += (memberName).text; - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - result += MemberName.memberNameToString(ar.entries[index]); - result += ar.delim; - } - } - result += memberName.suffix; - return result; - } - MemberName.create = function create(arg1, arg2, arg3) { - if(typeof arg1 == "string") { - return new MemberNameString(arg1); - } else { - var result = new MemberNameArray(); - if(arg2) { - result.prefix = arg2; - } - if(arg3) { - result.suffix = arg3; - } - result.entries.push(arg1); - return result; - } - } - return MemberName; - })(); - TypeScript.MemberName = MemberName; - var MemberNameString = (function (_super) { - __extends(MemberNameString, _super); - function MemberNameString(text) { - _super.call(this); - this.text = text; - } - MemberNameString.prototype.isString = function () { - return true; - }; - return MemberNameString; - })(MemberName); - TypeScript.MemberNameString = MemberNameString; - var MemberNameArray = (function (_super) { - __extends(MemberNameArray, _super); - function MemberNameArray() { - _super.apply(this, arguments); - - this.delim = ""; - this.entries = []; - } - MemberNameArray.prototype.isArray = function () { - return true; - }; - MemberNameArray.prototype.add = function (entry) { - this.entries.push(entry); - }; - MemberNameArray.prototype.addAll = function (entries) { - for(var i = 0; i < entries.length; i++) { - this.entries.push(entries[i]); - } - }; - return MemberNameArray; - })(MemberName); - TypeScript.MemberNameArray = MemberNameArray; - var currentTypeID = -1; - var Type = (function () { - function Type() { - this.typeID = currentTypeID++; - this.construct = null; - this.call = null; - this.index = null; - this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.primitiveTypeClass = Primitive.None; - this.typeFlags = TypeScript.TypeFlags.None; - } - Type.prototype.baseClass = function () { - if(this.extendsList && (this.extendsList.length > 0)) { - return this.extendsList[0]; - } else { - return null; - } - }; - Type.prototype.getArrayBase = function (arrInstType, checker) { - return this.arrayCache.specialize(arrInstType, checker); - }; - Type.prototype.isClass = function () { - return this.instanceType != null; - }; - Type.prototype.isArray = function () { - return this.elementType != null; - }; - Type.prototype.isClassInstance = function () { - return this.symbol && !this.elementType && (this.symbol).type.isClass(); - }; - Type.prototype.getInstanceType = function () { - if(this.isClass()) { - return this.instanceType; - } else { - return this; - } - }; - Type.prototype.hasImplementation = function () { - return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); - }; - Type.prototype.setHasImplementation = function () { - this.typeFlags |= TypeScript.TypeFlags.HasImplementation; - }; - Type.prototype.isDouble = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); - }; - Type.prototype.isString = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); - }; - Type.prototype.isBoolean = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); - }; - Type.prototype.isNull = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); - }; - Type.prototype.getTypeName = function () { - return this.getMemberTypeName("", true, false, null); - }; - Type.prototype.getScopedTypeName = function (scope) { - return this.getMemberTypeName("", true, false, scope); - }; - Type.prototype.getScopedTypeNameEx = function (scope) { - return this.getMemberTypeNameEx("", true, false, scope); - }; - Type.prototype.callCount = function () { - var total = 0; - if(this.call) { - total += this.call.signatures.length; - } - if(this.construct) { - total += this.construct.signatures.length; - } - if(this.index) { - total += this.index.signatures.length; - } - return total; - }; - Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope) { - var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope); - return memberName.toString(); - }; - Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope) { - if(this.elementType) { - return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); - } else { - if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { - var tn = this.symbol.scopeRelativeName(scope); - return MemberName.create(tn == "null" ? "any" : tn); - } else { - if(this.members || this.call || this.construct) { - if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { - return MemberName.create("this"); - } - this.typeFlags |= TypeScript.TypeFlags.BuildingName; - var builder = ""; - var allMemberNames = new MemberNameArray(); - var curlies = isElementType || this.index != null; - var memCount = 0; - var delim = "; "; - if(this.members) { - this.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - var typeNameMember = sym.getTypeNameEx(scope); - if(typeNameMember.isArray() && (typeNameMember).delim == delim) { - allMemberNames.addAll((typeNameMember).entries); - } else { - allMemberNames.add(typeNameMember); - } - memCount++; - curlies = true; - } - }, null); - } - var signatureCount = this.callCount(); - var j; - var len = 0; - var shortform = !curlies && signatureCount == 1 && topLevel; - if(this.call) { - allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope)); - } - if(this.construct) { - allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); - } - if(this.index) { - allMemberNames.addAll(this.index.toStrings("", shortform, scope)); - } - if((curlies) || ((signatureCount > 1) && topLevel)) { - allMemberNames.prefix = "{ "; - allMemberNames.suffix = "}"; - allMemberNames.delim = delim; - } else { - if(allMemberNames.entries.length > 1) { - allMemberNames.delim = delim; - } - } - this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); - if((signatureCount == 0) && (memCount == 0)) { - return MemberName.create("{}"); - } else { - return allMemberNames; - } - } else { - return MemberName.create("{}"); - } - } - } - }; - Type.prototype.checkDecl = function (checker) { - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST) { - checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); - } - } - }; - Type.prototype.getMemberScope = function (flow) { - if(this == flow.anyType) { - return null; - } else { - if(this.isDouble()) { - if(flow.numberInterfaceType) { - return flow.numberInterfaceType.memberScope; - } else { - return null; - } - } else { - if(this.isBoolean()) { - if(flow.booleanInterfaceType) { - return flow.booleanInterfaceType.memberScope; - } else { - return null; - } - } else { - if(this == flow.stringType) { - if(flow.stringInterfaceType) { - return flow.stringInterfaceType.memberScope; - } else { - return null; - } - } else { - if(this.elementType) { - if(flow.arrayInterfaceType) { - var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); - return arrInstType.memberScope; - } else { - return null; - } - } else { - return this.memberScope; - } - } - } - } - } - }; - Type.prototype.isReferenceType = function () { - return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; - }; - Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { - if(pattern == this) { - return replacement; - } - var result = this; - if(membersOnly) { - if(this.isReferenceType()) { - result = new Type(); - if(this.members) { - result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.members.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPublicMember(bSym.name, bSym); - }, null); - this.members.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPrivateMember(bSym.name, bSym); - }, null); - } - if(this.ambientMembers) { - result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.ambientMembers.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPublicMember(bSym.name, bSym); - }, null); - this.ambientMembers.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPrivateMember(bSym.name, bSym); - }, null); - } - result.containedScope = checker.scopeOf(result); - result.memberScope = result.containedScope; - } - } else { - if(this.elementType) { - if(this.elementType == pattern) { - result = checker.makeArrayType(replacement); - } else { - if(this.elementType.elementType == pattern) { - result = checker.makeArrayType(checker.makeArrayType(replacement)); - } - } - } else { - if(this.call) { - result = new Type(); - result.call = this.call.specializeType(pattern, replacement, checker); - } - } - } - return result; - }; - Type.prototype.hasBase = function (baseType) { - if(baseType == this) { - return true; - } else { - if(this.extendsList) { - for(var i = 0, len = this.extendsList.length; i < len; i++) { - if(this.extendsList[i].hasBase(baseType)) { - return true; - } - } - } - } - return false; - }; - Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { - if((this == checker.anyType) || (b == checker.anyType)) { - return checker.anyType; - } else { - if(this == b) { - return this; - } else { - if((b == checker.nullType) && this != checker.nullType) { - return this; - } else { - if((this == checker.nullType) && (b != checker.nullType)) { - return b; - } else { - if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { - return this; - } else { - if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { - return b; - } else { - if((b == checker.undefinedType) && this != checker.undefinedType) { - return this; - } else { - if((this == checker.undefinedType) && (b != checker.undefinedType)) { - return b; - } else { - if(this.elementType && b.elementType) { - if(this.elementType == b.elementType) { - return this; - } else { - var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); - if(mergedET == null) { - return checker.makeArrayType(checker.anyType); - } else { - return checker.makeArrayType(mergedET); - } - } - } else { - if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { - return b; - } else { - if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { - return this; - } else { - return null; - } - } - } - } - } - } - } - } - } - } - } - }; - Type.prototype.isModuleType = function () { - return false; - }; - Type.prototype.hasMembers = function () { - return this.members != null; - }; - Type.prototype.getAllEnclosedTypes = function () { - return null; - }; - Type.prototype.getAllAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getPublicEnclosedTypes = function () { - return null; - }; - Type.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getDocComments = function () { - if(this.elementType || !this.symbol) { - return []; - } - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return (this.symbol.declAST).classDecl.getDocComments(); - } else { - return this.symbol.getDocComments(); - } - } - if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { - return this.symbol.getDocComments(); - } - return []; - }; - return Type; - })(); - TypeScript.Type = Type; - var ModuleType = (function (_super) { - __extends(ModuleType, _super); - function ModuleType(enclosedTypes, ambientEnclosedTypes) { - _super.call(this); - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.importedModules = []; - } - ModuleType.prototype.isModuleType = function () { - return true; - }; - ModuleType.prototype.hasMembers = function () { - return this.members != null || this.enclosedTypes != null; - }; - ModuleType.prototype.getAllEnclosedTypes = function () { - return this.enclosedTypes; - }; - ModuleType.prototype.getAllAmbientEnclosedTypes = function () { - return this.ambientEnclosedTypes; - }; - ModuleType.prototype.getPublicEnclosedTypes = function () { - return null; - }; - ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { - var moduleName = null; - members.map(function (key, s, c) { - if(moduleName == null && !TypeScript.isQuoted(key)) { - var symbol = s; - var type = symbol.getType(); - if(type == moduleType) { - moduleName = { - name: key, - symbol: symbol - }; - } - } - }, null); - return moduleName; - } - ModuleType.prototype.findDynamicModuleName = function (moduleType) { - var moduleName = null; - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); - if(moduleName == null) { - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); - } - return moduleName; - }; - return ModuleType; - })(Type); - TypeScript.ModuleType = ModuleType; - var TypeLink = (function () { - function TypeLink() { - this.type = null; - this.ast = null; - } - return TypeLink; - })(); - TypeScript.TypeLink = TypeLink; - function getTypeLink(ast, checker, autoVar) { - var result = new TypeLink(); - result.ast = ast; - if((ast == null) && (autoVar)) { - result.type = checker.anyType; - } else { - result.type = null; - } - return result; - } - TypeScript.getTypeLink = getTypeLink; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function stripQuotes(str) { - return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); - } - TypeScript.stripQuotes = stripQuotes; - function isQuoted(str) { - return str.indexOf("\"") != -1 || str.indexOf("'") != -1 || str.indexOf("'") != -1 || str.indexOf("\"") != -1; - } - TypeScript.isQuoted = isQuoted; - function quoteStr(str) { - return "\"" + str + "\""; - } - TypeScript.quoteStr = quoteStr; - function swapQuotes(str) { - if(str.indexOf("\"") != -1) { - str = str.replace("\"", "'"); - str = str.replace("\"", "'"); - } else { - str = str.replace("'", "\""); - str = str.replace("'", "\""); - } - return str; - } - TypeScript.swapQuotes = swapQuotes; - function switchToForwardSlashes(path) { - return path.replace(/\\/g, "/"); - } - TypeScript.switchToForwardSlashes = switchToForwardSlashes; - function trimModName(modName) { - if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { - return modName.substring(0, modName.length - 6); - } - if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { - return modName.substring(0, modName.length - 4); - } - if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { - return modName.substring(0, modName.length - 5); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { - return modName.substring(0, modName.length - 3); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { - return modName.substring(0, modName.length - 3); - } - return modName; - } - TypeScript.trimModName = trimModName; - function getDeclareFilePath(fname) { - return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); - } - TypeScript.getDeclareFilePath = getDeclareFilePath; - function isFileOfExtension(fname, ext) { - var invariantFname = fname.toLocaleUpperCase(); - var invariantExt = ext.toLocaleUpperCase(); - var extLength = invariantExt.length; - return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; - } - function isJSFile(fname) { - return isFileOfExtension(fname, ".js"); - } - TypeScript.isJSFile = isJSFile; - function isSTRFile(fname) { - return isFileOfExtension(fname, ".str"); - } - TypeScript.isSTRFile = isSTRFile; - function isTSFile(fname) { - return isFileOfExtension(fname, ".ts"); - } - TypeScript.isTSFile = isTSFile; - function isDSTRFile(fname) { - return isFileOfExtension(fname, ".d.str"); - } - TypeScript.isDSTRFile = isDSTRFile; - function isDTSFile(fname) { - return isFileOfExtension(fname, ".d.ts"); - } - TypeScript.isDTSFile = isDTSFile; - function getPrettyName(modPath, quote, treatAsFileName) { - if (typeof quote === "undefined") { quote = true; } - if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } - var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); - var components = this.getPathComponents(modName); - return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; - } - TypeScript.getPrettyName = getPrettyName; - function getPathComponents(path) { - return path.split("/"); - } - TypeScript.getPathComponents = getPathComponents; - function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { - absoluteModPath = switchToForwardSlashes(absoluteModPath); - var modComponents = this.getPathComponents(absoluteModPath); - var fixedModComponents = this.getPathComponents(fixedModFilePath); - var joinStartIndex = 0; - for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { - break; - } - } - if(joinStartIndex != 0) { - var relativePath = ""; - var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); - for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != "") { - relativePath = relativePath + "../"; - } - } - return relativePath + relativePathComponents.join("/"); - } - return absoluteModPath; - } - TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; - function quoteBaseName(modPath) { - var modName = trimModName(stripQuotes(modPath)); - var path = getRootFilePath(modName); - if(path == "") { - return modPath; - } else { - var components = modName.split(path); - var fileIndex = components.length > 1 ? 1 : 0; - return quoteStr(components[fileIndex]); - } - } - TypeScript.quoteBaseName = quoteBaseName; - function changePathToSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".str"; - } - TypeScript.changePathToSTR = changePathToSTR; - function changePathToDSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.str"; - } - TypeScript.changePathToDSTR = changePathToDSTR; - function changePathToTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".ts"; - } - TypeScript.changePathToTS = changePathToTS; - function changePathToDTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.ts"; - } - TypeScript.changePathToDTS = changePathToDTS; - function isRelative(path) { - return path.charAt(0) == "."; - } - TypeScript.isRelative = isRelative; - function isRooted(path) { - return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); - } - TypeScript.isRooted = isRooted; - function getRootFilePath(outFname) { - if(outFname == "") { - return outFname; - } else { - var isPath = outFname.indexOf("/") != -1; - return isPath ? filePath(outFname) : ""; - } - } - TypeScript.getRootFilePath = getRootFilePath; - function filePathComponents(fullPath) { - fullPath = switchToForwardSlashes(fullPath); - var components = getPathComponents(fullPath); - return components.slice(0, components.length - 1); - } - TypeScript.filePathComponents = filePathComponents; - function filePath(fullPath) { - var path = filePathComponents(fullPath); - return path.join("/") + "/"; - } - TypeScript.filePath = filePath; - function normalizeURL(url) { - var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; - var matches = hostDomainAndPortRegex.exec(url); - if(matches) { - var hostDomainAndPort = matches[1]; - var actualPath = matches[3]; - return hostDomainAndPort + normalizePath(actualPath); - } - return normalizePath(url); - } - TypeScript.normalizeURL = normalizeURL; - TypeScript.pathNormalizeRegExp = /\//g; - function normalizePath(path) { - path = switchToForwardSlashes(path); - var startedWithSep = path.charAt(0) === "/"; - var parts = this.getPathComponents(path); - for(var i = 0; i < parts.length; i++) { - if(parts[i] === "." || parts[i] === "") { - parts.splice(i, 1); - i--; - } - if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { - parts.splice(i - 1, 2); - i -= 2; - } - } - return (startedWithSep ? "/" : "") + parts.join("/"); - } - TypeScript.normalizePath = normalizePath; - function normalizeImportPath(path) { - return normalizePath(path); - } - TypeScript.normalizeImportPath = normalizeImportPath; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var SourceUnit = (function () { - function SourceUnit(path, content) { - this.path = path; - this.content = content; - this.referencedFiles = null; - } - SourceUnit.prototype.getText = function (start, end) { - return this.content.substring(start, end); - }; - SourceUnit.prototype.getLength = function () { - return this.content.length; - }; - return SourceUnit; - })(); - TypeScript.SourceUnit = SourceUnit; - var CompilationEnvironment = (function () { - function CompilationEnvironment(compilationSettings, ioHost) { - this.compilationSettings = compilationSettings; - this.ioHost = ioHost; - this.residentCode = []; - this.code = []; - } - return CompilationEnvironment; - })(); - TypeScript.CompilationEnvironment = CompilationEnvironment; - var CodeResolver = (function () { - function CodeResolver(environment) { - this.environment = environment; - this.visited = { - }; - } - CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { - var resolvedFile = { - content: "", - path: referencePath - }; - var ioHost = this.environment.ioHost; - var isRelativePath = TypeScript.isRelative(referencePath); - var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); - var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); - if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { - normalizedPath += ".ts"; - } - normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); - var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); - if(!this.visited[absoluteModuleID]) { - if(isRelativePath || isRootedPath || !performSearch) { - try { - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - try { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else { - if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - } - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } - } - } - TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); - resolvedFile.path = normalizedPath; - this.visited[absoluteModuleID] = true; - } catch (err) { - TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); - } - } else { - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else { - if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - } - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - } - if(resolvedFile) { - resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); - TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); - resolvedFile.content = resolvedFile.content; - this.visited[absoluteModuleID] = true; - } else { - TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); - } - } - if(resolvedFile && resolvedFile.content) { - var rootDir = ioHost.dirName(resolvedFile.path); - var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); - var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); - sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; - for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { - var referencedFile = preProcessedFileInfo.referencedFiles[i]; - var normalizedPath = TypeScript.isRooted(referencedFile.path) ? referencedFile.path : rootDir + "/" + referencedFile.path; - normalizedPath = ioHost.resolvePath(normalizedPath); - if(referencePath == normalizedPath) { - resolutionDispatcher.postResolutionError(normalizedPath, "File contains reference to itself", null); - continue; - } - this.resolveCode(referencedFile.path, rootDir, false, resolutionDispatcher); - } - for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { - this.resolveCode(preProcessedFileInfo.importedFiles[i].path, rootDir, true, resolutionDispatcher); - } - resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); - } - } - }; - return CodeResolver; - })(); - TypeScript.CodeResolver = CodeResolver; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var StyleSettings = (function () { - function StyleSettings() { - this.bitwise = false; - this.blockInCompoundStmt = false; - this.eqeqeq = false; - this.forin = false; - this.emptyBlocks = true; - this.newMustBeUsed = false; - this.requireSemi = false; - this.assignmentInCond = false; - this.eqnull = false; - this.evalOK = true; - this.innerScopeDeclEscape = true; - this.funcInLoop = true; - this.reDeclareLocal = true; - this.literalSubscript = true; - this.implicitAny = false; - } - StyleSettings.prototype.setOption = function (opt, val) { - var optExists = this[opt]; - if(optExists !== undefined) { - this[opt] = val; - return true; - } else { - return false; - } - }; - StyleSettings.prototype.parseOptions = function (str) { - var opts = str.split(";"); - for(var i = 0, len = opts.length; i < len; i++) { - var opt = opts[i]; - var val = true; - var colonIndex = opt.lastIndexOf(":"); - if(colonIndex >= 0) { - var valStr = opt.substring(colonIndex + 1); - opt = opt.substring(0, colonIndex); - if(valStr == "off") { - val = false; - } - } - if(!this.setOption(opt, val)) { - return false; - } - } - return true; - }; - return StyleSettings; - })(); - TypeScript.StyleSettings = StyleSettings; - var CompilationSettings = (function () { - function CompilationSettings() { - this.styleSettings = new StyleSettings(); - this.propagateConstants = false; - this.minWhitespace = false; - this.parseOnly = false; - this.errorRecovery = false; - this.emitComments = false; - this.watch = false; - this.exec = false; - this.resolve = true; - this.controlFlow = false; - this.printControlFlow = false; - this.controlFlowUseDef = false; - this.errorOnWith = true; - this.preprocess = true; - this.canCallDefinitionSignature = false; - this.inferPropertiesFromThisAssignment = false; - this.useDefaultLib = true; - this.codeGenTarget = TypeScript.CodeGenTarget.ES3; - this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; - this.outputOption = ""; - this.mapSourceFiles = false; - this.generateDeclarationFiles = false; - this.useCaseSensitiveFileResolution = false; - } - CompilationSettings.prototype.setStyleOptions = function (str) { - this.styleSettings.parseOptions(str); - }; - return CompilationSettings; - })(); - TypeScript.CompilationSettings = CompilationSettings; - function getFileReferenceFromReferencePath(comment) { - var referencesRegEx = /^(\/\/\/\s*/igm; - var match = referencesRegEx.exec(comment); - if(match) { - var path = TypeScript.normalizePath(match[3]); - var adjustedPath = TypeScript.normalizePath(path); - var isResident = match.length >= 7 && match[6] == "true"; - if(isResident) { - TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); - } - return { - minChar: 0, - limChar: 0, - path: TypeScript.switchToForwardSlashes(adjustedPath), - isResident: isResident - }; - } else { - return null; - } - } - function getAdditionalDependencyPath(comment) { - var amdDependencyRegEx = /^(\/\/\/\s*/igm; - var match = amdDependencyRegEx.exec(comment); - if(match) { - var path = match[3]; - return path; - } else { - return null; - } - } - TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; - function getImplicitImport(comment) { - var implicitImportRegEx = /^(\/\/\/\s*/igm; - var match = implicitImportRegEx.exec(comment); - if(match) { - return true; - } - return false; - } - TypeScript.getImplicitImport = getImplicitImport; - function getStyleSettings(comment, styleSettings) { - var styleRegEx = /^(\/\/\/\s*/igm; - var settings = styleRegEx.exec(comment); - if(settings) { - var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/igm; - settings = settingsRegEx.exec(settings[2]); - if(settings) { - for(var i = 0; i < settings.length; i++) { - var setting = (settings[i]).split("="); - var on = "\"on\""; - switch(setting[0]) { - case "blockInCompoundStmt": { - styleSettings.blockInCompoundStmt = setting[1] == on; - break; - - } - case "eqeqeq": { - styleSettings.eqeqeq = setting[1] == on; - break; - - } - case "forin": { - styleSettings.forin = setting[1] == on; - break; - - } - case "emptyBlocks": { - styleSettings.emptyBlocks = setting[1] == on; - break; - - } - case "newMustBeUsed": { - styleSettings.newMustBeUsed = setting[1] == on; - break; - - } - case "requireSemi": { - styleSettings.requireSemi = setting[1] == on; - break; - - } - case "assignmentInCond": { - styleSettings.assignmentInCond = setting[1] == on; - break; - - } - case "eqnull": { - styleSettings.eqnull = setting[1] == on; - break; - - } - case "evalOK": { - styleSettings.evalOK = setting[1] == on; - break; - - } - case "innerScopeDeclEscape": { - styleSettings.innerScopeDeclEscape = setting[1] == on; - break; - - } - case "funcInLoop": { - styleSettings.funcInLoop = setting[1] == on; - break; - - } - case "reDeclareLocal": { - styleSettings.reDeclareLocal = setting[1] == on; - break; - - } - case "literalSubscript": { - styleSettings.literalSubscript = setting[1] == on; - break; - - } - case "implicitAny": { - styleSettings.implicitAny = setting[1] == on; - break; - - } - } - } - } - } - } - TypeScript.getStyleSettings = getStyleSettings; - function getReferencedFiles(sourceText) { - var preProcessInfo = preProcessFile(sourceText, null, false); - return preProcessInfo.referencedFiles; - } - TypeScript.getReferencedFiles = getReferencedFiles; - function preProcessFile(sourceText, options, readImportFiles) { - if (typeof options === "undefined") { options = new CompilationSettings(); } - if (typeof readImportFiles === "undefined") { readImportFiles = true; } - var scanner = new TypeScript.Scanner(); - scanner.resetComments(); - scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var tok = scanner.scan(); - var comments = []; - var comment = null; - var leftCurlies = []; - var settings = options; - var referencedFiles = []; - var importedFiles = []; - var isLibFile = false; - while(tok.tokenId != TypeScript.TokenID.EndOfFile) { - if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Equals) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Module) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.OpenParen) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.StringLiteral) { - var ref = { - minChar: scanner.startPos, - limChar: scanner.pos, - path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), - isResident: false - }; - importedFiles.push(ref); - } - } - } - } - } - } - if(tok.tokenId == TypeScript.TokenID.OpenBrace) { - leftCurlies.push(tok); - } - if(tok.tokenId == TypeScript.TokenID.CloseBrace) { - leftCurlies.pop(); - } - tok = scanner.scan(); - } - comments = scanner.getComments(); - for(var iComment = 0; iComment < comments.length; iComment++) { - comment = comments[iComment]; - if(!comment.isBlock) { - var referencedCode = getFileReferenceFromReferencePath(comment.getText()); - if(referencedCode) { - referencedCode.minChar = comment.startPos; - referencedCode.limChar = referencedCode.minChar + comment.value.length; - referencedFiles.push(referencedCode); - } - if(settings) { - getStyleSettings(comment.getText(), settings.styleSettings); - var isNoLibRegex = /^(\/\/\/\s*/igm; - var isNoLibMatch = isNoLibRegex.exec(comment.getText()); - if(isNoLibMatch) { - isLibFile = (isNoLibMatch[3] == "true"); - } - } - } - } - return { - settings: settings, - referencedFiles: referencedFiles, - importedFiles: importedFiles, - isLibFile: isLibFile - }; - } - TypeScript.preProcessFile = preProcessFile; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var IncrementalParser = (function () { - function IncrementalParser(logger) { - this.logger = logger; - this.astLogger = new TypeScript.AstLogger(this.logger); - } - IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - if(editRange.isUnknown()) { - this.logger.log(" Bailing out because edit range is unknown"); - return null; - } - var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); - var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); - if(scope1 == null || scope2 == null) { - this.logger.log(" Bailing out because containing scopes cannot be determined"); - return null; - } - if(scope1.scopeStartAST !== scope2.scopeStartAST) { - this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength <= 0) { - this.logger.log(" Bailing out because scope has been entirely removed from new source text"); - return null; - } - return scope1; - }; - IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); - if(scope1 === null) { - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength >= newSourceText.getLength() / 2) { - this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); - return null; - } - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); - if(quickParseResult.endLexState != TypeScript.LexState.Start) { - this.logger.log(" Bailing out because scope contains unterminated comment"); - return null; - } - var scriptFragment = quickParseResult.Script; - if(scriptFragment.vars.members.length !== 0) { - this.logger.log(" Bailing out because new source text defines variables"); - return null; - } - if(scriptFragment.bod.members.length !== 1) { - this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); - return null; - } - var oldScope = scope1.scopeStartAST; - var newScope = scriptFragment.bod.members[0]; - if(oldScope.nodeType != newScope.nodeType) { - this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); - return null; - } - if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { - this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); - return null; - } - if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); - return null; - } - if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); - return null; - } - if(newScope.minChar !== 0) { - this.logger.log(" Bailing out because new function declaration does not start at position 0"); - return null; - } - if(newScope.limChar !== newScopeLength) { - this.logger.log(" Bailing out because new function declaration does not end at the new end position"); - return null; - } - return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); - }; - IncrementalParser.prototype.mergeTrees = function (updateResult) { - var _this = this; - TypeScript.timeFunction(this.logger, "mergeTrees()", function () { - var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); - _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); - _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); - _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); - _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); - }); - }; - IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { - var _this = this; - var pre = function (cur, parent, walker) { - if(cur === oldAst) { - newAst.preComments = cur.preComments; - newAst.postComments = cur.postComments; - _this.logger.log("replaced old AST node with new one in script AST"); - walker.options.stopWalk(); - return newAst; - } - if(TypeScript.isValidAstNode(cur)) { - if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - }; - IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { - var lineMap1 = script.locationInfo.lineMap; - var lineMap2 = partial.locationInfo.lineMap; - if(this.logger.information()) { - this.logger.log("lineMap1 (before):"); - this.astLogger.logLinemap(lineMap1); - this.logger.log("lineMap2 (quick parse):"); - this.astLogger.logLinemap(lineMap2); - this.logger.log("EditRange=" + editRange); - } - var i1 = 2; - var i2 = 2; - var len1 = lineMap1.length; - var len2 = lineMap2.length; - while(i1 < len1) { - if(lineMap1[i1] <= editRange.minChar) { - i1++; - } else { - if(lineMap1[i1] >= editRange.limChar) { - lineMap1[i1] += editRange.delta; - i1++; - } else { - if(i2 < len2) { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } else { - lineMap1.splice(i1, 1); - len1--; - } - } - } - } - if(i2 < len2) { - if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { - i1 = 2; - while(i1 < len1 && i2 < len2) { - if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { - i1++; - } else { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } - } - } - for(; i2 < len2; i2++) { - lineMap1.push(lineMap2[i2] + editRange.minChar); - } - } - if(this.logger.information()) { - this.logger.log("lineMap1 (after merge):"); - this.astLogger.logLinemap(lineMap1); - } - }; - IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { - var applyDelta = function (ast) { - if(ast.minChar !== -1 && ast.minChar >= start) { - ast.minChar += delta; - } - if(ast.limChar !== -1 && ast.limChar >= start) { - ast.limChar += delta; - } - }; - var applyDeltaToComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - applyDelta(comments[i]); - } - } - }; - var pre = function (cur, parent, walker) { - if(cur.limChar !== -1 && cur.limChar < start) { - walker.options.goChildren = false; - } - applyDelta(cur); - applyDeltaToComments(cur.preComments); - applyDeltaToComments(cur.postComments); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(ast, pre); - }; - return IncrementalParser; - })(); - TypeScript.IncrementalParser = IncrementalParser; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var DeclFileWriter = (function () { - function DeclFileWriter(declFile) { - this.declFile = declFile; - this.onNewLine = true; - } - DeclFileWriter.prototype.Write = function (s) { - this.declFile.Write(s); - this.onNewLine = false; - }; - DeclFileWriter.prototype.WriteLine = function (s) { - this.declFile.WriteLine(s); - this.onNewLine = true; - }; - DeclFileWriter.prototype.Close = function () { - this.declFile.Close(); - }; - return DeclFileWriter; - })(); - TypeScript.DeclFileWriter = DeclFileWriter; - var DeclarationEmitter = (function () { - function DeclarationEmitter(checker, emitOptions, errorReporter) { - this.checker = checker; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.declFile = null; - this.indenter = new TypeScript.Indenter(); - this.declarationContainerStack = []; - this.isDottedModuleName = []; - this.ignoreCallbackAst = null; - this.singleDeclFile = null; - this.varListCount = 0; - } - DeclarationEmitter.prototype.getAstDeclarationContainer = function () { - return this.declarationContainerStack[this.declarationContainerStack.length - 1]; - }; - DeclarationEmitter.prototype.emitDottedModuleName = function () { - return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; - }; - DeclarationEmitter.prototype.setDeclarationFile = function (file) { - this.declFile = new DeclFileWriter(file); - }; - DeclarationEmitter.prototype.Close = function () { - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - DeclarationEmitter.prototype.emitDeclarations = function (script) { - TypeScript.AstWalkerWithDetailCallback.walk(script, this); - }; - DeclarationEmitter.prototype.getIndentString = function (declIndent) { - if (typeof declIndent === "undefined") { declIndent = false; } - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - DeclarationEmitter.prototype.emitIndent = function () { - this.declFile.Write(this.getIndentString()); - }; - DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { - if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } - if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } - var container; - if(useDeclarationContainerTop) { - container = this.getAstDeclarationContainer(); - } else { - container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; - } - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - return false; - } - if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { - return false; - } - return true; - }; - DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { - if(this.ignoreCallbackAst) { - TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); - this.ignoreCallbackAst = null; - return false; - } else { - if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { - this.ignoreCallbackAst = astWithPrePostCallback; - return false; - } - } - return true; - }; - DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { - var result = this.getIndentString(); - var accessorString = ""; - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { - accessorString = "get "; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { - accessorString = "set "; - } - } - var container = this.getAstDeclarationContainer(); - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - result += "export "; - } - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { - result += "static " + accessorString; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { - result += "private " + accessorString; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { - result += "public " + accessorString; - } else { - if(accessorString == "") { - result += typeString + " "; - } else { - result += accessorString; - } - } - } - } - return result; - }; - DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { - this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); - }; - DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { - if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } - return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); - }; - DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { - this.declarationContainerStack.push(ast); - }; - DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { - TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); - this.declarationContainerStack.pop(); - }; - DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { - if (typeof emitIndent === "undefined") { emitIndent = false; } - if(memberName.prefix == "{ ") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.WriteLine("{"); - this.indenter.increaseIndent(); - emitIndent = true; - } else { - if(memberName.prefix != "") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write(memberName.prefix); - emitIndent = false; - } - } - if(memberName.isString()) { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write((memberName).text); - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - this.emitTypeNamesMember(ar.entries[index], emitIndent); - if(ar.delim == "; ") { - this.declFile.WriteLine(";"); - } - } - } - if(memberName.suffix == "}") { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.Write(memberName.suffix); - } else { - this.declFile.Write(memberName.suffix); - } - }; - DeclarationEmitter.prototype.emitTypeSignature = function (type) { - var containingScope = null; - var declarationContainerAst = this.getAstDeclarationContainer(); - switch(declarationContainerAst.nodeType) { - case TypeScript.NodeType.ModuleDeclaration: - case TypeScript.NodeType.InterfaceDeclaration: - case TypeScript.NodeType.FuncDecl: { - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.containedScope; - } - break; - - } - case TypeScript.NodeType.Script: { - var script = declarationContainerAst; - if(script.bod) { - containingScope = script.bod.enclosingScope; - } - break; - - } - case TypeScript.NodeType.ClassDeclaration: { - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.instanceType.containedScope; - } - break; - - } - default: { - TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); - - } - } - var typeNameMembers = type.getScopedTypeNameEx(containingScope); - this.emitTypeNamesMember(typeNameMembers); - }; - DeclarationEmitter.prototype.emitComment = function (comment) { - var text = comment.getText(); - if(this.declFile.onNewLine) { - this.emitIndent(); - } else { - if(!comment.isBlockComment) { - this.declFile.WriteLine(""); - this.emitIndent(); - } - } - this.declFile.Write(text[0]); - for(var i = 1; i < text.length; i++) { - this.declFile.WriteLine(""); - this.emitIndent(); - this.declFile.Write(text[i]); - } - if(comment.endsLine || !comment.isBlockComment) { - this.declFile.WriteLine(""); - } else { - this.declFile.Write(" "); - } - }; - DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { - if (typeof endLine === "undefined") { endLine = true; } - if(!this.emitOptions.emitComments) { - return; - } - var declComments = astOrSymbol.getDocComments(); - if(declComments.length > 0) { - for(var i = 0; i < declComments.length; i++) { - this.emitComment(declComments[i]); - } - if(endLine) { - if(!this.declFile.onNewLine) { - this.declFile.WriteLine(""); - } - } else { - if(this.declFile.onNewLine) { - this.emitIndent(); - } - } - } - }; - DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { - if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { - var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - this.emitDeclarationComments(varDecl); - if(!interfaceMember) { - if(this.varListCount >= 0) { - this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); - this.varListCount = -this.varListCount; - } - this.declFile.Write(varDecl.id.text); - } else { - this.emitIndent(); - this.declFile.Write(varDecl.id.text); - if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("?"); - } - } - var type = null; - if(varDecl.typeExpr && varDecl.typeExpr.type) { - type = varDecl.typeExpr.type; - } else { - if(varDecl.sym) { - type = (varDecl.sym).getType(); - if(type == this.checker.anyType) { - type = null; - } - } - } - if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(type); - } - if(this.varListCount > 0) { - this.varListCount--; - } else { - if(this.varListCount < 0) { - this.varListCount++; - } - } - if(this.varListCount < 0) { - this.declFile.Write(", "); - } else { - this.declFile.WriteLine(";"); - } - } - return false; - }; - DeclarationEmitter.prototype.BlockCallback = function (pre, block) { - if(!block.isStatementBlock) { - if(pre) { - this.varListCount = block.statements.members.length; - } else { - this.varListCount = 0; - } - return true; - } - return false; - }; - DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { - this.emitDeclarationComments(argDecl, false); - this.declFile.Write(argDecl.id.text); - if(argDecl.isOptionalArg()) { - this.declFile.Write("?"); - } - if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - }; - DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { - if(!pre) { - return false; - } - if(funcDecl.isAccessor()) { - return this.emitPropertyAccessorSignature(funcDecl); - } - var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - if(funcDecl.bod) { - if(funcDecl.isConstructor) { - if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { - return false; - } - } else { - if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - return false; - } - } - } else { - if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - var signatures = funcDecl.type.call.signatures; - var firstSignature = signatures[0].declAST; - if(firstSignature.bod) { - firstSignature = signatures[1].declAST; - } - if(firstSignature != funcDecl) { - return false; - } - } - } - if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { - return false; - } - this.emitDeclarationComments(funcDecl); - if(funcDecl.isConstructor) { - this.emitIndent(); - this.declFile.Write("constructor"); - } else { - var id = funcDecl.getNameText(); - if(!isInterfaceMember) { - this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); - this.declFile.Write(id); - } else { - this.emitIndent(); - if(funcDecl.isConstructMember()) { - this.declFile.Write("new"); - } else { - if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { - this.declFile.Write(id); - if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("? "); - } - } - } - } - } - if(!funcDecl.isIndexerMember()) { - this.declFile.Write("("); - } else { - this.declFile.Write("["); - } - this.indenter.increaseIndent(); - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - this.emitArgDecl(argDecl, funcDecl); - if(i < (argsLen - 1)) { - this.declFile.Write(", "); - } - } - } - if(funcDecl.variableArgList) { - var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; - if(funcDecl.arguments.members.length > 1) { - this.declFile.Write(", ..."); - } else { - this.declFile.Write("..."); - } - this.emitArgDecl(lastArg, funcDecl); - } - this.indenter.decreaseIndent(); - if(!funcDecl.isIndexerMember()) { - this.declFile.Write(")"); - } else { - this.declFile.Write("]"); - } - if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(funcDecl.signature.returnType.type); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { - if(bases && (bases.members.length > 0)) { - this.declFile.Write(" " + qual + " "); - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = baseExpr.type.symbol; - var baseType = baseExpr.type; - if(i > 0) { - this.declFile.Write(", "); - } - this.emitTypeSignature(baseType); - } - } - }; - DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { - var accessorSymbol = funcDecl.accessorSymbol; - if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { - return false; - } - this.emitDeclarationComments(accessorSymbol); - this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); - this.declFile.Write(funcDecl.name.text); - var propertyType = accessorSymbol.getType(); - if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { - this.declFile.Write(" : "); - this.emitTypeSignature(propertyType); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { - this.emitDeclarationComments(argDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); - this.declFile.Write(argDecl.id.text); - if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - this.declFile.WriteLine(";"); - } - } - } - }; - DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { - return false; - } - if(pre) { - var className = classDecl.name.text; - this.emitDeclarationComments(classDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); - this.declFile.Write(className); - this.emitBaseList(classDecl.extendsList, "extends"); - this.emitBaseList(classDecl.implementsList, "implements"); - this.declFile.WriteLine(" {"); - this.pushDeclarationContainer(classDecl); - this.indenter.increaseIndent(); - if(classDecl.constructorDecl) { - this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); - } - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(classDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { - return false; - } - if(pre) { - var interfaceName = interfaceDecl.name.text; - this.emitDeclarationComments(interfaceDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); - this.declFile.Write(interfaceName); - this.emitBaseList(interfaceDecl.extendsList, "extends"); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - this.pushDeclarationContainer(interfaceDecl); - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(interfaceDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { - if(pre) { - if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { - this.emitDeclarationComments(importDecl); - this.emitIndent(); - this.declFile.Write("import "); - this.declFile.Write(importDecl.id.text + " = "); - if(importDecl.isDynamicImport) { - this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); - } else { - this.declFile.WriteLine(importDecl.getAliasName() + ";"); - } - } - } - return false; - }; - DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { - if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { - return false; - } - this.emitDeclarationComments(moduleDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); - this.declFile.WriteLine(moduleDecl.name.text + " {"); - this.indenter.increaseIndent(); - var membersLen = moduleDecl.members.members.length; - for(var j = 1; j < membersLen; j++) { - var memberDecl = moduleDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.emitDeclarationComments(memberDecl); - this.emitIndent(); - this.declFile.WriteLine((memberDecl).id.text + ","); - } else { - TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); - } - } - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - return false; - }; - DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - if(pre) { - if(!this.emitOptions.outputMany) { - this.singleDeclFile = this.declFile; - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - try { - this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - } - this.pushDeclarationContainer(moduleDecl); - } else { - if(!this.emitOptions.outputMany) { - TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - this.declFile = this.singleDeclFile; - } - this.popDeclarationContainer(moduleDecl); - } - } - return true; - } - if(moduleDecl.isEnum()) { - if(pre) { - this.emitEnumSignature(moduleDecl); - } - return false; - } - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { - return false; - } - if(pre) { - if(this.emitDottedModuleName()) { - this.dottedModuleEmit += "."; - } else { - this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); - } - this.dottedModuleEmit += moduleDecl.name.text; - var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); - var moduleDeclComments = moduleDecl.getDocComments(); - isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); - this.isDottedModuleName.push(isCurrentModuleDotted); - this.pushDeclarationContainer(moduleDecl); - if(!isCurrentModuleDotted) { - this.emitDeclarationComments(moduleDecl); - this.declFile.Write(this.dottedModuleEmit); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - } - } else { - if(!this.emitDottedModuleName()) { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - this.popDeclarationContainer(moduleDecl); - this.isDottedModuleName.pop(); - } - return true; - }; - DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { - if(pre) { - if(this.emitOptions.outputMany) { - for(var i = 0; i < script.referencedFiles.length; i++) { - var referencePath = script.referencedFiles[i].path; - var declareFileName; - if(TypeScript.isRooted(referencePath)) { - declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); - } else { - declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); - } - this.declFile.WriteLine('/// '); - } - } - this.pushDeclarationContainer(script); - } else { - this.popDeclarationContainer(script); - } - return true; - }; - DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { - return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); - }; - return DeclarationEmitter; - })(); - TypeScript.DeclarationEmitter = DeclarationEmitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (UpdateUnitKind) { - UpdateUnitKind._map = []; - UpdateUnitKind._map[0] = "Unknown"; - UpdateUnitKind.Unknown = 0; - UpdateUnitKind._map[1] = "NoEdits"; - UpdateUnitKind.NoEdits = 1; - UpdateUnitKind._map[2] = "EditsInsideSingleScope"; - UpdateUnitKind.EditsInsideSingleScope = 2; - })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); - var UpdateUnitKind = TypeScript.UpdateUnitKind; - var ScriptEditRange = (function () { - function ScriptEditRange(minChar, limChar, delta) { - this.minChar = minChar; - this.limChar = limChar; - this.delta = delta; - } - ScriptEditRange.unknown = function unknown() { - return new ScriptEditRange(-1, -1, -1); - } - ScriptEditRange.prototype.isUnknown = function () { - return this.minChar === -1 && this.limChar === -1 && this.delta === -1; - }; - ScriptEditRange.prototype.containsPosition = function (pos) { - return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); - }; - ScriptEditRange.prototype.toString = function () { - return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; - }; - return ScriptEditRange; - })(); - TypeScript.ScriptEditRange = ScriptEditRange; - var UpdateUnitResult = (function () { - function UpdateUnitResult(kind, unitIndex, script1, script2) { - this.kind = kind; - this.unitIndex = unitIndex; - this.script1 = script1; - this.script2 = script2; - this.scope1 = null; - this.scope2 = null; - this.editRange = null; - this.parseErrors = []; - } - UpdateUnitResult.noEdits = function noEdits(unitIndex) { - return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); - } - UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); - result.parseErrors = parseErrors; - return result; - } - UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); - result.scope1 = scope1; - result.scope2 = scope2; - result.editRange = editRange; - result.parseErrors = parseErrors; - return result; - } - return UpdateUnitResult; - })(); - TypeScript.UpdateUnitResult = UpdateUnitResult; - var ErrorEntry = (function () { - function ErrorEntry(unitIndex, minChar, limChar, message) { - this.unitIndex = unitIndex; - this.minChar = minChar; - this.limChar = limChar; - this.message = message; - } - return ErrorEntry; - })(); - TypeScript.ErrorEntry = ErrorEntry; - TypeScript.defaultSettings = new TypeScript.CompilationSettings(); - var TypeScriptCompiler = (function () { - function TypeScriptCompiler(errorOutput, logger, settings) { - if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } - if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } - this.errorOutput = errorOutput; - this.logger = logger; - this.settings = settings; - this.parser = new TypeScript.Parser(); - this.typeFlow = null; - this.scripts = new TypeScript.ASTList(); - this.units = new Array(); - this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); - this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); - this.errorReporter.parser = this.parser; - this.initTypeChecker(this.errorOutput); - this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; - this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; - this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; - this.emitSettings = new TypeScript.EmitOptions(this.settings); - TypeScript.codeGenTarget = settings.codeGenTarget; - } - TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { - return TypeScript.timeFunction(this.logger, funcDescription, func); - }; - TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { - this.persistentTypeState.refreshPersistentState(); - this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); - this.typeChecker.errorReporter = this.errorReporter; - this.typeChecker.checkControlFlow = this.settings.controlFlow; - this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; - this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; - this.typeChecker.errorsOnWith = this.settings.errorOnWith; - this.typeChecker.styleSettings = this.settings.styleSettings; - this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; - this.errorReporter.checker = this.typeChecker; - this.setErrorOutput(this.errorOutput); - }; - TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { - this.errorOutput = outerr; - this.errorReporter.setErrOut(outerr); - this.parser.outfile = outerr; - }; - TypeScriptCompiler.prototype.emitCommentsToOutput = function () { - this.emitSettings = new TypeScript.EmitOptions(this.settings); - }; - TypeScriptCompiler.prototype.setErrorCallback = function (fn) { - this.parser.errorCallback = fn; - }; - TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { - return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); - }; - TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("updateSourceUnit(" + filename + ")", function () { - var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); - return _this.applyUpdateResult(updateResult); - }); - }; - TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { - switch(updateResult.kind) { - case UpdateUnitKind.NoEdits: { - return false; - - } - case UpdateUnitKind.Unknown: { - this.scripts.members[updateResult.unitIndex] = updateResult.script2; - this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; - for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { - var e = updateResult.parseErrors[i]; - if(this.parser.errorCallback) { - this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); - } - } - return true; - - } - case UpdateUnitKind.EditsInsideSingleScope: { - new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); - return true; - - } - } - }; - TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { - for(var i = 0, len = _this.units.length; i < len; i++) { - if(_this.units[i].filename == filename) { - if((_this.scripts.members[i]).isResident) { - return UpdateUnitResult.noEdits(i); - } - if(setRecovery) { - _this.parser.setErrorRecovery(null); - } - var updateResult; - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var svErrorCallback = _this.parser.errorCallback; - if(svErrorCallback) { - _this.parser.errorCallback = errorCapture; - } - var oldScript = _this.scripts.members[i]; - var newScript = _this.parser.parse(sourceText, filename, i); - if(svErrorCallback) { - _this.parser.errorCallback = svErrorCallback; - } - updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); - return updateResult; - } - } - throw new Error("Unknown file \"" + filename + "\""); - }); - }; - TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { - if (typeof keepResident === "undefined") { keepResident = false; } - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); - }; - TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - var _this = this; - return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { - var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); - script.referencedFiles = referencedFiles; - script.isResident = keepResident; - _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); - var index = _this.units.length; - _this.units[index] = script.locationInfo; - _this.typeChecker.collectTypes(script); - _this.scripts.append(script); - return script; - }); - }; - TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { - return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); - }; - TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { - this.parser.setErrorRecovery(this.errorOutput); - var script = this.parser.parse(sourceText, filename, 0); - var index = this.units.length; - this.units[index] = script.locationInfo; - this.typeChecker.collectTypes(script); - this.scripts.append(script); - }; - TypeScriptCompiler.prototype.typeCheck = function () { - var _this = this; - return this.timeFunction("typeCheck()", function () { - var binder = new TypeScript.Binder(_this.typeChecker); - _this.typeChecker.units = _this.units; - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); - _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); - var i = 0; - var script = null; - var len = _this.scripts.members.length; - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.typeCheck(script); - script.hasBeenTypeChecked = true; - } - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - len = _this.scripts.members.length; - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.typeCheck(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { - function cleanASTType(ast, parent) { - ast.type = null; - if(ast.nodeType == TypeScript.NodeType.VarDecl) { - var vardecl = ast; - vardecl.sym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - var argdecl = ast; - argdecl.sym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.Name) { - var name = ast; - name.sym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcdecl = ast; - funcdecl.signature = null; - funcdecl.freeVariables = new Array(); - funcdecl.symbols = null; - funcdecl.accessorSymbol = null; - funcdecl.scopeType = null; - } else { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var modDecl = ast; - modDecl.mod = null; - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - (ast).withSym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.Catch) { - (ast).containedScope = null; - } - } - } - } - } - } - } - return ast; - } - TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); - }; - TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { - var _this = this; - return this.timeFunction("cleanTypesForReTypeCheck()", function () { - for(var i = 0, len = _this.scripts.members.length; i < len; i++) { - var script = _this.scripts.members[i]; - if((script).isResident) { - continue; - } - _this.cleanASTTypesForReTypeCheck(script); - _this.typeChecker.collectTypes(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { - return this.timeFunction("attemptIncrementalTypeCheck()", function () { - return false; - }); - }; - TypeScriptCompiler.prototype.reTypeCheck = function () { - var _this = this; - return this.timeFunction("reTypeCheck()", function () { - TypeScript.CompilerDiagnostics.analysisPass++; - _this.initTypeChecker(_this.errorOutput); - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - _this.cleanTypesForReTypeCheck(); - return _this.typeCheck(); - }); - }; - TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(!script.isDeclareFile && script.topLevelMod != null) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { - var commonComponents = []; - var commonComponentsLength = -1; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(script.emitRequired(this.emitSettings)) { - var fileName = script.locationInfo.filename; - var fileComponents = TypeScript.filePathComponents(fileName); - if(commonComponentsLength == -1) { - commonComponents = fileComponents; - commonComponentsLength = commonComponents.length; - } else { - var updatedPath = false; - for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { - if(commonComponents[j] != fileComponents[j]) { - commonComponentsLength = j; - updatedPath = true; - if(j == 0) { - this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); - return; - } - break; - } - } - if(!updatedPath && fileComponents.length < commonComponentsLength) { - commonComponentsLength = fileComponents.length; - } - } - } - } - this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; - if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { - this.emitSettings.outputOption += "/"; - } - }; - TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { - this.emitSettings.ioHost = ioHost; - if(this.emitSettings.outputOption == "") { - this.emitSettings.outputMany = true; - this.emitSettings.commonDirectoryPath = ""; - return; - } - this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); - if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = true; - } else { - if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = false; - } else { - this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); - } - } - if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { - this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); - } - if(this.emitSettings.outputMany) { - this.updateCommonDirectoryPath(); - } - }; - TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { - if(this.emitSettings.outputMany) { - return this.outputScriptToUTF8(script); - } else { - return this.outputScriptsToUTF8((this.scripts.members)); - } - }; - TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { - return TypeScript.getDeclareFilePath(fileName); - } - TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { - if(!this.settings.generateDeclarationFiles) { - return false; - } - if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { - return false; - } - return true; - }; - TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { - if(!this.canEmitDeclarations(script)) { - return null; - } - if(!declarationEmitter) { - var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); - var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); - declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); - declarationEmitter.setDeclarationFile(declareFile); - } - declarationEmitter.emitDeclarations(script); - if(!reuseEmitter) { - declarationEmitter.Close(); - return null; - } else { - return declarationEmitter; - } - }; - TypeScriptCompiler.prototype.emitDeclarations = function () { - if(!this.canEmitDeclarations()) { - return; - } - if(this.errorReporter.hasErrors) { - return; - } - if(this.scripts.members.length == 0) { - return; - } - var declarationEmitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || declarationEmitter == null) { - declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); - } else { - this.emitDeclarationsUnit(script, true, declarationEmitter); - } - } - if(declarationEmitter) { - declarationEmitter.Close(); - } - }; - TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { - if(wholeFileNameReplaced) { - return fileName; - } else { - var splitFname = fileName.split("."); - splitFname.pop(); - return splitFname.join(".") + extension; - } - } - TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); - } - TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter) { - if(!script.emitRequired(this.emitSettings)) { - return null; - } - var fname = script.locationInfo.filename; - if(!emitter) { - var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); - var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); - if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter)); - } - } else { - if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter)); - } - } - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - if(!reuseEmitter) { - emitter.Close(); - return null; - } else { - return emitter; - } - }; - TypeScriptCompiler.prototype.emit = function (ioHost) { - this.parseEmitOption(ioHost); - var emitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || emitter == null) { - emitter = this.emitUnit(script, !this.emitSettings.outputMany); - } else { - this.emitUnit(script, true, emitter); - } - } - if(emitter) { - emitter.Close(); - } - }; - TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { - if(this.settings.mapSourceFiles) { - throw Error("Cannot generate source map"); - } - if(this.settings.generateDeclarationFiles) { - throw Error("Cannot generate declaration files"); - } - if(this.settings.outputOption != "") { - throw Error("Cannot parse output option"); - } - var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); - ; ; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - } - }; - TypeScriptCompiler.prototype.emitAST = function (ioHost) { - this.parseEmitOption(ioHost); - var outFile = null; - var context = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || context == null) { - var fname = this.units[i].filename; - var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); - }; - var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); - outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - context = new TypeScript.PrintContext(outFile, this.parser); - } - TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); - if(this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - } - if(!this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - }; - TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { - return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); - }; - TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { - for(var i = 0, len = scripts.length; i < len; i++) { - var script = scripts[i]; - if(this.outputScriptToUTF8(script)) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitSettings.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return TypeScriptCompiler; - })(); - TypeScript.TypeScriptCompiler = TypeScriptCompiler; - var ScopeEntry = (function () { - function ScopeEntry(name, type, sym) { - this.name = name; - this.type = type; - this.sym = sym; - } - return ScopeEntry; - })(); - TypeScript.ScopeEntry = ScopeEntry; - var ScopeTraversal = (function () { - function ScopeTraversal(compiler) { - this.compiler = compiler; - } - ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { - if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { - return enclosingScopeContext.getObjectLiteralScope(); - } else { - if(enclosingScopeContext.isMemberCompletion) { - if(enclosingScopeContext.useFullAst) { - return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); - } else { - return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); - } - } else { - return enclosingScopeContext.getScope(); - } - } - }; - ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext) { - var scope = this.getScope(enclosingScopeContext); - if(scope == null) { - return []; - } - var inScopeNames = new TypeScript.StringHashTable(); - var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); - for(var i = 0; i < allSymbolNames.length; i++) { - var name = allSymbolNames[i]; - if(name == TypeScript.globalId || name == "_Core" || name == "_element") { - continue; - } - inScopeNames.add(name, ""); - } - var svModuleDecl = this.compiler.typeChecker.currentModDecl; - this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; - var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope); - this.compiler.typeChecker.currentModDecl = svModuleDecl; - return result; - }; - ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope) { - var result = []; - var enclosingScope = enclosingScopeContext.getScope(); - for(var i = 0; i < allNames.length; i++) { - var name = allNames[i]; - var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; - var symbol = scope.find(name, publicsOnly, false); - if(symbol == null) { - symbol = scope.find(name, publicsOnly, true); - } - var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; - if(symbol) { - if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { - var typeName = symbol.getType().getScopedTypeName(enclosingScope); - result.push(new ScopeEntry(name, typeName, symbol)); - } - } else { - if(name == "true" || name == "false") { - result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); - } - } - } - return result; - }; - return ScopeTraversal; - })(); - TypeScript.ScopeTraversal = ScopeTraversal; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (CompilerDiagnostics) { - CompilerDiagnostics.debug = false; - CompilerDiagnostics.diagnosticWriter = null; - CompilerDiagnostics.analysisPass = 0; - function Alert(output) { - if(CompilerDiagnostics.diagnosticWriter) { - CompilerDiagnostics.diagnosticWriter.Alert(output); - } - } - CompilerDiagnostics.Alert = Alert; - function debugPrint(s) { - if(CompilerDiagnostics.debug) { - Alert(s); - } - } - CompilerDiagnostics.debugPrint = debugPrint; - function assert(condition, s) { - if(CompilerDiagnostics.debug) { - if(!condition) { - Alert(s); - } - } - } - CompilerDiagnostics.assert = assert; - })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); - var CompilerDiagnostics = TypeScript.CompilerDiagnostics; - var NullLogger = (function () { - function NullLogger() { } - NullLogger.prototype.information = function () { - return false; - }; - NullLogger.prototype.debug = function () { - return false; - }; - NullLogger.prototype.warning = function () { - return false; - }; - NullLogger.prototype.error = function () { - return false; - }; - NullLogger.prototype.fatal = function () { - return false; - }; - NullLogger.prototype.log = function (s) { - }; - return NullLogger; - })(); - TypeScript.NullLogger = NullLogger; - var LoggerAdapter = (function () { - function LoggerAdapter(logger) { - this.logger = logger; - this._information = this.logger.information(); - this._debug = this.logger.debug(); - this._warning = this.logger.warning(); - this._error = this.logger.error(); - this._fatal = this.logger.fatal(); - } - LoggerAdapter.prototype.information = function () { - return this._information; - }; - LoggerAdapter.prototype.debug = function () { - return this._debug; - }; - LoggerAdapter.prototype.warning = function () { - return this._warning; - }; - LoggerAdapter.prototype.error = function () { - return this._error; - }; - LoggerAdapter.prototype.fatal = function () { - return this._fatal; - }; - LoggerAdapter.prototype.log = function (s) { - this.logger.log(s); - }; - return LoggerAdapter; - })(); - TypeScript.LoggerAdapter = LoggerAdapter; - var BufferedLogger = (function () { - function BufferedLogger() { - this.logContents = []; - } - BufferedLogger.prototype.information = function () { - return false; - }; - BufferedLogger.prototype.debug = function () { - return false; - }; - BufferedLogger.prototype.warning = function () { - return false; - }; - BufferedLogger.prototype.error = function () { - return false; - }; - BufferedLogger.prototype.fatal = function () { - return false; - }; - BufferedLogger.prototype.log = function (s) { - this.logContents.push(s); - }; - return BufferedLogger; - })(); - TypeScript.BufferedLogger = BufferedLogger; - function timeFunction(logger, funcDescription, func) { - var start = +new Date(); - var result = func(); - var end = +new Date(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); - return result; - } - TypeScript.timeFunction = timeFunction; - function stringToLiteral(value, length) { - var result = ""; - var addChar = function (index) { - var ch = value.charCodeAt(index); - switch(ch) { - case 9: { - result += "\\t"; - break; - - } - case 10: { - result += "\\n"; - break; - - } - case 11: { - result += "\\v"; - break; - - } - case 12: { - result += "\\f"; - break; - - } - case 13: { - result += "\\r"; - break; - - } - case 34: { - result += "\\\""; - break; - - } - case 39: { - result += "\\\'"; - break; - - } - case 92: { - result += "\\"; - break; - - } - default: { - result += value.charAt(index); - - } - } - }; - var tooLong = (value.length > length); - if(tooLong) { - var mid = length >> 1; - for(var i = 0; i < mid; i++) { - addChar(i); - } - result += "(...)"; - for(var i = value.length - mid; i < value.length; i++) { - addChar(i); - } - } else { - length = value.length; - for(var i = 0; i < length; i++) { - addChar(i); - } - } - return result; - } - TypeScript.stringToLiteral = stringToLiteral; -})(TypeScript || (TypeScript = {})); -var IOUtils; -(function (IOUtils) { - function createDirectoryStructure(ioHost, dirName) { - if(ioHost.directoryExists(dirName)) { - return; - } - var parentDirectory = ioHost.dirName(dirName); - if(parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - function throwIOError(message, error) { - var errorMessage = message; - if(error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - function getStreamObject() { - if(streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - var args = []; - for(var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) { - streamObj.Charset = 'unicode'; - } else { - if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) { - streamObj.Charset = 'utf-8'; - } - } - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - while(true) { - if(fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - if(rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if(fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - }finally { - if(streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || { - }; - function filesInFolder(folder, root) { - var paths = []; - var fc; - if(options.recursive) { - fc = new Enumerator(folder.subfolders); - for(; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - fc = new Enumerator(folder.files); - for(; !fc.atEnd(); fc.moveNext()) { - if(!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - return paths; - } - var folder = fso.GetFolder(path); - var paths = []; - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; ; - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch(buffer[0]) { - case 254: { - if(buffer[1] == 255) { - var i = 0; - while((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - - } - case 255: { - if(buffer[1] == 254) { - return buffer.toString("ucs2", 2); - } - break; - - } - case 239: { - if(buffer[1] == 187) { - return buffer.toString("utf8", 3); - } - - } - } - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if(stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else { - if(stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 509); - } - } - } - mkdirRecursiveSync(_path.dirname(path)); - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }; - }, - dir: function dir(path, spec, options) { - options = options || { - }; - function filesInFolder(folder) { - var paths = []; - var files = _fs.readdirSync(folder); - for(var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if(options.recursive && stat.isDirectory()) { - paths = paths.concat(filesInFolder(folder + "/" + files[i])); - } else { - if(stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - } - return paths; - } - return filesInFolder(path); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - while(true) { - if(_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - if(rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - var fileChanged = function (curr, prev) { - if(!firstRun) { - if(curr.mtime < prev.mtime) { - return; - } - _fs.unwatchFile(filename, fileChanged); - if(!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { - persistent: true, - interval: 500 - }, fileChanged); - }; - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; ; - if(typeof ActiveXObject === "function") { - return getWindowsScriptHostIO(); - } else { - if(typeof require === "function") { - return getNodeIO(); - } else { - return null; - } - } -})(); -var OptionsParser = (function () { - function OptionsParser(host) { - this.host = host; - this.DEFAULT_SHORT_FLAG = "-"; - this.DEFAULT_LONG_FLAG = "--"; - this.unnamed = []; - this.options = []; - } - OptionsParser.prototype.findOption = function (arg) { - for(var i = 0; i < this.options.length; i++) { - if(arg === this.options[i].short || arg === this.options[i].name) { - return this.options[i]; - } - } - return null; - }; - OptionsParser.prototype.printUsage = function () { - this.host.printLine("Syntax: tsc [options] [file ..]"); - this.host.printLine(""); - this.host.printLine("Examples: tsc hello.ts"); - this.host.printLine(" tsc --out foo.js foo.ts"); - this.host.printLine(" tsc @args.txt"); - this.host.printLine(""); - this.host.printLine("Options:"); - var output = []; - var maxLength = 0; - this.options = this.options.sort(function (a, b) { - var aName = a.name.toLowerCase(); - var bName = b.name.toLowerCase(); - if(aName > bName) { - return 1; - } else { - if(aName < bName) { - return -1; - } else { - return 0; - } - } - }); - for(var i = 0; i < this.options.length; i++) { - var option = this.options[i]; - if(option.experimental) { - continue; - } - if(!option.usage) { - break; - } - var usageString = " "; - var type = option.type ? " " + option.type.toUpperCase() : ""; - if(option.short) { - usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; - } - usageString += this.DEFAULT_LONG_FLAG + option.name + type; - output.push([ - usageString, - option.usage - ]); - if(usageString.length > maxLength) { - maxLength = usageString.length; - } - } - output.push([ - " @", - "Insert command line options and files from a file." - ]); - for(var i = 0; i < output.length; i++) { - this.host.printLine(output[i][0] + (new Array(maxLength - output[i][0].length + 3)).join(" ") + output[i][1]); - } - }; - OptionsParser.prototype.option = function (name, config, short) { - if(!config) { - config = short; - short = null; - } - config.name = name; - config.short = short; - config.flag = false; - this.options.push(config); - }; - OptionsParser.prototype.flag = function (name, config, short) { - if(!config) { - config = short; - short = null; - } - config.name = name; - config.short = short; - config.flag = true; - this.options.push(config); - }; - OptionsParser.prototype.parseString = function (argString) { - var position = 0; - var tokens = argString.match(/\s+|"|[^\s"]+/g); - function peek() { - return tokens[position]; - } - function consume() { - return tokens[position++]; - } - function consumeQuotedString() { - var value = ''; - consume(); - var token = peek(); - while(token && token !== '"') { - consume(); - value += token; - token = peek(); - } - consume(); - return value; - } - var args = []; - var currentArg = ''; - while(position < tokens.length) { - var token = peek(); - if(token === '"') { - currentArg += consumeQuotedString(); - } else { - if(token.match(/\s/)) { - if(currentArg.length > 0) { - args.push(currentArg); - currentArg = ''; - } - consume(); - } else { - consume(); - currentArg += token; - } - } - } - if(currentArg.length > 0) { - args.push(currentArg); - } - this.parse(args); - }; - OptionsParser.prototype.parse = function (args) { - var position = 0; - function consume() { - return args[position++]; - } - while(position < args.length) { - var current = consume(); - var match = current.match(/^(--?|@)(.*)/); - var value = null; - if(match) { - if(match[1] === '@') { - this.parseString(this.host.readFile(match[2])); - } else { - var arg = match[2]; - var option = this.findOption(arg); - if(option === null) { - this.host.printLine("Unknown option '" + arg + "'"); - this.host.printLine("Use the '--help' flag to see options"); - } else { - if(!option.flag) { - value = consume(); - } - option.set(value); - } - } - } else { - this.unnamed.push(current); - } - } - }; - return OptionsParser; -})(); -var CommandLineHost = (function () { - function CommandLineHost(compilationSettings) { - this.compilationSettings = compilationSettings; - this.pathMap = { - }; - this.resolvedPaths = { - }; - } - CommandLineHost.prototype.getPathIdentifier = function (path) { - return this.compilationSettings.useCaseSensitiveFileResolution ? path : path.toLocaleUpperCase(); - }; - CommandLineHost.prototype.isResolved = function (path) { - return this.resolvedPaths[this.getPathIdentifier(this.pathMap[path])] != undefined; - }; - CommandLineHost.prototype.resolveCompilationEnvironment = function (preEnv, resolver, traceDependencies) { - var _this = this; - var resolvedEnv = new TypeScript.CompilationEnvironment(preEnv.compilationSettings, preEnv.ioHost); - var nCode = preEnv.code.length; - var path = ""; - var postResolutionError = function (errorFile, errorMessage) { - TypeScript.CompilerDiagnostics.debugPrint("Could not resolve file '" + errorFile + "'" + (errorMessage == "" ? "" : ": " + errorMessage)); - }; - var resolutionDispatcher = { - postResolutionError: postResolutionError, - postResolution: function (path, code) { - var pathId = _this.getPathIdentifier(path); - if(!_this.resolvedPaths[pathId]) { - resolvedEnv.code.push(code); - _this.resolvedPaths[pathId] = true; - } - } - }; - for(var i = 0; i < nCode; i++) { - path = TypeScript.switchToForwardSlashes(preEnv.ioHost.resolvePath(preEnv.code[i].path)); - this.pathMap[preEnv.code[i].path] = path; - resolver.resolveCode(path, "", false, resolutionDispatcher); - } - return resolvedEnv; - }; - return CommandLineHost; -})(); -var BatchCompiler = (function () { - function BatchCompiler(ioHost) { - this.ioHost = ioHost; - this.resolvedEnvironment = null; - this.hasResolveErrors = false; - this.compilerVersion = "0.8.2.0"; - this.printedVersion = false; - this.compilationSettings = new TypeScript.CompilationSettings(); - this.compilationEnvironment = new TypeScript.CompilationEnvironment(this.compilationSettings, this.ioHost); - } - BatchCompiler.prototype.resolve = function () { - var resolver = new TypeScript.CodeResolver(this.compilationEnvironment); - var commandLineHost = new CommandLineHost(this.compilationSettings); - var ret = commandLineHost.resolveCompilationEnvironment(this.compilationEnvironment, resolver, true); - this.hasResolveErrors = false; - for(var i = 0; i < this.compilationEnvironment.code.length; i++) { - if(!commandLineHost.isResolved(this.compilationEnvironment.code[i].path)) { - this.hasResolveErrors = true; - var path = this.compilationEnvironment.code[i].path; - if(!TypeScript.isSTRFile(path) && !TypeScript.isDSTRFile(path) && !TypeScript.isTSFile(path) && !TypeScript.isDTSFile(path)) { - this.ioHost.stderr.WriteLine("Unknown extension for file: \"" + path + "\". Only .ts and .d.ts extensions are allowed."); - } else { - this.ioHost.stderr.WriteLine("Error reading file \"" + path + "\": File not found"); - } - } - } - return ret; - }; - BatchCompiler.prototype.compile = function () { - var _this = this; - var compiler; - compiler = new TypeScript.TypeScriptCompiler(this.ioHost.stderr, new TypeScript.NullLogger(), this.compilationSettings); - compiler.setErrorOutput(this.ioHost.stderr); - compiler.setErrorCallback(function (minChar, charLen, message, unitIndex) { - compiler.errorReporter.hasErrors = true; - var fname = _this.resolvedEnvironment.code[unitIndex].path; - var lineCol = { - line: -1, - col: -1 - }; - compiler.parser.getSourceLineCol(lineCol, minChar); - var msg = fname + " (" + lineCol.line + "," + (lineCol.col + 1) + "): " + message; - if(_this.compilationSettings.errorRecovery) { - _this.ioHost.stderr.WriteLine(msg); - } else { - throw new SyntaxError(msg); - } - }); - if(this.compilationSettings.emitComments) { - compiler.emitCommentsToOutput(); - } - var consumeUnit = function (code, addAsResident) { - try { - if(!_this.compilationSettings.resolve) { - code.content = _this.ioHost.readFile(code.path); - if(_this.compilationSettings.generateDeclarationFiles) { - TypeScript.CompilerDiagnostics.assert(code.referencedFiles == null, "With no resolve option, referenced files need to null"); - code.referencedFiles = TypeScript.getReferencedFiles(code); - } - } - if(code.content) { - if(_this.compilationSettings.parseOnly) { - compiler.parseUnit(code.content, code.path); - } else { - if(_this.compilationSettings.errorRecovery) { - compiler.parser.setErrorRecovery(_this.ioHost.stderr); - } - compiler.addUnit(code.content, code.path, addAsResident, code.referencedFiles); - } - } - } catch (err) { - compiler.errorReporter.hasErrors = true; - _this.ioHost.stderr.WriteLine(err.message); - } - }; - for(var iCode = 0; iCode < this.resolvedEnvironment.code.length; iCode++) { - if(!this.compilationSettings.parseOnly || (iCode > 0)) { - consumeUnit(this.resolvedEnvironment.code[iCode], false); - } - } - var emitterIOHost = { - createFile: function (fileName, useUTF8) { - return IOUtils.createFileAndFolderStructure(_this.ioHost, fileName, useUTF8); - }, - directoryExists: this.ioHost.directoryExists, - fileExists: this.ioHost.fileExists, - resolvePath: this.ioHost.resolvePath - }; - try { - if(!this.compilationSettings.parseOnly) { - compiler.typeCheck(); - compiler.emit(emitterIOHost); - compiler.emitDeclarations(); - } else { - compiler.emitAST(emitterIOHost); - } - } catch (err) { - compiler.errorReporter.hasErrors = true; - if(err.message != "EmitError") { - throw err; - } - } - return compiler.errorReporter.hasErrors; - }; - BatchCompiler.prototype.run = function () { - for(var i = 0; i < this.compilationEnvironment.code.length; i++) { - var unit = this.compilationEnvironment.code[i]; - var outputFileName = unit.path; - if(TypeScript.isTSFile(outputFileName)) { - outputFileName = outputFileName.replace(/\.ts$/, ".js"); - } else { - if(TypeScript.isSTRFile(outputFileName)) { - outputFileName = outputFileName.replace(/\.str$/, ".js"); - } - } - if(this.ioHost.fileExists(outputFileName)) { - var unitRes = this.ioHost.readFile(outputFileName); - this.ioHost.run(unitRes, outputFileName); - } - } - }; - BatchCompiler.prototype.batchCompile = function () { - var _this = this; - TypeScript.CompilerDiagnostics.diagnosticWriter = { - Alert: function (s) { - _this.ioHost.printLine(s); - } - }; - var code; - var opts = new OptionsParser(this.ioHost); - opts.option('out', { - usage: 'Concatenate and emit output to single file | Redirect output structure to the directory', - type: 'file|directory', - set: function (str) { - _this.compilationSettings.outputOption = str; - } - }); - opts.option('style', { - usage: 'Select style checking options (examples --style requireSemi:off or --style "eqeqeq;bitwise:off")', - experimental: true, - set: function (str) { - _this.compilationSettings.setStyleOptions(str); - } - }); - opts.flag('sourcemap', { - usage: 'Generates corresponding .map file', - set: function () { - _this.compilationSettings.mapSourceFiles = true; - } - }); - opts.flag('declaration', { - usage: 'Generates corresponding .d.ts file', - set: function () { - _this.compilationSettings.generateDeclarationFiles = true; - } - }); - if(this.ioHost.watchFile) { - opts.flag('watch', { - usage: 'Watch output files', - set: function () { - _this.compilationSettings.watch = true; - } - }, 'w'); - } - opts.flag('exec', { - usage: 'Execute the script after compilation', - set: function () { - _this.compilationSettings.exec = true; - } - }, 'e'); - opts.flag('parse', { - usage: 'Parse only', - experimental: true, - set: function () { - _this.compilationSettings.parseOnly = true; - } - }); - opts.flag('minw', { - usage: 'Minimize whitespace', - experimental: true, - set: function () { - _this.compilationSettings.minWhitespace = true; - } - }, 'mw'); - opts.flag('const', { - usage: 'Propagate constants to emitted code', - experimental: true, - set: function () { - _this.compilationSettings.propagateConstants = true; - } - }); - opts.flag('errorrecovery', { - usage: 'Enable error recovery', - experimental: true, - set: function () { - _this.compilationSettings.errorRecovery = true; - } - }, 'er'); - opts.flag('comments', { - usage: 'Emit comments to output', - set: function () { - _this.compilationSettings.emitComments = true; - } - }, 'c'); - opts.flag('cflow', { - usage: 'Control flow', - experimental: true, - set: function () { - _this.compilationSettings.controlFlow = true; - } - }); - opts.flag('cflowp', { - usage: 'Print control flow', - experimental: true, - set: function () { - _this.compilationSettings.controlFlow = true; - _this.compilationSettings.printControlFlow = true; - } - }); - opts.flag('cflowu', { - usage: 'Print Use Def control flow', - experimental: true, - set: function () { - _this.compilationSettings.controlFlow = true; - _this.compilationSettings.controlFlowUseDef = true; - } - }); - opts.flag('noerroronwith', { - usage: 'Allow with statements', - experimental: true, - set: function () { - _this.compilationSettings.errorOnWith = false; - } - }); - opts.flag('noresolve', { - usage: 'Skip resolution and preprocessing', - experimental: true, - set: function () { - _this.compilationSettings.resolve = false; - _this.compilationSettings.preprocess = false; - } - }); - opts.flag('debug', { - usage: 'Print debug output', - experimental: true, - set: function () { - TypeScript.CompilerDiagnostics.debug = true; - } - }); - opts.flag('canCallDefinitionSignature', { - usage: 'Allows you to call the definition signature of an overload group', - experimental: true, - set: function () { - _this.compilationSettings.canCallDefinitionSignature = true; - } - }); - opts.flag('nooptimizemodules', { - usage: 'Do not optimize module codegen', - experimental: true, - set: function () { - TypeScript.optimizeModuleCodeGen = false; - } - }); - opts.flag('nolib', { - usage: 'Do not include a default lib.d.ts with global declarations', - set: function () { - _this.compilationSettings.useDefaultLib = false; - } - }); - opts.flag('inferProperties', { - usage: 'Infer class properties from top-level assignments to \'this\'', - experimental: true, - set: function () { - _this.compilationSettings.inferPropertiesFromThisAssignment = true; - } - }); - opts.option('target', { - usage: 'Specify ECMAScript target version: "ES3" (default), or "ES5"', - type: 'VER', - set: function (type) { - type = type.toLowerCase(); - if(type === 'es3') { - _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES3; - } else { - if(type === 'es5') { - _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES5; - } else { - _this.ioHost.printLine("ECMAScript target version '" + type + "' not supported. Using default 'ES3' code generation"); - } - } - } - }); - opts.option('module', { - usage: 'Specify module code generation: "commonjs" (default) or "amd"', - type: 'kind', - set: function (type) { - type = type.toLowerCase(); - if(type === 'commonjs' || type === 'node') { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; - } else { - if(type === 'amd') { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Asynchronous; - } else { - _this.ioHost.printLine("Module code generation '" + type + "' not supported. Using default 'commonjs' code generation"); - } - } - } - }); - var printedUsage = false; - opts.flag('help', { - usage: 'Print this message', - set: function () { - _this.printVersion(); - opts.printUsage(); - printedUsage = true; - } - }, 'h'); - opts.flag('useCaseSensitiveFileResolution', { - usage: 'Force file resolution to be case sensitive', - experimental: true, - set: function () { - _this.compilationSettings.useCaseSensitiveFileResolution = true; - } - }); - opts.flag('version', { - usage: 'Print the compiler\'s version: ' + this.compilerVersion, - set: function () { - _this.printVersion(); - } - }, 'v'); - opts.parse(this.ioHost.arguments); - if(this.compilationSettings.useDefaultLib) { - var compilerFilePath = this.ioHost.getExecutingFilePath(); - var binDirPath = this.ioHost.dirName(compilerFilePath); - var libStrPath = this.ioHost.resolvePath(binDirPath + "/lib.d.ts"); - code = new TypeScript.SourceUnit(libStrPath, null); - this.compilationEnvironment.code.push(code); - } - for(var i = 0; i < opts.unnamed.length; i++) { - code = new TypeScript.SourceUnit(opts.unnamed[i], null); - this.compilationEnvironment.code.push(code); - } - if(this.compilationEnvironment.code.length == (this.compilationSettings.useDefaultLib ? 1 : 0)) { - if(!printedUsage && !this.printedVersion) { - this.printVersion(); - opts.printUsage(); - this.ioHost.quit(1); - } - return; - } - var sourceFiles = []; - if(this.compilationSettings.watch) { - sourceFiles = this.compilationEnvironment.code.slice(0); - } - this.resolvedEnvironment = this.compilationSettings.resolve ? this.resolve() : this.compilationEnvironment; - var hasCompileErrors = this.compile(); - var hasErrors = hasCompileErrors || this.hasResolveErrors; - if(!hasErrors) { - if(this.compilationSettings.exec) { - this.run(); - } - } - if(this.compilationSettings.watch) { - this.watchFiles(sourceFiles); - } else { - this.ioHost.quit(hasErrors ? 1 : 0); - } - }; - BatchCompiler.prototype.printVersion = function () { - if(!this.printedVersion) { - this.ioHost.printLine("Version " + this.compilerVersion); - this.printedVersion = true; - } - }; - BatchCompiler.prototype.watchFiles = function (soruceFiles) { - var _this = this; - if(!this.ioHost.watchFile) { - this.ioHost.printLine("Error: Current host does not support -w[atch] option"); - return; - } - var resolvedFiles = []; - var watchers = { - }; - var addWatcher = function (filename) { - if(!watchers[filename]) { - var watcher = _this.ioHost.watchFile(filename, onWatchedFileChange); - watchers[filename] = watcher; - } else { - throw new Error("Cannot watch file, it is already watched."); - } - }; - var removeWatcher = function (filename) { - if(watchers[filename]) { - watchers[filename].close(); - delete watchers[filename]; - } else { - throw new Error("Cannot stop watching file, it is not being watched."); - } - }; - var onWatchedFileChange = function () { - _this.compilationEnvironment.code = soruceFiles; - _this.resolvedEnvironment = _this.compilationSettings.resolve ? _this.resolve() : _this.compilationEnvironment; - var oldFiles = resolvedFiles; - var newFiles = []; - _this.resolvedEnvironment.code.forEach(function (sf) { - return newFiles.push(sf.path); - }); - newFiles = newFiles.sort(); - var i = 0, j = 0; - while(i < oldFiles.length && j < newFiles.length) { - var compareResult = oldFiles[i].localeCompare(newFiles[j]); - if(compareResult == 0) { - i++; - j++; - } else { - if(compareResult < 0) { - removeWatcher(oldFiles[i]); - i++; - } else { - addWatcher(newFiles[j]); - j++; - } - } - } - for(var k = i; k < oldFiles.length; k++) { - removeWatcher(oldFiles[k]); - } - for(var k = j; k < newFiles.length; k++) { - addWatcher(newFiles[k]); - } - resolvedFiles = newFiles; - ; ; - _this.ioHost.printLine(""); - _this.ioHost.printLine("Recompiling (" + new Date() + "): "); - resolvedFiles.forEach(function (f) { - return _this.ioHost.printLine(" " + f); - }); - var hasCompileErrors = _this.compile(); - var hasErrors = hasCompileErrors || _this.hasResolveErrors; - if(!hasErrors) { - if(_this.compilationSettings.exec) { - _this.run(); - } - } - }; - this.ioHost.stderr = this.ioHost.stdout; - this.resolvedEnvironment.code.forEach(function (sf) { - resolvedFiles.push(sf.path); - addWatcher(sf.path); - }); - resolvedFiles.sort(); - }; - return BatchCompiler; -})(); -var batch = new BatchCompiler(IO); -batch.batchCompile(); diff --git a/_infrastructure/tests/typescript_0.8.2/typescript.js b/_infrastructure/tests/typescript_0.8.2/typescript.js deleted file mode 100644 index 4a902f5b7..000000000 --- a/_infrastructure/tests/typescript_0.8.2/typescript.js +++ /dev/null @@ -1,24654 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -var TypeScript; -(function (TypeScript) { - function hasFlag(val, flag) { - return (val & flag) != 0; - } - TypeScript.hasFlag = hasFlag; - (function (ErrorRecoverySet) { - ErrorRecoverySet._map = []; - ErrorRecoverySet.None = 0; - ErrorRecoverySet.Comma = 1; - ErrorRecoverySet.SColon = 1 << 1; - ErrorRecoverySet.Asg = 1 << 2; - ErrorRecoverySet.BinOp = 1 << 3; - ErrorRecoverySet.RBrack = 1 << 4; - ErrorRecoverySet.RCurly = 1 << 5; - ErrorRecoverySet.RParen = 1 << 6; - ErrorRecoverySet.Dot = 1 << 7; - ErrorRecoverySet.Colon = 1 << 8; - ErrorRecoverySet.PrimType = 1 << 9; - ErrorRecoverySet.AddOp = 1 << 10; - ErrorRecoverySet.LCurly = 1 << 11; - ErrorRecoverySet.PreOp = 1 << 12; - ErrorRecoverySet.RegExp = 1 << 13; - ErrorRecoverySet.LParen = 1 << 14; - ErrorRecoverySet.LBrack = 1 << 15; - ErrorRecoverySet.Scope = 1 << 16; - ErrorRecoverySet.In = 1 << 17; - ErrorRecoverySet.SCase = 1 << 18; - ErrorRecoverySet.Else = 1 << 19; - ErrorRecoverySet.Catch = 1 << 20; - ErrorRecoverySet.Var = 1 << 21; - ErrorRecoverySet.Stmt = 1 << 22; - ErrorRecoverySet.While = 1 << 23; - ErrorRecoverySet.ID = 1 << 24; - ErrorRecoverySet.Prefix = 1 << 25; - ErrorRecoverySet.Literal = 1 << 26; - ErrorRecoverySet.RLit = 1 << 27; - ErrorRecoverySet.Func = 1 << 28; - ErrorRecoverySet.EOF = 1 << 29; - ErrorRecoverySet.TypeScriptS = 1 << 30; - ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; - ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; - ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; - })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); - var ErrorRecoverySet = TypeScript.ErrorRecoverySet; - (function (AllowedElements) { - AllowedElements._map = []; - AllowedElements.None = 0; - AllowedElements.ModuleDeclarations = 1 << 2; - AllowedElements.ClassDeclarations = 1 << 3; - AllowedElements.InterfaceDeclarations = 1 << 4; - AllowedElements.AmbientDeclarations = 1 << 10; - AllowedElements.Properties = 1 << 11; - AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; - AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; - })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); - var AllowedElements = TypeScript.AllowedElements; - (function (Modifiers) { - Modifiers._map = []; - Modifiers.None = 0; - Modifiers.Private = 1; - Modifiers.Public = 1 << 1; - Modifiers.Readonly = 1 << 2; - Modifiers.Ambient = 1 << 3; - Modifiers.Exported = 1 << 4; - Modifiers.Getter = 1 << 5; - Modifiers.Setter = 1 << 6; - Modifiers.Static = 1 << 7; - })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); - var Modifiers = TypeScript.Modifiers; - (function (ASTFlags) { - ASTFlags._map = []; - ASTFlags.None = 0; - ASTFlags.ExplicitSemicolon = 1; - ASTFlags.AutomaticSemicolon = 1 << 1; - ASTFlags.Writeable = 1 << 2; - ASTFlags.Error = 1 << 3; - ASTFlags.DotLHSPartial = 1 << 4; - ASTFlags.DotLHS = 1 << 5; - ASTFlags.IsStatement = 1 << 6; - ASTFlags.StrictMode = 1 << 7; - ASTFlags.PossibleOptionalParameter = 1 << 8; - ASTFlags.ClassBaseConstructorCall = 1 << 9; - ASTFlags.OptionalName = 1 << 10; - ASTFlags.SkipNextRParen = 1 << 11; - })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); - var ASTFlags = TypeScript.ASTFlags; - (function (DeclFlags) { - DeclFlags._map = []; - DeclFlags.None = 0; - DeclFlags.Exported = 1; - DeclFlags.Private = 1 << 1; - DeclFlags.Public = 1 << 2; - DeclFlags.Ambient = 1 << 3; - DeclFlags.Static = 1 << 4; - DeclFlags.LocalStatic = 1 << 5; - DeclFlags.GetAccessor = 1 << 6; - DeclFlags.SetAccessor = 1 << 7; - })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); - var DeclFlags = TypeScript.DeclFlags; - (function (ModuleFlags) { - ModuleFlags._map = []; - ModuleFlags.None = 0; - ModuleFlags.Exported = 1; - ModuleFlags.Private = 1 << 1; - ModuleFlags.Public = 1 << 2; - ModuleFlags.Ambient = 1 << 3; - ModuleFlags.Static = 1 << 4; - ModuleFlags.LocalStatic = 1 << 5; - ModuleFlags.GetAccessor = 1 << 6; - ModuleFlags.SetAccessor = 1 << 7; - ModuleFlags.IsEnum = 1 << 8; - ModuleFlags.ShouldEmitModuleDecl = 1 << 9; - ModuleFlags.IsWholeFile = 1 << 10; - ModuleFlags.IsDynamic = 1 << 11; - ModuleFlags.MustCaptureThis = 1 << 12; - })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); - var ModuleFlags = TypeScript.ModuleFlags; - (function (SymbolFlags) { - SymbolFlags._map = []; - SymbolFlags.None = 0; - SymbolFlags.Exported = 1; - SymbolFlags.Private = 1 << 1; - SymbolFlags.Public = 1 << 2; - SymbolFlags.Ambient = 1 << 3; - SymbolFlags.Static = 1 << 4; - SymbolFlags.LocalStatic = 1 << 5; - SymbolFlags.GetAccessor = 1 << 6; - SymbolFlags.SetAccessor = 1 << 7; - SymbolFlags.Property = 1 << 8; - SymbolFlags.Readonly = 1 << 9; - SymbolFlags.ModuleMember = 1 << 10; - SymbolFlags.InterfaceMember = 1 << 11; - SymbolFlags.ClassMember = 1 << 12; - SymbolFlags.BuiltIn = 1 << 13; - SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; - SymbolFlags.Constant = 1 << 15; - SymbolFlags.Optional = 1 << 16; - SymbolFlags.RecursivelyReferenced = 1 << 17; - SymbolFlags.Bound = 1 << 18; - SymbolFlags.CompilerGenerated = 1 << 19; - })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); - var SymbolFlags = TypeScript.SymbolFlags; - (function (VarFlags) { - VarFlags._map = []; - VarFlags.None = 0; - VarFlags.Exported = 1; - VarFlags.Private = 1 << 1; - VarFlags.Public = 1 << 2; - VarFlags.Ambient = 1 << 3; - VarFlags.Static = 1 << 4; - VarFlags.LocalStatic = 1 << 5; - VarFlags.GetAccessor = 1 << 6; - VarFlags.SetAccessor = 1 << 7; - VarFlags.AutoInit = 1 << 8; - VarFlags.Property = 1 << 9; - VarFlags.Readonly = 1 << 10; - VarFlags.Class = 1 << 11; - VarFlags.ClassProperty = 1 << 12; - VarFlags.ClassBodyProperty = 1 << 13; - VarFlags.ClassConstructorProperty = 1 << 14; - VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; - VarFlags.Constant = 1 << 16; - VarFlags.MustCaptureThis = 1 << 17; - })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); - var VarFlags = TypeScript.VarFlags; - (function (FncFlags) { - FncFlags._map = []; - FncFlags.None = 0; - FncFlags.Exported = 1; - FncFlags.Private = 1 << 1; - FncFlags.Public = 1 << 2; - FncFlags.Ambient = 1 << 3; - FncFlags.Static = 1 << 4; - FncFlags.LocalStatic = 1 << 5; - FncFlags.GetAccessor = 1 << 6; - FncFlags.SetAccessor = 1 << 7; - FncFlags.Definition = 1 << 8; - FncFlags.Signature = 1 << 9; - FncFlags.Method = 1 << 10; - FncFlags.HasReturnExpression = 1 << 11; - FncFlags.CallMember = 1 << 12; - FncFlags.ConstructMember = 1 << 13; - FncFlags.HasSelfReference = 1 << 14; - FncFlags.IsFatArrowFunction = 1 << 15; - FncFlags.IndexerMember = 1 << 16; - FncFlags.IsFunctionExpression = 1 << 17; - FncFlags.ClassMethod = 1 << 18; - FncFlags.ClassPropertyMethodExported = 1 << 19; - FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; - FncFlags.IsPropertyBound = 1 << 21; - })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); - var FncFlags = TypeScript.FncFlags; - (function (SignatureFlags) { - SignatureFlags._map = []; - SignatureFlags.None = 0; - SignatureFlags.IsIndexer = 1; - SignatureFlags.IsStringIndexer = 1 << 1; - SignatureFlags.IsNumberIndexer = 1 << 2; - })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); - var SignatureFlags = TypeScript.SignatureFlags; - function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { - return fncOrVarOrSymbolOrModuleFlags; - } - TypeScript.ToDeclFlags = ToDeclFlags; - (function (TypeFlags) { - TypeFlags._map = []; - TypeFlags.None = 0; - TypeFlags.HasImplementation = 1; - TypeFlags.HasSelfReference = 1 << 1; - TypeFlags.MergeResult = 1 << 2; - TypeFlags.IsEnum = 1 << 3; - TypeFlags.BuildingName = 1 << 4; - TypeFlags.HasBaseType = 1 << 5; - TypeFlags.HasBaseTypeOfObject = 1 << 6; - TypeFlags.IsClass = 1 << 7; - })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); - var TypeFlags = TypeScript.TypeFlags; - (function (TypeRelationshipFlags) { - TypeRelationshipFlags._map = []; - TypeRelationshipFlags.SuccessfulComparison = 0; - TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; - TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; - TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; - TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; - TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; - TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; - TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; - })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); - var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; - (function (CodeGenTarget) { - CodeGenTarget._map = []; - CodeGenTarget.ES3 = 0; - CodeGenTarget.ES5 = 1; - })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); - var CodeGenTarget = TypeScript.CodeGenTarget; - (function (ModuleGenTarget) { - ModuleGenTarget._map = []; - ModuleGenTarget.Synchronous = 0; - ModuleGenTarget.Asynchronous = 1; - ModuleGenTarget.Local = 1 << 1; - })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); - var ModuleGenTarget = TypeScript.ModuleGenTarget; - TypeScript.codeGenTarget = CodeGenTarget.ES3; - TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; - TypeScript.optimizeModuleCodeGen = true; - function flagsToString(e, flags) { - var builder = ""; - for(var i = 1; i < (1 << 31); i = i << 1) { - if((flags & i) != 0) { - for(var k in e) { - if(e[k] == i) { - if(builder.length > 0) { - builder += "|"; - } - builder += k; - break; - } - } - } - } - return builder; - } - TypeScript.flagsToString = flagsToString; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (NodeType) { - NodeType._map = []; - NodeType._map[0] = "None"; - NodeType.None = 0; - NodeType._map[1] = "Empty"; - NodeType.Empty = 1; - NodeType._map[2] = "EmptyExpr"; - NodeType.EmptyExpr = 2; - NodeType._map[3] = "True"; - NodeType.True = 3; - NodeType._map[4] = "False"; - NodeType.False = 4; - NodeType._map[5] = "This"; - NodeType.This = 5; - NodeType._map[6] = "Super"; - NodeType.Super = 6; - NodeType._map[7] = "QString"; - NodeType.QString = 7; - NodeType._map[8] = "Regex"; - NodeType.Regex = 8; - NodeType._map[9] = "Null"; - NodeType.Null = 9; - NodeType._map[10] = "ArrayLit"; - NodeType.ArrayLit = 10; - NodeType._map[11] = "ObjectLit"; - NodeType.ObjectLit = 11; - NodeType._map[12] = "Void"; - NodeType.Void = 12; - NodeType._map[13] = "Comma"; - NodeType.Comma = 13; - NodeType._map[14] = "Pos"; - NodeType.Pos = 14; - NodeType._map[15] = "Neg"; - NodeType.Neg = 15; - NodeType._map[16] = "Delete"; - NodeType.Delete = 16; - NodeType._map[17] = "Await"; - NodeType.Await = 17; - NodeType._map[18] = "In"; - NodeType.In = 18; - NodeType._map[19] = "Dot"; - NodeType.Dot = 19; - NodeType._map[20] = "From"; - NodeType.From = 20; - NodeType._map[21] = "Is"; - NodeType.Is = 21; - NodeType._map[22] = "InstOf"; - NodeType.InstOf = 22; - NodeType._map[23] = "Typeof"; - NodeType.Typeof = 23; - NodeType._map[24] = "NumberLit"; - NodeType.NumberLit = 24; - NodeType._map[25] = "Name"; - NodeType.Name = 25; - NodeType._map[26] = "TypeRef"; - NodeType.TypeRef = 26; - NodeType._map[27] = "Index"; - NodeType.Index = 27; - NodeType._map[28] = "Call"; - NodeType.Call = 28; - NodeType._map[29] = "New"; - NodeType.New = 29; - NodeType._map[30] = "Asg"; - NodeType.Asg = 30; - NodeType._map[31] = "AsgAdd"; - NodeType.AsgAdd = 31; - NodeType._map[32] = "AsgSub"; - NodeType.AsgSub = 32; - NodeType._map[33] = "AsgDiv"; - NodeType.AsgDiv = 33; - NodeType._map[34] = "AsgMul"; - NodeType.AsgMul = 34; - NodeType._map[35] = "AsgMod"; - NodeType.AsgMod = 35; - NodeType._map[36] = "AsgAnd"; - NodeType.AsgAnd = 36; - NodeType._map[37] = "AsgXor"; - NodeType.AsgXor = 37; - NodeType._map[38] = "AsgOr"; - NodeType.AsgOr = 38; - NodeType._map[39] = "AsgLsh"; - NodeType.AsgLsh = 39; - NodeType._map[40] = "AsgRsh"; - NodeType.AsgRsh = 40; - NodeType._map[41] = "AsgRs2"; - NodeType.AsgRs2 = 41; - NodeType._map[42] = "ConditionalExpression"; - NodeType.ConditionalExpression = 42; - NodeType._map[43] = "LogOr"; - NodeType.LogOr = 43; - NodeType._map[44] = "LogAnd"; - NodeType.LogAnd = 44; - NodeType._map[45] = "Or"; - NodeType.Or = 45; - NodeType._map[46] = "Xor"; - NodeType.Xor = 46; - NodeType._map[47] = "And"; - NodeType.And = 47; - NodeType._map[48] = "Eq"; - NodeType.Eq = 48; - NodeType._map[49] = "Ne"; - NodeType.Ne = 49; - NodeType._map[50] = "Eqv"; - NodeType.Eqv = 50; - NodeType._map[51] = "NEqv"; - NodeType.NEqv = 51; - NodeType._map[52] = "Lt"; - NodeType.Lt = 52; - NodeType._map[53] = "Le"; - NodeType.Le = 53; - NodeType._map[54] = "Gt"; - NodeType.Gt = 54; - NodeType._map[55] = "Ge"; - NodeType.Ge = 55; - NodeType._map[56] = "Add"; - NodeType.Add = 56; - NodeType._map[57] = "Sub"; - NodeType.Sub = 57; - NodeType._map[58] = "Mul"; - NodeType.Mul = 58; - NodeType._map[59] = "Div"; - NodeType.Div = 59; - NodeType._map[60] = "Mod"; - NodeType.Mod = 60; - NodeType._map[61] = "Lsh"; - NodeType.Lsh = 61; - NodeType._map[62] = "Rsh"; - NodeType.Rsh = 62; - NodeType._map[63] = "Rs2"; - NodeType.Rs2 = 63; - NodeType._map[64] = "Not"; - NodeType.Not = 64; - NodeType._map[65] = "LogNot"; - NodeType.LogNot = 65; - NodeType._map[66] = "IncPre"; - NodeType.IncPre = 66; - NodeType._map[67] = "DecPre"; - NodeType.DecPre = 67; - NodeType._map[68] = "IncPost"; - NodeType.IncPost = 68; - NodeType._map[69] = "DecPost"; - NodeType.DecPost = 69; - NodeType._map[70] = "TypeAssertion"; - NodeType.TypeAssertion = 70; - NodeType._map[71] = "FuncDecl"; - NodeType.FuncDecl = 71; - NodeType._map[72] = "Member"; - NodeType.Member = 72; - NodeType._map[73] = "VarDecl"; - NodeType.VarDecl = 73; - NodeType._map[74] = "ArgDecl"; - NodeType.ArgDecl = 74; - NodeType._map[75] = "Return"; - NodeType.Return = 75; - NodeType._map[76] = "Break"; - NodeType.Break = 76; - NodeType._map[77] = "Continue"; - NodeType.Continue = 77; - NodeType._map[78] = "Throw"; - NodeType.Throw = 78; - NodeType._map[79] = "For"; - NodeType.For = 79; - NodeType._map[80] = "ForIn"; - NodeType.ForIn = 80; - NodeType._map[81] = "If"; - NodeType.If = 81; - NodeType._map[82] = "While"; - NodeType.While = 82; - NodeType._map[83] = "DoWhile"; - NodeType.DoWhile = 83; - NodeType._map[84] = "Block"; - NodeType.Block = 84; - NodeType._map[85] = "Case"; - NodeType.Case = 85; - NodeType._map[86] = "Switch"; - NodeType.Switch = 86; - NodeType._map[87] = "Try"; - NodeType.Try = 87; - NodeType._map[88] = "TryCatch"; - NodeType.TryCatch = 88; - NodeType._map[89] = "TryFinally"; - NodeType.TryFinally = 89; - NodeType._map[90] = "Finally"; - NodeType.Finally = 90; - NodeType._map[91] = "Catch"; - NodeType.Catch = 91; - NodeType._map[92] = "List"; - NodeType.List = 92; - NodeType._map[93] = "Script"; - NodeType.Script = 93; - NodeType._map[94] = "ClassDeclaration"; - NodeType.ClassDeclaration = 94; - NodeType._map[95] = "InterfaceDeclaration"; - NodeType.InterfaceDeclaration = 95; - NodeType._map[96] = "ModuleDeclaration"; - NodeType.ModuleDeclaration = 96; - NodeType._map[97] = "ImportDeclaration"; - NodeType.ImportDeclaration = 97; - NodeType._map[98] = "With"; - NodeType.With = 98; - NodeType._map[99] = "Label"; - NodeType.Label = 99; - NodeType._map[100] = "LabeledStatement"; - NodeType.LabeledStatement = 100; - NodeType._map[101] = "EBStart"; - NodeType.EBStart = 101; - NodeType._map[102] = "GotoEB"; - NodeType.GotoEB = 102; - NodeType._map[103] = "EndCode"; - NodeType.EndCode = 103; - NodeType._map[104] = "Error"; - NodeType.Error = 104; - NodeType._map[105] = "Comment"; - NodeType.Comment = 105; - NodeType._map[106] = "Debugger"; - NodeType.Debugger = 106; - NodeType.GeneralNode = NodeType.FuncDecl; - NodeType.LastAsg = NodeType.AsgRs2; - })(TypeScript.NodeType || (TypeScript.NodeType = {})); - var NodeType = TypeScript.NodeType; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var BlockIntrinsics = (function () { - function BlockIntrinsics() { - this.prototype = undefined; - this.toString = undefined; - this.toLocaleString = undefined; - this.valueOf = undefined; - this.hasOwnProperty = undefined; - this.propertyIsEnumerable = undefined; - this.isPrototypeOf = undefined; - this["constructor"] = undefined; - } - return BlockIntrinsics; - })(); - TypeScript.BlockIntrinsics = BlockIntrinsics; - var StringHashTable = (function () { - function StringHashTable() { - this.itemCount = 0; - this.table = (new BlockIntrinsics()); - } - StringHashTable.prototype.getAllKeys = function () { - var result = []; - for(var k in this.table) { - if(this.table[k] != undefined) { - result[result.length] = k; - } - } - return result; - }; - StringHashTable.prototype.add = function (key, data) { - if(this.table[key] != undefined) { - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.table[key] != undefined) { - this.table[key] = data; - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.map = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - fn(k, this.table[k], context); - } - } - }; - StringHashTable.prototype.every = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(!fn(k, this.table[k], context)) { - return false; - } - } - } - return true; - }; - StringHashTable.prototype.some = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(fn(k, this.table[k], context)) { - return true; - } - } - } - return false; - }; - StringHashTable.prototype.count = function () { - return this.itemCount; - }; - StringHashTable.prototype.lookup = function (key) { - var data = this.table[key]; - if(data != undefined) { - return data; - } else { - return (null); - } - }; - return StringHashTable; - })(); - TypeScript.StringHashTable = StringHashTable; - var DualStringHashTable = (function () { - function DualStringHashTable(primaryTable, secondaryTable) { - this.primaryTable = primaryTable; - this.secondaryTable = secondaryTable; - this.insertPrimary = true; - } - DualStringHashTable.prototype.getAllKeys = function () { - return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); - }; - DualStringHashTable.prototype.add = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.add(key, data); - } else { - return this.secondaryTable.add(key, data); - } - }; - DualStringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.addOrUpdate(key, data); - } else { - return this.secondaryTable.addOrUpdate(key, data); - } - }; - DualStringHashTable.prototype.map = function (fn, context) { - this.primaryTable.map(fn, context); - this.secondaryTable.map(fn, context); - }; - DualStringHashTable.prototype.every = function (fn, context) { - return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); - }; - DualStringHashTable.prototype.some = function (fn, context) { - return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); - }; - DualStringHashTable.prototype.count = function () { - return this.primaryTable.count() + this.secondaryTable.count(); - }; - DualStringHashTable.prototype.lookup = function (key) { - var data = this.primaryTable.lookup(key); - if(data != undefined) { - return data; - } else { - return this.secondaryTable.lookup(key); - } - }; - return DualStringHashTable; - })(); - TypeScript.DualStringHashTable = DualStringHashTable; - function numberHashFn(key) { - var c2 = 668265261; - key = (key ^ 61) ^ (key >>> 16); - key = key + (key << 3); - key = key ^ (key >>> 4); - key = key * c2; - key = key ^ (key >>> 15); - return key; - } - TypeScript.numberHashFn = numberHashFn; - function combineHashes(key1, key2) { - return key2 ^ ((key1 >> 5) + key1); - } - TypeScript.combineHashes = combineHashes; - var HashEntry = (function () { - function HashEntry(key, data) { - this.key = key; - this.data = data; - } - return HashEntry; - })(); - TypeScript.HashEntry = HashEntry; - var HashTable = (function () { - function HashTable(size, hashFn, equalsFn) { - this.size = size; - this.hashFn = hashFn; - this.equalsFn = equalsFn; - this.itemCount = 0; - this.table = new Array(); - for(var i = 0; i < this.size; i++) { - this.table[i] = null; - } - } - HashTable.prototype.add = function (key, data) { - var current; - var entry = new HashEntry(key, data); - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return false; - } - } - entry.next = this.table[val]; - this.table[val] = entry; - this.itemCount++; - return true; - }; - HashTable.prototype.remove = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - var result = null; - var prevEntry = null; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - result = current.data; - this.itemCount--; - if(prevEntry) { - prevEntry.next = current.next; - } else { - this.table[val] = current.next; - } - break; - } - prevEntry = current; - } - return result; - }; - HashTable.prototype.count = function () { - return this.itemCount; - }; - HashTable.prototype.lookup = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return (current.data); - } - } - return (null); - }; - return HashTable; - })(); - TypeScript.HashTable = HashTable; - var SimpleHashTable = (function () { - function SimpleHashTable() { - this.keys = []; - this.values = []; - } - SimpleHashTable.prototype.lookup = function (key, findValue) { - var searchArray = this.keys; - if(findValue) { - searchArray = this.values; - } - for(var i = 0; i < searchArray.length; i++) { - if(searchArray[i] == key) { - return { - key: this.keys[i], - data: this.values[i] - }; - } - } - return null; - }; - SimpleHashTable.prototype.add = function (key, data) { - var lookupData = this.lookup(key); - if(lookupData) { - return false; - } - this.keys[this.keys.length] = key; - this.values[this.values.length] = data; - return true; - }; - return SimpleHashTable; - })(); - TypeScript.SimpleHashTable = SimpleHashTable; -})(TypeScript || (TypeScript = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -var TypeScript; -(function (TypeScript) { - var ASTSpan = (function () { - function ASTSpan() { - this.minChar = -1; - this.limChar = -1; - } - return ASTSpan; - })(); - TypeScript.ASTSpan = ASTSpan; - var AST = (function (_super) { - __extends(AST, _super); - function AST(nodeType) { - _super.call(this); - this.nodeType = nodeType; - this.type = null; - this.flags = TypeScript.ASTFlags.Writeable; - this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.preComments = null; - this.postComments = null; - this.docComments = null; - this.isParenthesized = false; - } - AST.prototype.isExpression = function () { - return false; - }; - AST.prototype.isStatementOrExpression = function () { - return false; - }; - AST.prototype.isCompoundStatement = function () { - return false; - }; - AST.prototype.isLeaf = function () { - return this.isStatementOrExpression() && (!this.isCompoundStatement()); - }; - AST.prototype.isDeclaration = function () { - return false; - }; - AST.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: { - this.type = typeFlow.anyType; - break; - - } - case TypeScript.NodeType.This: { - return typeFlow.typeCheckThis(this); - - } - case TypeScript.NodeType.Null: { - this.type = typeFlow.nullType; - break; - - } - case TypeScript.NodeType.False: - case TypeScript.NodeType.True: { - this.type = typeFlow.booleanType; - break; - - } - case TypeScript.NodeType.Super: { - return typeFlow.typeCheckSuper(this); - - } - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Empty: - case TypeScript.NodeType.Void: { - this.type = typeFlow.voidType; - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - return this; - }; - AST.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - switch(this.nodeType) { - case TypeScript.NodeType.This: { - emitter.recordSourceMappingStart(this); - if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - emitter.writeToOutput("_this"); - } else { - emitter.writeToOutput("this"); - } - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.Null: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("null"); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.False: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("false"); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.True: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("true"); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.Super: { - emitter.recordSourceMappingStart(this); - emitter.emitSuperReference(); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: { - break; - - } - case TypeScript.NodeType.Empty: { - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingEnd(this); - break; - - } - case TypeScript.NodeType.Void: { - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("void "); - emitter.recordSourceMappingEnd(this); - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - emitter.emitParensAndCommentsInPlace(this, false); - }; - AST.prototype.print = function (context) { - context.startLine(); - var lineCol = { - line: -1, - col: -1 - }; - var limLineCol = { - line: -1, - col: -1 - }; - if(context.parser !== null) { - context.parser.getSourceLineCol(lineCol, this.minChar); - context.parser.getSourceLineCol(limLineCol, this.limChar); - context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); - } - var lab = this.printLabel(); - if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { - lab += " (Error)"; - } - context.writeLine(lab); - }; - AST.prototype.printLabel = function () { - if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { - return TypeScript.nodeTypeTable[this.nodeType]; - } else { - return (TypeScript.NodeType)._map[this.nodeType]; - } - }; - AST.prototype.addToControlFlow = function (context) { - context.walker.options.goChildren = false; - context.addContent(this); - }; - AST.prototype.netFreeUses = function (container, freeUses) { - }; - AST.prototype.treeViewLabel = function () { - return (TypeScript.NodeType)._map[this.nodeType]; - }; - AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { - if(!name) { - return ""; - } - var resolved = ""; - var start = 0; - var i = 0; - while(i <= name.length - 6) { - if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { - var charCode = parseInt(name.substr(i + 2, 4), 16); - resolved += name.substr(start, i - start); - resolved += String.fromCharCode(charCode); - i += 6; - start = i; - continue; - } - i++; - } - resolved += name.substring(start); - return resolved; - } - AST.prototype.getDocComments = function () { - if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { - return []; - } - if(!this.docComments) { - var preCommentsLength = this.preComments.length; - var docComments = []; - for(var i = preCommentsLength - 1; i >= 0; i--) { - if(this.preComments[i].isDocComment()) { - var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; - if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { - docComments.push(this.preComments[i]); - continue; - } - } - break; - } - this.docComments = docComments.reverse(); - } - return this.docComments; - }; - return AST; - })(ASTSpan); - TypeScript.AST = AST; - var IncompleteAST = (function (_super) { - __extends(IncompleteAST, _super); - function IncompleteAST(min, lim) { - _super.call(this, TypeScript.NodeType.Error); - this.minChar = min; - this.limChar = lim; - } - return IncompleteAST; - })(AST); - TypeScript.IncompleteAST = IncompleteAST; - var ASTList = (function (_super) { - __extends(ASTList, _super); - function ASTList() { - _super.call(this, TypeScript.NodeType.List); - this.enclosingScope = null; - this.members = new Array(); - } - ASTList.prototype.addToControlFlow = function (context) { - var len = this.members.length; - for(var i = 0; i < len; i++) { - if(context.noContinuation) { - context.addUnreachable(this.members[i]); - break; - } else { - this.members[i] = context.walk(this.members[i], this); - } - } - context.walker.options.goChildren = false; - }; - ASTList.prototype.append = function (ast) { - this.members[this.members.length] = ast; - return this; - }; - ASTList.prototype.appendAll = function (ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - for(var i = 0, len = list.members.length; i < len; i++) { - this.append(list.members[i]); - } - } else { - this.append(ast); - } - return this; - }; - ASTList.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); - emitter.recordSourceMappingEnd(this); - }; - ASTList.prototype.typeCheck = function (typeFlow) { - var len = this.members.length; - typeFlow.nestingLevel++; - for(var i = 0; i < len; i++) { - if(this.members[i]) { - this.members[i] = this.members[i].typeCheck(typeFlow); - } - } - typeFlow.nestingLevel--; - return this; - }; - return ASTList; - })(AST); - TypeScript.ASTList = ASTList; - var Identifier = (function (_super) { - __extends(Identifier, _super); - function Identifier(actualText, hasEscapeSequence) { - _super.call(this, TypeScript.NodeType.Name); - this.actualText = actualText; - this.hasEscapeSequence = hasEscapeSequence; - this.sym = null; - this.cloId = -1; - this.setText(actualText, hasEscapeSequence); - } - Identifier.prototype.setText = function (actualText, hasEscapeSequence) { - this.actualText = actualText; - if(hasEscapeSequence) { - this.text = AST.getResolvedIdentifierName(actualText); - } else { - this.text = actualText; - } - }; - Identifier.prototype.isMissing = function () { - return false; - }; - Identifier.prototype.isLeaf = function () { - return true; - }; - Identifier.prototype.treeViewLabel = function () { - return "id: " + this.actualText; - }; - Identifier.prototype.printLabel = function () { - if(this.actualText) { - return "id: " + this.actualText; - } else { - return "name node"; - } - }; - Identifier.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckName(this); - }; - Identifier.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptName(this, true); - }; - Identifier.fromToken = function fromToken(token) { - return new Identifier(token.getText(), (token).hasEscapeSequence); - } - return Identifier; - })(AST); - TypeScript.Identifier = Identifier; - var MissingIdentifier = (function (_super) { - __extends(MissingIdentifier, _super); - function MissingIdentifier() { - _super.call(this, "__missing"); - } - MissingIdentifier.prototype.isMissing = function () { - return true; - }; - MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { - }; - return MissingIdentifier; - })(Identifier); - TypeScript.MissingIdentifier = MissingIdentifier; - var Label = (function (_super) { - __extends(Label, _super); - function Label(id) { - _super.call(this, TypeScript.NodeType.Label); - this.id = id; - } - Label.prototype.printLabel = function () { - return this.id.actualText + ":"; - }; - Label.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - Label.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingStart(this.id); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this.id); - emitter.writeLineToOutput(":"); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Label; - })(AST); - TypeScript.Label = Label; - var Expression = (function (_super) { - __extends(Expression, _super); - function Expression(nodeType) { - _super.call(this, nodeType); - } - Expression.prototype.isExpression = function () { - return true; - }; - Expression.prototype.isStatementOrExpression = function () { - return true; - }; - return Expression; - })(AST); - TypeScript.Expression = Expression; - var UnaryExpression = (function (_super) { - __extends(UnaryExpression, _super); - function UnaryExpression(nodeType, operand) { - _super.call(this, nodeType); - this.operand = operand; - this.targetType = null; - this.castTerm = null; - } - UnaryExpression.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - if(this.nodeType == TypeScript.NodeType.Throw) { - context.returnStmt(); - } - }; - UnaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Not: { - return typeFlow.typeCheckBitNot(this); - - } - case TypeScript.NodeType.LogNot: { - return typeFlow.typeCheckLogNot(this); - - } - case TypeScript.NodeType.Pos: - case TypeScript.NodeType.Neg: { - return typeFlow.typeCheckUnaryNumberOperator(this); - - } - case TypeScript.NodeType.IncPost: - case TypeScript.NodeType.IncPre: - case TypeScript.NodeType.DecPost: - case TypeScript.NodeType.DecPre: { - return typeFlow.typeCheckIncOrDec(this); - - } - case TypeScript.NodeType.ArrayLit: { - typeFlow.typeCheckArrayLit(this); - return this; - - } - case TypeScript.NodeType.ObjectLit: { - typeFlow.typeCheckObjectLit(this); - return this; - - } - case TypeScript.NodeType.Throw: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.voidType; - return this; - - } - case TypeScript.NodeType.Typeof: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.stringType; - return this; - - } - case TypeScript.NodeType.Delete: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.booleanType; - break; - - } - case TypeScript.NodeType.TypeAssertion: { - this.castTerm = typeFlow.typeCheck(this.castTerm); - var applyTargetType = !this.operand.isParenthesized; - var targetType = applyTargetType ? this.castTerm.type : null; - typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); - typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); - this.type = this.castTerm.type; - return this; - - } - case TypeScript.NodeType.Void: { - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.checker.undefinedType; - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - return this; - }; - UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - switch(this.nodeType) { - case TypeScript.NodeType.IncPost: { - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - emitter.writeToOutput("++"); - break; - - } - case TypeScript.NodeType.LogNot: { - emitter.writeToOutput("!"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); - break; - - } - case TypeScript.NodeType.DecPost: { - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - emitter.writeToOutput("--"); - break; - - } - case TypeScript.NodeType.ObjectLit: { - emitter.emitObjectLiteral(this.operand); - break; - - } - case TypeScript.NodeType.ArrayLit: { - emitter.emitArrayLiteral(this.operand); - break; - - } - case TypeScript.NodeType.Not: { - emitter.writeToOutput("~"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.Neg: { - emitter.writeToOutput("-"); - if(this.operand.nodeType == TypeScript.NodeType.Neg) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); - break; - - } - case TypeScript.NodeType.Pos: { - emitter.writeToOutput("+"); - if(this.operand.nodeType == TypeScript.NodeType.Pos) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); - break; - - } - case TypeScript.NodeType.IncPre: { - emitter.writeToOutput("++"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - break; - - } - case TypeScript.NodeType.DecPre: { - emitter.writeToOutput("--"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - break; - - } - case TypeScript.NodeType.Throw: { - emitter.writeToOutput("throw "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - emitter.writeToOutput(";"); - break; - - } - case TypeScript.NodeType.Typeof: { - emitter.writeToOutput("typeof "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.Delete: { - emitter.writeToOutput("delete "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.Void: { - emitter.writeToOutput("void "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - case TypeScript.NodeType.TypeAssertion: { - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return UnaryExpression; - })(Expression); - TypeScript.UnaryExpression = UnaryExpression; - var CallExpression = (function (_super) { - __extends(CallExpression, _super); - function CallExpression(nodeType, target, arguments) { - _super.call(this, nodeType); - this.target = target; - this.arguments = arguments; - this.signature = null; - this.minChar = this.target.minChar; - } - CallExpression.prototype.typeCheck = function (typeFlow) { - if(this.nodeType == TypeScript.NodeType.New) { - return typeFlow.typeCheckNew(this); - } else { - return typeFlow.typeCheckCall(this); - } - }; - CallExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.New) { - emitter.emitNew(this.target, this.arguments); - } else { - emitter.emitCall(this, this.target, this.arguments); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return CallExpression; - })(Expression); - TypeScript.CallExpression = CallExpression; - var BinaryExpression = (function (_super) { - __extends(BinaryExpression, _super); - function BinaryExpression(nodeType, operand1, operand2) { - _super.call(this, nodeType); - this.operand1 = operand1; - this.operand2 = operand2; - } - BinaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: { - return typeFlow.typeCheckDotOperator(this); - - } - case TypeScript.NodeType.Asg: { - return typeFlow.typeCheckAsgOperator(this); - - } - case TypeScript.NodeType.Add: - case TypeScript.NodeType.Sub: - case TypeScript.NodeType.Mul: - case TypeScript.NodeType.Div: - case TypeScript.NodeType.Mod: - case TypeScript.NodeType.Or: - case TypeScript.NodeType.And: { - return typeFlow.typeCheckArithmeticOperator(this, false); - - } - case TypeScript.NodeType.Xor: { - return typeFlow.typeCheckBitwiseOperator(this, false); - - } - case TypeScript.NodeType.Ne: - case TypeScript.NodeType.Eq: { - var text; - if(typeFlow.checker.styleSettings.eqeqeq) { - text = TypeScript.nodeTypeTable[this.nodeType]; - typeFlow.checker.errorReporter.styleError(this, "use of " + text); - } else { - if(typeFlow.checker.styleSettings.eqnull) { - text = TypeScript.nodeTypeTable[this.nodeType]; - if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { - typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); - } - } - } - - } - case TypeScript.NodeType.Eqv: - case TypeScript.NodeType.NEqv: - case TypeScript.NodeType.Lt: - case TypeScript.NodeType.Le: - case TypeScript.NodeType.Ge: - case TypeScript.NodeType.Gt: { - return typeFlow.typeCheckBooleanOperator(this); - - } - case TypeScript.NodeType.Index: { - return typeFlow.typeCheckIndex(this); - - } - case TypeScript.NodeType.Member: { - this.type = typeFlow.voidType; - return this; - - } - case TypeScript.NodeType.LogOr: { - return typeFlow.typeCheckLogOr(this); - - } - case TypeScript.NodeType.LogAnd: { - return typeFlow.typeCheckLogAnd(this); - - } - case TypeScript.NodeType.AsgAdd: - case TypeScript.NodeType.AsgSub: - case TypeScript.NodeType.AsgMul: - case TypeScript.NodeType.AsgDiv: - case TypeScript.NodeType.AsgMod: - case TypeScript.NodeType.AsgOr: - case TypeScript.NodeType.AsgAnd: { - return typeFlow.typeCheckArithmeticOperator(this, true); - - } - case TypeScript.NodeType.AsgXor: { - return typeFlow.typeCheckBitwiseOperator(this, true); - - } - case TypeScript.NodeType.Lsh: - case TypeScript.NodeType.Rsh: - case TypeScript.NodeType.Rs2: { - return typeFlow.typeCheckShift(this, false); - - } - case TypeScript.NodeType.AsgLsh: - case TypeScript.NodeType.AsgRsh: - case TypeScript.NodeType.AsgRs2: { - return typeFlow.typeCheckShift(this, true); - - } - case TypeScript.NodeType.Comma: { - return typeFlow.typeCheckCommaOperator(this); - - } - case TypeScript.NodeType.InstOf: { - return typeFlow.typeCheckInstOf(this); - - } - case TypeScript.NodeType.In: { - return typeFlow.typeCheckInOperator(this); - - } - case TypeScript.NodeType.From: { - typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); - break; - - } - default: { - throw new Error("please implement in derived class"); - - } - } - return this; - }; - BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(binTokenId != undefined) { - emitter.emitJavascript(this.operand1, binTokenId, false); - if(TypeScript.tokenTable[binTokenId].text == "instanceof") { - emitter.writeToOutput(" instanceof "); - } else { - if(TypeScript.tokenTable[binTokenId].text == "in") { - emitter.writeToOutput(" in "); - } else { - emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); - } - } - emitter.emitJavascript(this.operand2, binTokenId, false); - } else { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: { - if(!emitter.tryEmitConstant(this)) { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); - emitter.writeToOutput("."); - emitter.emitJavascriptName(this.operand2, false); - } - break; - - } - case TypeScript.NodeType.Index: { - emitter.emitIndex(this.operand1, this.operand2); - break; - - } - case TypeScript.NodeType.Member: { - if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { - var funcDecl = this.operand2; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - emitter.writeToOutput("get "); - } else { - emitter.writeToOutput("set "); - } - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - } else { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - emitter.writeToOutputTrimmable(": "); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - - } - case TypeScript.NodeType.Comma: { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); - if(emitter.emitState.inObjectLiteral) { - emitter.writeLineToOutput(", "); - } else { - emitter.writeToOutput(","); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - - } - case TypeScript.NodeType.Is: { - throw new Error("should be de-sugared during type check"); - - } - default: { - throw new Error("please implement in derived class"); - - } - } - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return BinaryExpression; - })(Expression); - TypeScript.BinaryExpression = BinaryExpression; - var ConditionalExpression = (function (_super) { - __extends(ConditionalExpression, _super); - function ConditionalExpression(operand1, operand2, operand3) { - _super.call(this, TypeScript.NodeType.ConditionalExpression); - this.operand1 = operand1; - this.operand2 = operand2; - this.operand3 = operand3; - } - ConditionalExpression.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckQMark(this); - }; - ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" ? "); - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" : "); - emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ConditionalExpression; - })(Expression); - TypeScript.ConditionalExpression = ConditionalExpression; - var NumberLiteral = (function (_super) { - __extends(NumberLiteral, _super); - function NumberLiteral(value, hasEmptyFraction) { - _super.call(this, TypeScript.NodeType.NumberLit); - this.value = value; - this.hasEmptyFraction = hasEmptyFraction; - this.isNegativeZero = false; - } - NumberLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.doubleType; - return this; - }; - NumberLiteral.prototype.treeViewLabel = function () { - return "num: " + this.printLabel(); - }; - NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.isNegativeZero) { - emitter.writeToOutput("-"); - } - emitter.writeToOutput(this.value.toString()); - if(this.hasEmptyFraction) { - emitter.writeToOutput(".0"); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - NumberLiteral.prototype.printLabel = function () { - if(Math.floor(this.value) != this.value) { - return this.value.toFixed(2).toString(); - } else { - if(this.hasEmptyFraction) { - return this.value.toString() + ".0"; - } else { - return this.value.toString(); - } - } - }; - return NumberLiteral; - })(Expression); - TypeScript.NumberLiteral = NumberLiteral; - var RegexLiteral = (function (_super) { - __extends(RegexLiteral, _super); - function RegexLiteral(regex) { - _super.call(this, TypeScript.NodeType.Regex); - this.regex = regex; - } - RegexLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.regexType; - return this; - }; - RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.regex.toString()); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return RegexLiteral; - })(Expression); - TypeScript.RegexLiteral = RegexLiteral; - var StringLiteral = (function (_super) { - __extends(StringLiteral, _super); - function StringLiteral(text) { - _super.call(this, TypeScript.NodeType.QString); - this.text = text; - } - StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitStringLiteral(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - StringLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.stringType; - return this; - }; - StringLiteral.prototype.treeViewLabel = function () { - return "st: " + this.text; - }; - StringLiteral.prototype.printLabel = function () { - return this.text; - }; - return StringLiteral; - })(Expression); - TypeScript.StringLiteral = StringLiteral; - var ModuleElement = (function (_super) { - __extends(ModuleElement, _super); - function ModuleElement(nodeType) { - _super.call(this, nodeType); - } - return ModuleElement; - })(AST); - TypeScript.ModuleElement = ModuleElement; - var ImportDeclaration = (function (_super) { - __extends(ImportDeclaration, _super); - function ImportDeclaration(id, alias) { - _super.call(this, TypeScript.NodeType.ImportDeclaration); - this.id = id; - this.alias = alias; - this.varFlags = TypeScript.VarFlags.None; - this.isDynamicImport = false; - } - ImportDeclaration.prototype.isStatementOrExpression = function () { - return true; - }; - ImportDeclaration.prototype.isDeclaration = function () { - return true; - }; - ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - var mod = this.alias.type; - if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { - var prevModAliasId = emitter.modAliasId; - var prevFirstModAlias = emitter.firstModAlias; - emitter.recordSourceMappingStart(this); - emitter.emitParensAndCommentsInPlace(this, true); - emitter.writeToOutput("var " + this.id.actualText + " = "); - emitter.modAliasId = this.id.actualText; - emitter.firstModAlias = this.firstAliasedModToString(); - emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); - if(!this.isDynamicImport) { - emitter.writeToOutput(";"); - } - emitter.emitParensAndCommentsInPlace(this, false); - emitter.recordSourceMappingEnd(this); - emitter.modAliasId = prevModAliasId; - emitter.firstModAlias = prevFirstModAlias; - } - }; - ImportDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckImportDecl(this); - }; - ImportDeclaration.prototype.getAliasName = function (aliasAST) { - if (typeof aliasAST === "undefined") { aliasAST = this.alias; } - if(aliasAST.nodeType == TypeScript.NodeType.Name) { - return (aliasAST).actualText; - } else { - var dotExpr = aliasAST; - return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); - } - }; - ImportDeclaration.prototype.firstAliasedModToString = function () { - if(this.alias.nodeType == TypeScript.NodeType.Name) { - return (this.alias).actualText; - } else { - var dotExpr = this.alias; - var firstMod = dotExpr.operand1; - return firstMod.actualText; - } - }; - return ImportDeclaration; - })(ModuleElement); - TypeScript.ImportDeclaration = ImportDeclaration; - var BoundDecl = (function (_super) { - __extends(BoundDecl, _super); - function BoundDecl(id, nodeType, nestingLevel) { - _super.call(this, nodeType); - this.id = id; - this.nestingLevel = nestingLevel; - this.init = null; - this.typeExpr = null; - this.varFlags = TypeScript.VarFlags.None; - this.sym = null; - } - BoundDecl.prototype.isDeclaration = function () { - return true; - }; - BoundDecl.prototype.isStatementOrExpression = function () { - return true; - }; - BoundDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); - }; - BoundDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); - }; - BoundDecl.prototype.isProperty = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); - }; - BoundDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckBoundDecl(this); - }; - BoundDecl.prototype.printLabel = function () { - return this.treeViewLabel(); - }; - return BoundDecl; - })(AST); - TypeScript.BoundDecl = BoundDecl; - var VarDecl = (function (_super) { - __extends(VarDecl, _super); - function VarDecl(id, nest) { - _super.call(this, id, TypeScript.NodeType.VarDecl, nest); - } - VarDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - VarDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - VarDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); - }; - VarDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptVarDecl(this, tokenId); - }; - VarDecl.prototype.treeViewLabel = function () { - return "var " + this.id.actualText; - }; - return VarDecl; - })(BoundDecl); - TypeScript.VarDecl = VarDecl; - var ArgDecl = (function (_super) { - __extends(ArgDecl, _super); - function ArgDecl(id) { - _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); - this.isOptional = false; - this.parameterPropertySym = null; - } - ArgDecl.prototype.isOptionalArg = function () { - return this.isOptional || this.init; - }; - ArgDecl.prototype.treeViewLabel = function () { - return "arg: " + this.id.actualText; - }; - ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ArgDecl; - })(BoundDecl); - TypeScript.ArgDecl = ArgDecl; - var internalId = 0; - var FuncDecl = (function (_super) { - __extends(FuncDecl, _super); - function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { - _super.call(this, nodeType); - this.name = name; - this.bod = bod; - this.isConstructor = isConstructor; - this.arguments = arguments; - this.vars = vars; - this.scopes = scopes; - this.statics = statics; - this.hint = null; - this.fncFlags = TypeScript.FncFlags.None; - this.returnTypeAnnotation = null; - this.variableArgList = false; - this.jumpRefs = null; - this.internalNameCache = null; - this.tmp1Declared = false; - this.enclosingFnc = null; - this.freeVariables = []; - this.unitIndex = -1; - this.classDecl = null; - this.boundToProperty = null; - this.isOverload = false; - this.innerStaticFuncs = []; - this.isTargetTypedAsMethod = false; - this.isInlineCallLiteral = false; - this.accessorSymbol = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.returnStatementsWithExpressions = []; - this.scopeType = null; - this.endingToken = null; - } - FuncDecl.prototype.isDeclaration = function () { - return true; - }; - FuncDecl.prototype.internalName = function () { - if(this.internalNameCache == null) { - var extName = this.getNameText(); - if(extName) { - this.internalNameCache = "_internal_" + extName; - } else { - this.internalNameCache = "_internal_" + internalId++; - } - } - return this.internalNameCache; - }; - FuncDecl.prototype.hasSelfReference = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); - }; - FuncDecl.prototype.setHasSelfReference = function () { - this.fncFlags |= TypeScript.FncFlags.HasSelfReference; - }; - FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); - }; - FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { - this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; - }; - FuncDecl.prototype.addCloRef = function (id, sym) { - if(this.envids == null) { - this.envids = new Array(); - } - this.envids[this.envids.length] = id; - var outerFnc = this.enclosingFnc; - if(sym) { - while(outerFnc && (outerFnc.type.symbol != sym.container)) { - outerFnc.addJumpRef(sym); - outerFnc = outerFnc.enclosingFnc; - } - } - return this.envids.length - 1; - }; - FuncDecl.prototype.addJumpRef = function (sym) { - if(this.jumpRefs == null) { - this.jumpRefs = new Array(); - } - var id = new Identifier(sym.name); - this.jumpRefs[this.jumpRefs.length] = id; - id.sym = sym; - id.cloId = this.addCloRef(id, null); - }; - FuncDecl.prototype.buildControlFlow = function () { - var entry = new TypeScript.BasicBlock(); - var exit = new TypeScript.BasicBlock(); - var context = new TypeScript.ControlFlowContext(entry, exit); - var controlFlowPrefix = function (ast, parent, walker) { - ast.addToControlFlow(walker.state); - return ast; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); - context.walker = walker; - walker.walk(this.bod, this); - return context; - }; - FuncDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFunction(this); - }; - FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptFunction(this); - }; - FuncDecl.prototype.getNameText = function () { - if(this.name) { - return this.name.actualText; - } else { - return this.hint; - } - }; - FuncDecl.prototype.isMethod = function () { - return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isCallMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); - }; - FuncDecl.prototype.isConstructMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); - }; - FuncDecl.prototype.isIndexerMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); - }; - FuncDecl.prototype.isSpecialFn = function () { - return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); - }; - FuncDecl.prototype.isAnonymousFn = function () { - return this.name === null; - }; - FuncDecl.prototype.isAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isGetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); - }; - FuncDecl.prototype.isSetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); - }; - FuncDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); - }; - FuncDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); - }; - FuncDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); - }; - FuncDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); - }; - FuncDecl.prototype.treeViewLabel = function () { - if(this.name == null) { - return "funcExpr"; - } else { - return "func: " + this.name.actualText; - } - }; - FuncDecl.prototype.ClearFlags = function () { - this.fncFlags = TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isSignature = function () { - return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; - }; - return FuncDecl; - })(AST); - TypeScript.FuncDecl = FuncDecl; - var LocationInfo = (function () { - function LocationInfo(filename, lineMap, unitIndex) { - this.filename = filename; - this.lineMap = lineMap; - this.unitIndex = unitIndex; - } - return LocationInfo; - })(); - TypeScript.LocationInfo = LocationInfo; - TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); - var Script = (function (_super) { - __extends(Script, _super); - function Script(vars, scopes) { - _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); - this.locationInfo = null; - this.referencedFiles = []; - this.requiresGlobal = false; - this.requiresExtendsBlock = false; - this.isResident = false; - this.isDeclareFile = false; - this.hasBeenTypeChecked = false; - this.topLevelMod = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.externallyVisibleImportedSymbols = []; - this.vars = vars; - this.scopes = scopes; - } - Script.prototype.setCachedEmitRequired = function (value) { - this.cachedEmitRequired = value; - return this.cachedEmitRequired; - }; - Script.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckScript(this); - }; - Script.prototype.treeViewLabel = function () { - return "Script"; - }; - Script.prototype.emitRequired = function (emitOptions) { - if(this.cachedEmitRequired != undefined) { - return this.cachedEmitRequired; - } - if(!this.isDeclareFile && !this.isResident && this.bod) { - for(var i = 0, len = this.bod.members.length; i < len; i++) { - var stmt = this.bod.members[i]; - if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { - if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType == TypeScript.NodeType.VarDecl) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { - if(!(stmt).isSignature()) { - return this.setCachedEmitRequired(true); - } - } else { - if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { - return this.setCachedEmitRequired(true); - } - } - } - } - } - } - if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { - return this.setCachedEmitRequired(true); - } - } - return this.setCachedEmitRequired(false); - }; - Script.prototype.emit = function (emitter, tokenId, startLine) { - if(this.emitRequired(emitter.emitOptions)) { - emitter.emitParensAndCommentsInPlace(this.bod, true); - emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); - emitter.emitParensAndCommentsInPlace(this.bod, false); - } - }; - Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { - if(this.isExternallyVisibleSymbol(symbol)) { - return; - } - if(!symbol.getType().symbol.isExternallyVisible(checker)) { - var quotes = ""; - var moduleName = symbol.getType().symbol.prettyName; - if(!TypeScript.isQuoted(moduleName)) { - quotes = "'"; - } - checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); - } - this.externallyVisibleImportedSymbols.push(symbol); - }; - Script.prototype.isExternallyVisibleSymbol = function (symbol) { - for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { - if(this.externallyVisibleImportedSymbols[i] == symbol) { - return true; - } - } - return false; - }; - return Script; - })(FuncDecl); - TypeScript.Script = Script; - var NamedDeclaration = (function (_super) { - __extends(NamedDeclaration, _super); - function NamedDeclaration(nodeType, name, members) { - _super.call(this, nodeType); - this.name = name; - this.members = members; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - } - NamedDeclaration.prototype.isDeclaration = function () { - return true; - }; - return NamedDeclaration; - })(ModuleElement); - TypeScript.NamedDeclaration = NamedDeclaration; - var ModuleDeclaration = (function (_super) { - __extends(ModuleDeclaration, _super); - function ModuleDeclaration(name, members, vars, scopes, endingToken) { - _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); - this.endingToken = endingToken; - this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; - this.amdDependencies = []; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.vars = vars; - this.scopes = scopes; - this.prettyName = this.name.actualText; - } - ModuleDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); - }; - ModuleDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); - }; - ModuleDeclaration.prototype.isEnum = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); - }; - ModuleDeclaration.prototype.recordNonInterface = function () { - this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - }; - ModuleDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckModule(this); - }; - ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascriptModule(this); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - } - }; - return ModuleDeclaration; - })(NamedDeclaration); - TypeScript.ModuleDeclaration = ModuleDeclaration; - var TypeDeclaration = (function (_super) { - __extends(TypeDeclaration, _super); - function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { - _super.call(this, nodeType, name, members); - this.extendsList = extendsList; - this.implementsList = implementsList; - this.varFlags = TypeScript.VarFlags.None; - } - TypeDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - TypeDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - return TypeDeclaration; - })(NamedDeclaration); - TypeScript.TypeDeclaration = TypeDeclaration; - var ClassDeclaration = (function (_super) { - __extends(ClassDeclaration, _super); - function ClassDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); - this.knownMemberNames = { - }; - this.constructorDecl = null; - this.constructorNestingLevel = 0; - this.endingToken = null; - } - ClassDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckClass(this); - }; - ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptClass(this); - }; - return ClassDeclaration; - })(TypeDeclaration); - TypeScript.ClassDeclaration = ClassDeclaration; - var InterfaceDeclaration = (function (_super) { - __extends(InterfaceDeclaration, _super); - function InterfaceDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); - } - InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckInterface(this); - }; - InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - }; - return InterfaceDeclaration; - })(TypeDeclaration); - TypeScript.InterfaceDeclaration = InterfaceDeclaration; - var Statement = (function (_super) { - __extends(Statement, _super); - function Statement(nodeType) { - _super.call(this, nodeType); - this.flags |= TypeScript.ASTFlags.IsStatement; - } - Statement.prototype.isLoop = function () { - return false; - }; - Statement.prototype.isStatementOrExpression = function () { - return true; - }; - Statement.prototype.isCompoundStatement = function () { - return this.isLoop(); - }; - Statement.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - return Statement; - })(ModuleElement); - TypeScript.Statement = Statement; - var LabeledStatement = (function (_super) { - __extends(LabeledStatement, _super); - function LabeledStatement(labels, stmt) { - _super.call(this, TypeScript.NodeType.LabeledStatement); - this.labels = labels; - this.stmt = stmt; - } - LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.labels) { - var labelsLen = this.labels.members.length; - for(var i = 0; i < labelsLen; i++) { - this.labels.members[i].emit(emitter, tokenId, startLine); - } - } - this.stmt.emit(emitter, tokenId, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - LabeledStatement.prototype.typeCheck = function (typeFlow) { - typeFlow.typeCheck(this.labels); - this.stmt = this.stmt.typeCheck(typeFlow); - return this; - }; - LabeledStatement.prototype.addToControlFlow = function (context) { - var beforeBB = context.current; - var bb = new TypeScript.BasicBlock(); - context.current = bb; - beforeBB.addSuccessor(bb); - }; - return LabeledStatement; - })(Statement); - TypeScript.LabeledStatement = LabeledStatement; - var Block = (function (_super) { - __extends(Block, _super); - function Block(statements, isStatementBlock) { - _super.call(this, TypeScript.NodeType.Block); - this.statements = statements; - this.isStatementBlock = isStatementBlock; - } - Block.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.isStatementBlock) { - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - } else { - emitter.setInVarBlock(this.statements.members.length); - } - var temp = emitter.setInObjectLiteral(false); - if(this.statements) { - emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); - } - if(this.isStatementBlock) { - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Block.prototype.addToControlFlow = function (context) { - var afterIfNeeded = new TypeScript.BasicBlock(); - context.pushStatement(this, context.current, afterIfNeeded); - if(this.statements) { - context.walk(this.statements, this); - } - context.walker.options.goChildren = false; - context.popStatement(); - if(afterIfNeeded.predecessors.length > 0) { - context.current.addSuccessor(afterIfNeeded); - context.current = afterIfNeeded; - } - }; - Block.prototype.typeCheck = function (typeFlow) { - if(!typeFlow.checker.styleSettings.emptyBlocks) { - if((this.statements === null) || (this.statements.members.length == 0)) { - typeFlow.checker.errorReporter.styleError(this, "empty block"); - } - } - typeFlow.typeCheck(this.statements); - return this; - }; - return Block; - })(Statement); - TypeScript.Block = Block; - var Jump = (function (_super) { - __extends(Jump, _super); - function Jump(nodeType) { - _super.call(this, nodeType); - this.target = null; - this.resolvedTarget = null; - } - Jump.prototype.hasExplicitTarget = function () { - return (this.target); - }; - Jump.prototype.setResolvedTarget = function (parser, stmt) { - if(stmt.isLoop()) { - this.resolvedTarget = stmt; - return true; - } - if(this.nodeType === TypeScript.NodeType.Continue) { - parser.reportParseError("continue statement applies only to loops"); - return false; - } else { - if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { - this.resolvedTarget = stmt; - return true; - } else { - parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); - return false; - } - } - }; - Jump.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); - }; - Jump.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.Break) { - emitter.writeToOutput("break"); - } else { - emitter.writeToOutput("continue"); - } - if(this.hasExplicitTarget()) { - emitter.writeToOutput(" " + this.target); - } - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Jump; - })(Statement); - TypeScript.Jump = Jump; - var WhileStatement = (function (_super) { - __extends(WhileStatement, _super); - function WhileStatement(cond) { - _super.call(this, TypeScript.NodeType.While); - this.cond = cond; - this.body = null; - } - WhileStatement.prototype.isLoop = function () { - return true; - }; - WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("while("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, false); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWhile(this); - }; - WhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - context.addContent(this.cond); - var condBlock = context.current; - var targetInfo = null; - if(this.body) { - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return WhileStatement; - })(Statement); - TypeScript.WhileStatement = WhileStatement; - var DoWhileStatement = (function (_super) { - __extends(DoWhileStatement, _super); - function DoWhileStatement() { - _super.call(this, TypeScript.NodeType.DoWhile); - this.body = null; - this.whileAST = null; - this.cond = null; - } - DoWhileStatement.prototype.isLoop = function () { - return true; - }; - DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("do"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingStart(this.whileAST); - emitter.writeToOutput("while"); - emitter.recordSourceMappingEnd(this.whileAST); - emitter.writeToOutput('('); - emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); - emitter.writeToOutput(")"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - DoWhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckDoWhile(this); - }; - DoWhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var targetInfo = null; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - context.addContent(this.cond); - context.current = afterLoop; - loopEnd.addSuccessor(afterLoop); - } else { - context.addUnreachable(this.cond); - } - context.walker.options.goChildren = false; - }; - return DoWhileStatement; - })(Statement); - TypeScript.DoWhileStatement = DoWhileStatement; - var IfStatement = (function (_super) { - __extends(IfStatement, _super); - function IfStatement(cond) { - _super.call(this, TypeScript.NodeType.If); - this.cond = cond; - this.elseBod = null; - this.statement = new ASTSpan(); - } - IfStatement.prototype.isCompoundStatement = function () { - return true; - }; - IfStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("if("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.thenBod, true); - if(this.elseBod) { - if(this.elseBod.nodeType === TypeScript.NodeType.If) { - emitter.writeToOutput(" else "); - this.elseBod.emit(emitter, tokenId, false); - } else { - emitter.writeToOutput(" else"); - emitter.emitJavascriptStatements(this.elseBod, true); - } - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - IfStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckIf(this); - }; - IfStatement.prototype.addToControlFlow = function (context) { - this.cond.addToControlFlow(context); - var afterIf = new TypeScript.BasicBlock(); - var beforeIf = context.current; - context.pushStatement(this, beforeIf, afterIf); - var hasContinuation = false; - context.current = new TypeScript.BasicBlock(); - beforeIf.addSuccessor(context.current); - context.walk(this.thenBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } - if(this.elseBod) { - context.current = new TypeScript.BasicBlock(); - context.noContinuation = false; - beforeIf.addSuccessor(context.current); - context.walk(this.elseBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } else { - if(hasContinuation) { - context.noContinuation = false; - } - } - } else { - beforeIf.addSuccessor(afterIf); - context.noContinuation = false; - hasContinuation = true; - } - var targetInfo = context.popStatement(); - if(afterIf.predecessors.length > 0) { - context.noContinuation = false; - hasContinuation = true; - } - if(hasContinuation) { - context.current = afterIf; - } - context.walker.options.goChildren = false; - }; - return IfStatement; - })(Statement); - TypeScript.IfStatement = IfStatement; - var ReturnStatement = (function (_super) { - __extends(ReturnStatement, _super); - function ReturnStatement() { - _super.call(this, TypeScript.NodeType.Return); - this.returnExpression = null; - } - ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - if(this.returnExpression) { - emitter.writeToOutput("return "); - emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); - if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { - emitter.writeToOutput(";"); - } - } else { - emitter.writeToOutput("return;"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ReturnStatement.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.returnStmt(); - }; - ReturnStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckReturn(this); - }; - return ReturnStatement; - })(Statement); - TypeScript.ReturnStatement = ReturnStatement; - var EndCode = (function (_super) { - __extends(EndCode, _super); - function EndCode() { - _super.call(this, TypeScript.NodeType.EndCode); - } - return EndCode; - })(AST); - TypeScript.EndCode = EndCode; - var ForInStatement = (function (_super) { - __extends(ForInStatement, _super); - function ForInStatement(lval, obj) { - _super.call(this, TypeScript.NodeType.ForIn); - this.lval = lval; - this.obj = obj; - this.statement = new ASTSpan(); - if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { - (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; - } - } - ForInStatement.prototype.isLoop = function () { - return true; - }; - ForInStatement.prototype.isFiltered = function () { - if(this.body) { - var singleItem = null; - if(this.body.nodeType == TypeScript.NodeType.List) { - var stmts = this.body; - if(stmts.members.length == 1) { - singleItem = stmts.members[0]; - } - } else { - singleItem = this.body; - } - if(singleItem !== null) { - if(singleItem.nodeType == TypeScript.NodeType.Block) { - var block = singleItem; - if((block.statements !== null) && (block.statements.members.length == 1)) { - singleItem = block.statements.members[0]; - } - } - if(singleItem.nodeType == TypeScript.NodeType.If) { - var cond = (singleItem).cond; - if(cond.nodeType == TypeScript.NodeType.Call) { - var target = (cond).target; - if(target.nodeType == TypeScript.NodeType.Dot) { - var binex = target; - if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { - var prop = binex.operand2; - if(prop.actualText == "hasOwnProperty") { - var args = (cond).arguments; - if((args !== null) && (args.members.length == 1)) { - var arg = args.members[0]; - if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { - if(((this.lval).actualText) == (arg).actualText) { - return true; - } - } - } - } - } - } - } - } - } - } - return false; - }; - ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("for("); - emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); - emitter.writeToOutput(" in "); - emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForInStatement.prototype.typeCheck = function (typeFlow) { - if(typeFlow.checker.styleSettings.forin) { - if(!this.isFiltered()) { - typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); - } - } - return typeFlow.typeCheckForIn(this); - }; - ForInStatement.prototype.addToControlFlow = function (context) { - if(this.lval) { - context.addContent(this.lval); - } - if(this.obj) { - context.addContent(this.obj); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - context.noContinuation = false; - loopHeader.addSuccessor(afterLoop); - context.walker.options.goChildren = false; - }; - return ForInStatement; - })(Statement); - TypeScript.ForInStatement = ForInStatement; - var ForStatement = (function (_super) { - __extends(ForStatement, _super); - function ForStatement(init) { - _super.call(this, TypeScript.NodeType.For); - this.init = init; - } - ForStatement.prototype.isLoop = function () { - return true; - }; - ForStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("for("); - if(this.init) { - if(this.init.nodeType != TypeScript.NodeType.List) { - emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); - } else { - emitter.setInVarBlock((this.init).members.length); - emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); - } - } - emitter.writeToOutput("; "); - emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); - emitter.writeToOutput("; "); - emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFor(this); - }; - ForStatement.prototype.addToControlFlow = function (context) { - if(this.init) { - context.addContent(this.init); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var condBlock = null; - var continueTarget = loopStart; - var incrBB = null; - if(this.incr) { - incrBB = new TypeScript.BasicBlock(); - continueTarget = incrBB; - } - if(this.cond) { - condBlock = context.current; - context.addContent(this.cond); - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - } - var targetInfo = null; - if(this.body) { - context.pushStatement(this, continueTarget, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(this.incr) { - if(context.noContinuation) { - if(incrBB.predecessors.length == 0) { - context.addUnreachable(this.incr); - } - } else { - context.current.addSuccessor(incrBB); - context.current = incrBB; - context.addContent(this.incr); - } - } - var loopEnd = context.current; - if(!(context.noContinuation)) { - loopEnd.addSuccessor(loopStart); - } - if(condBlock) { - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - } - if(afterLoop.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterLoop; - } - context.walker.options.goChildren = false; - }; - return ForStatement; - })(Statement); - TypeScript.ForStatement = ForStatement; - var WithStatement = (function (_super) { - __extends(WithStatement, _super); - function WithStatement(expr) { - _super.call(this, TypeScript.NodeType.With); - this.expr = expr; - this.withSym = null; - } - WithStatement.prototype.isCompoundStatement = function () { - return true; - }; - WithStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("with ("); - if(this.expr) { - emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); - } - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WithStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWith(this); - }; - return WithStatement; - })(Statement); - TypeScript.WithStatement = WithStatement; - var SwitchStatement = (function (_super) { - __extends(SwitchStatement, _super); - function SwitchStatement(val) { - _super.call(this, TypeScript.NodeType.Switch); - this.val = val; - this.defaultCase = null; - this.statement = new ASTSpan(); - } - SwitchStatement.prototype.isCompoundStatement = function () { - return true; - }; - SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("switch("); - emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - var casesLen = this.caseList.members.length; - for(var i = 0; i < casesLen; i++) { - var caseExpr = this.caseList.members[i]; - emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); - } - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - SwitchStatement.prototype.typeCheck = function (typeFlow) { - var len = this.caseList.members.length; - this.val = typeFlow.typeCheck(this.val); - for(var i = 0; i < len; i++) { - this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); - } - this.defaultCase = typeFlow.typeCheck(this.defaultCase); - this.type = typeFlow.voidType; - return this; - }; - SwitchStatement.prototype.addToControlFlow = function (context) { - var condBlock = context.current; - context.addContent(this.val); - var execBlock = new TypeScript.BasicBlock(); - var afterSwitch = new TypeScript.BasicBlock(); - condBlock.addSuccessor(execBlock); - context.pushSwitch(execBlock); - context.current = execBlock; - context.pushStatement(this, execBlock, afterSwitch); - context.walk(this.caseList, this); - context.popSwitch(); - var targetInfo = context.popStatement(); - var hasCondContinuation = (this.defaultCase == null); - if(this.defaultCase == null) { - condBlock.addSuccessor(afterSwitch); - } - if(afterSwitch.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterSwitch; - } else { - context.noContinuation = true; - } - context.walker.options.goChildren = false; - }; - return SwitchStatement; - })(Statement); - TypeScript.SwitchStatement = SwitchStatement; - var CaseStatement = (function (_super) { - __extends(CaseStatement, _super); - function CaseStatement() { - _super.call(this, TypeScript.NodeType.Case); - this.expr = null; - } - CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.expr) { - emitter.writeToOutput("case "); - emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); - } else { - emitter.writeToOutput("default"); - } - emitter.writeToOutput(":"); - if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { - emitter.emitJavascriptStatements(this.body, false); - } else { - emitter.writeLineToOutput(""); - emitter.indenter.increaseIndent(); - emitter.emitBareJavascriptStatements(this.body); - emitter.indenter.decreaseIndent(); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - CaseStatement.prototype.typeCheck = function (typeFlow) { - this.expr = typeFlow.typeCheck(this.expr); - typeFlow.typeCheck(this.body); - this.type = typeFlow.voidType; - return this; - }; - CaseStatement.prototype.addToControlFlow = function (context) { - var execBlock = new TypeScript.BasicBlock(); - var sw = context.currentSwitch[context.currentSwitch.length - 1]; - if(this.expr) { - var exprBlock = new TypeScript.BasicBlock(); - context.current = exprBlock; - sw.addSuccessor(exprBlock); - context.addContent(this.expr); - exprBlock.addSuccessor(execBlock); - } else { - sw.addSuccessor(execBlock); - } - context.current = execBlock; - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return CaseStatement; - })(Statement); - TypeScript.CaseStatement = CaseStatement; - var TypeReference = (function (_super) { - __extends(TypeReference, _super); - function TypeReference(term, arrayCount) { - _super.call(this, TypeScript.NodeType.TypeRef); - this.term = term; - this.arrayCount = arrayCount; - } - TypeReference.prototype.emit = function (emitter, tokenId, startLine) { - throw new Error("should not emit a type ref"); - }; - TypeReference.prototype.typeCheck = function (typeFlow) { - var prevInTCTR = typeFlow.inTypeRefTypeCheck; - typeFlow.inTypeRefTypeCheck = true; - var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); - typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); - if(this.term) { - typeFlow.typeCheck(this.term); - } - typeFlow.checkForVoidConstructor(typeLink.type, this); - this.type = typeLink.type; - if(this.term) { - this.term.type = this.type; - } - typeFlow.inTypeRefTypeCheck = prevInTCTR; - return this; - }; - return TypeReference; - })(AST); - TypeScript.TypeReference = TypeReference; - var TryFinally = (function (_super) { - __extends(TryFinally, _super); - function TryFinally(tryNode, finallyNode) { - _super.call(this, TypeScript.NodeType.TryFinally); - this.tryNode = tryNode; - this.finallyNode = finallyNode; - } - TryFinally.prototype.isCompoundStatement = function () { - return true; - }; - TryFinally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - }; - TryFinally.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.finallyNode = typeFlow.typeCheck(this.finallyNode); - this.type = typeFlow.voidType; - return this; - }; - TryFinally.prototype.addToControlFlow = function (context) { - var afterFinally = new TypeScript.BasicBlock(); - context.walk(this.tryNode, this); - var finBlock = new TypeScript.BasicBlock(); - if(context.current) { - context.current.addSuccessor(finBlock); - } - context.current = finBlock; - context.pushStatement(this, null, afterFinally); - context.walk(this.finallyNode, this); - if(!context.noContinuation && context.current) { - context.current.addSuccessor(afterFinally); - } - if(afterFinally.predecessors.length > 0) { - context.current = afterFinally; - } else { - context.noContinuation = true; - } - context.popStatement(); - context.walker.options.goChildren = false; - }; - return TryFinally; - })(Statement); - TypeScript.TryFinally = TryFinally; - var TryCatch = (function (_super) { - __extends(TryCatch, _super); - function TryCatch(tryNode, catchNode) { - _super.call(this, TypeScript.NodeType.TryCatch); - this.tryNode = tryNode; - this.catchNode = catchNode; - } - TryCatch.prototype.isCompoundStatement = function () { - return true; - }; - TryCatch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - TryCatch.prototype.addToControlFlow = function (context) { - var beforeTry = context.current; - var tryBlock = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(tryBlock); - context.current = tryBlock; - var afterTryCatch = new TypeScript.BasicBlock(); - context.pushStatement(this, null, afterTryCatch); - context.walk(this.tryNode, this); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(context.current); - context.walk(this.catchNode, this); - context.popStatement(); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = afterTryCatch; - context.walker.options.goChildren = false; - }; - TryCatch.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.catchNode = typeFlow.typeCheck(this.catchNode); - this.type = typeFlow.voidType; - return this; - }; - return TryCatch; - })(Statement); - TypeScript.TryCatch = TryCatch; - var Try = (function (_super) { - __extends(Try, _super); - function Try(body) { - _super.call(this, TypeScript.NodeType.Try); - this.body = body; - } - Try.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("try "); - emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Try.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - Try.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - return Try; - })(Statement); - TypeScript.Try = Try; - var Catch = (function (_super) { - __extends(Catch, _super); - function Catch(param, body) { - _super.call(this, TypeScript.NodeType.Catch); - this.param = param; - this.body = body; - this.statement = new ASTSpan(); - this.containedScope = null; - if(this.param) { - this.param.varFlags |= TypeScript.VarFlags.AutoInit; - } - } - Catch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(" "); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("catch ("); - emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Catch.prototype.addToControlFlow = function (context) { - if(this.param) { - context.addContent(this.param); - var bodBlock = new TypeScript.BasicBlock(); - context.current.addSuccessor(bodBlock); - context.current = bodBlock; - } - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - Catch.prototype.typeCheck = function (typeFlow) { - var prevScope = typeFlow.scope; - typeFlow.scope = this.containedScope; - this.param = typeFlow.typeCheck(this.param); - var exceptVar = new TypeScript.ValueLocation(); - var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); - exceptVar.symbol = varSym; - exceptVar.typeLink = new TypeScript.TypeLink(); - exceptVar.typeLink.type = typeFlow.anyType; - var thisFnc = typeFlow.thisFnc; - if(thisFnc && thisFnc.type) { - exceptVar.symbol.container = thisFnc.type.symbol; - } else { - exceptVar.symbol.container = null; - } - this.param.sym = exceptVar.symbol; - typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); - this.body = typeFlow.typeCheck(this.body); - if(typeFlow.checker.inProvisionalTypecheckMode()) { - var table = typeFlow.scope.getTable(); - (table).secondaryTable.table[exceptVar.symbol.name] = undefined; - } - this.type = typeFlow.voidType; - typeFlow.scope = prevScope; - return this; - }; - return Catch; - })(Statement); - TypeScript.Catch = Catch; - var Finally = (function (_super) { - __extends(Finally, _super); - function Finally(body) { - _super.call(this, TypeScript.NodeType.Finally); - this.body = body; - } - Finally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("finally"); - emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Finally.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - Finally.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - return Finally; - })(Statement); - TypeScript.Finally = Finally; - var Comment = (function (_super) { - __extends(Comment, _super); - function Comment(content, isBlockComment, endsLine) { - _super.call(this, TypeScript.NodeType.Comment); - this.content = content; - this.isBlockComment = isBlockComment; - this.endsLine = endsLine; - this.text = null; - this.docCommentText = null; - } - Comment.prototype.getText = function () { - if(this.text == null) { - if(this.isBlockComment) { - this.text = this.content.split("\n"); - for(var i = 0; i < this.text.length; i++) { - this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); - } - } else { - this.text = [ - (this.content.replace(/^\s+|\s+$/g, '')) - ]; - } - } - return this.text; - }; - Comment.prototype.isDocComment = function () { - if(this.isBlockComment) { - return this.content.charAt(2) == "*"; - } - return false; - }; - Comment.prototype.getDocCommentText = function () { - if(this.docCommentText == null) { - this.docCommentText = Comment.cleanJSDocComment(this.content); - } - return this.docCommentText; - }; - Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { - var endIndex = line.length; - if(maxSpacesToRemove != undefined) { - endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); - } - for(; startIndex < endIndex; startIndex++) { - var charCode = line.charCodeAt(startIndex); - if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { - return startIndex; - } - } - if(endIndex != line.length) { - return endIndex; - } - return -1; - } - Comment.isSpaceChar = function isSpaceChar(line, index) { - var length = line.length; - if(index < length) { - var charCode = line.charCodeAt(index); - return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; - } - return index == length; - } - Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { - var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); - if(nonSpaceIndex != -1) { - var jsDocSpacesRemoved = nonSpaceIndex; - if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { - var startIndex = nonSpaceIndex + 1; - nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); - if(nonSpaceIndex != -1) { - jsDocSpacesRemoved = nonSpaceIndex - startIndex; - } else { - return null; - } - } - return { - minChar: nonSpaceIndex, - limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, - jsDocSpacesRemoved: jsDocSpacesRemoved - }; - } - return null; - } - Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { - var docCommentLines = []; - content = content.replace("/**", ""); - if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { - content = content.substring(0, content.length - 2); - } - var lines = content.split("\n"); - var inParamTag = false; - for(var l = 0; l < lines.length; l++) { - var line = lines[l]; - var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); - if(!cleanLinePos) { - continue; - } - var docCommentText = ""; - var prevPos = cleanLinePos.minChar; - for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { - var wasInParamtag = inParamTag; - if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { - if(!wasInParamtag) { - docCommentText += line.substring(prevPos, i); - } - prevPos = i; - inParamTag = true; - } else { - if(wasInParamtag) { - prevPos = i; - inParamTag = false; - } - } - } - if(!inParamTag) { - docCommentText += line.substring(prevPos, cleanLinePos.limChar); - } - var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); - if(newCleanPos) { - if(spacesToRemove == undefined) { - spacesToRemove = cleanLinePos.jsDocSpacesRemoved; - } - docCommentLines.push(docCommentText); - } - } - return docCommentLines.join("\n"); - } - Comment.getDocCommentText = function getDocCommentText(comments) { - var docCommentText = []; - for(var c = 0; c < comments.length; c++) { - var commentText = comments[c].getDocCommentText(); - if(commentText != "") { - docCommentText.push(commentText); - } - } - return docCommentText.join("\n"); - } - Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { - if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { - return ""; - } - for(var i = 0; i < fncDocComments.length; i++) { - var commentContents = fncDocComments[i].content; - for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { - j += 6; - if(!Comment.isSpaceChar(commentContents, j)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j); - if(j == -1) { - break; - } - if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { - j++; - var charCode = 0; - for(var curlies = 1; j < commentContents.length; j++) { - charCode = commentContents.charCodeAt(j); - if(charCode == TypeScript.LexCodeLC) { - curlies++; - continue; - } - if(charCode == TypeScript.LexCodeRC) { - curlies--; - if(curlies == 0) { - break; - } else { - continue; - } - } - if(charCode == TypeScript.LexCodeAtSign) { - break; - } - } - if(j == commentContents.length) { - break; - } - if(charCode == TypeScript.LexCodeAtSign) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + 1); - if(j == -1) { - break; - } - } - if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + param.length); - if(j == -1) { - return ""; - } - var endOfParam = commentContents.indexOf("@", j); - var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); - var paramSpacesToRemove = undefined; - var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; - if(paramLineIndex != 0) { - if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { - paramLineIndex++; - } - } - var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); - if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { - paramSpacesToRemove = j - startSpaceRemovalIndex - 1; - } - return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); - } - } - return ""; - } - Comment.getDocCommentTextOfSignatures = function getDocCommentTextOfSignatures(signatures) { - var comments = []; - for(var i = 0; i < signatures.length; i++) { - var signatureDocComment = TypeScript.Comment.getDocCommentText(signatures[i].declAST.getDocComments()); - if(signatureDocComment != "") { - comments.push(signatureDocComment); - } - } - return comments.join("\n"); - } - return Comment; - })(AST); - TypeScript.Comment = Comment; - var DebuggerStatement = (function (_super) { - __extends(DebuggerStatement, _super); - function DebuggerStatement() { - _super.call(this, TypeScript.NodeType.Debugger); - } - DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeLineToOutput("debugger;"); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return DebuggerStatement; - })(Statement); - TypeScript.DebuggerStatement = DebuggerStatement; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstWalkOptions = (function () { - function AstWalkOptions() { - this.goChildren = true; - this.goNextSibling = true; - this.reverseSiblings = false; - } - AstWalkOptions.prototype.stopWalk = function (stop) { - if (typeof stop === "undefined") { stop = true; } - this.goChildren = !stop; - this.goNextSibling = !stop; - }; - return AstWalkOptions; - })(); - TypeScript.AstWalkOptions = AstWalkOptions; - var AstWalker = (function () { - function AstWalker(childrenWalkers, pre, post, options, state) { - this.childrenWalkers = childrenWalkers; - this.pre = pre; - this.post = post; - this.options = options; - this.state = state; - } - AstWalker.prototype.walk = function (ast, parent) { - var preAst = this.pre(ast, parent, this); - if(preAst === undefined) { - preAst = ast; - } - if(this.options.goChildren) { - var svGoSib = this.options.goNextSibling; - this.options.goNextSibling = true; - this.childrenWalkers[ast.nodeType](ast, parent, this); - this.options.goNextSibling = svGoSib; - } else { - this.options.goChildren = true; - } - if(this.post) { - var postAst = this.post(preAst, parent, this); - if(postAst === undefined) { - postAst = preAst; - } - return postAst; - } else { - return preAst; - } - }; - return AstWalker; - })(); - var AstWalkerFactory = (function () { - function AstWalkerFactory() { - this.childrenWalkers = []; - this.initChildrenWalkers(); - } - AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { - return this.getWalker(pre, post, options, state).walk(ast, null); - }; - AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { - return this.getSlowWalker(pre, post, options, state); - }; - AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { - if(!options) { - options = new AstWalkOptions(); - } - return new AstWalker(this.childrenWalkers, pre, post, options, state); - }; - AstWalkerFactory.prototype.initChildrenWalkers = function () { - this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; - this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; - this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; - this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; - this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; - this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; - this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; - this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; - this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; - this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; - this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; - this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; - this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; - this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; - this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; - for(var e in (TypeScript.NodeType)._map) { - if((this.childrenWalkers)[e] === undefined) { - throw new Error("initWalkers function is not up to date with enum content!"); - } - } - }; - return AstWalkerFactory; - })(); - TypeScript.AstWalkerFactory = AstWalkerFactory; - var globalAstWalkerFactory; - function getAstWalkerFactory() { - if(!globalAstWalkerFactory) { - globalAstWalkerFactory = new AstWalkerFactory(); - } - return globalAstWalkerFactory; - } - TypeScript.getAstWalkerFactory = getAstWalkerFactory; - var ChildrenWalkers; - (function (ChildrenWalkers) { - function walkNone(preAst, parent, walker) { - } - ChildrenWalkers.walkNone = walkNone; - function walkListChildren(preAst, parent, walker) { - var len = preAst.members.length; - if(walker.options.reverseSiblings) { - for(var i = len - 1; i >= 0; i--) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } else { - for(var i = 0; i < len; i++) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } - } - ChildrenWalkers.walkListChildren = walkListChildren; - function walkUnaryExpressionChildren(preAst, parent, walker) { - if(preAst.castTerm) { - preAst.castTerm = walker.walk(preAst.castTerm, preAst); - } - if(preAst.operand) { - preAst.operand = walker.walk(preAst.operand, preAst); - } - } - ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; - function walkBinaryExpressionChildren(preAst, parent, walker) { - if(walker.options.reverseSiblings) { - if(preAst.operand2) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if((preAst.operand1) && (walker.options.goNextSibling)) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - } else { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if((preAst.operand2) && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - } - } - ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; - function walkTypeReferenceChildren(preAst, parent, walker) { - if(preAst.term) { - preAst.term = walker.walk(preAst.term, preAst); - } - } - ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; - function walkCallExpressionChildren(preAst, parent, walker) { - if(!walker.options.reverseSiblings) { - preAst.target = walker.walk(preAst.target, preAst); - } - if(preAst.arguments && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { - preAst.target = walker.walk(preAst.target, preAst); - } - } - ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; - function walkTrinaryExpressionChildren(preAst, parent, walker) { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if(preAst.operand2 && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if(preAst.operand3 && (walker.options.goNextSibling)) { - preAst.operand3 = walker.walk(preAst.operand3, preAst); - } - } - ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; - function walkFuncDeclChildren(preAst, parent, walker) { - if(preAst.name) { - preAst.name = walker.walk(preAst.name, preAst); - } - if(preAst.arguments && (preAst.arguments.members.length > 0) && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { - preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); - } - if(preAst.bod && (preAst.bod.members.length > 0) && (walker.options.goNextSibling)) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; - function walkBoundDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if((preAst.typeExpr) && (walker.options.goNextSibling)) { - preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); - } - } - ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; - function walkReturnStatementChildren(preAst, parent, walker) { - if(preAst.returnExpression) { - preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); - } - } - ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; - function walkForStatementChildren(preAst, parent, walker) { - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if(preAst.cond && walker.options.goNextSibling) { - preAst.cond = walker.walk(preAst.cond, preAst); - } - if(preAst.incr && walker.options.goNextSibling) { - preAst.incr = walker.walk(preAst.incr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; - function walkForInStatementChildren(preAst, parent, walker) { - preAst.lval = walker.walk(preAst.lval, preAst); - if(walker.options.goNextSibling) { - preAst.obj = walker.walk(preAst.obj, preAst); - } - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; - function walkIfStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.thenBod && (walker.options.goNextSibling)) { - preAst.thenBod = walker.walk(preAst.thenBod, preAst); - } - if(preAst.elseBod && (walker.options.goNextSibling)) { - preAst.elseBod = walker.walk(preAst.elseBod, preAst); - } - } - ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; - function walkWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; - function walkDoWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; - function walkBlockChildren(preAst, parent, walker) { - if(preAst.statements) { - preAst.statements = walker.walk(preAst.statements, preAst); - } - } - ChildrenWalkers.walkBlockChildren = walkBlockChildren; - function walkCaseStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; - function walkSwitchStatementChildren(preAst, parent, walker) { - if(preAst.val) { - preAst.val = walker.walk(preAst.val, preAst); - } - if((preAst.caseList) && walker.options.goNextSibling) { - preAst.caseList = walker.walk(preAst.caseList, preAst); - } - } - ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; - function walkTryChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkTryChildren = walkTryChildren; - function walkTryCatchChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if((preAst.catchNode) && walker.options.goNextSibling) { - preAst.catchNode = walker.walk(preAst.catchNode, preAst); - } - } - ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; - function walkTryFinallyChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if(preAst.finallyNode && walker.options.goNextSibling) { - preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); - } - } - ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; - function walkFinallyChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; - function walkCatchChildren(preAst, parent, walker) { - if(preAst.param) { - preAst.param = walker.walk(preAst.param, preAst); - } - if((preAst.body) && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCatchChildren = walkCatchChildren; - function walkRecordChildren(preAst, parent, walker) { - preAst.name = walker.walk(preAst.name, preAst); - if(walker.options.goNextSibling && preAst.members) { - preAst.members = walker.walk(preAst.members, preAst); - } - } - ChildrenWalkers.walkRecordChildren = walkRecordChildren; - function walkNamedTypeChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; - function walkClassDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; - function walkScriptChildren(preAst, parent, walker) { - if(preAst.bod) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkScriptChildren = walkScriptChildren; - function walkTypeDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; - function walkModuleDeclChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; - function walkImportDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.alias) { - preAst.alias = walker.walk(preAst.alias, preAst); - } - } - ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; - function walkWithStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; - function walkLabelChildren(preAst, parent, walker) { - } - ChildrenWalkers.walkLabelChildren = walkLabelChildren; - function walkLabeledStatementChildren(preAst, parent, walker) { - preAst.labels = walker.walk(preAst.labels, preAst); - if(walker.options.goNextSibling) { - preAst.stmt = walker.walk(preAst.stmt, preAst); - } - } - ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; - })(ChildrenWalkers || (ChildrenWalkers = {})); -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (AstWalkerWithDetailCallback) { - function walk(script, callback) { - var pre = function (cur, parent) { - walker.options.goChildren = AstWalkerCallback(true, cur, callback); - return cur; - }; - var post = function (cur, parent) { - AstWalkerCallback(false, cur, callback); - return cur; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); - walker.walk(script, null); - } - AstWalkerWithDetailCallback.walk = walk; - function AstWalkerCallback(pre, ast, callback) { - var nodeType = ast.nodeType; - var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; - if(callback[callbackString]) { - return callback[callbackString](pre, ast); - } - if(callback.DefaultCallback) { - return callback.DefaultCallback(pre, ast); - } - return true; - } - })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); - var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function lastOf(items) { - return (items === null || items.length === 0) ? null : items[items.length - 1]; - } - TypeScript.lastOf = lastOf; - function max(a, b) { - return a >= b ? a : b; - } - TypeScript.max = max; - function min(a, b) { - return a <= b ? a : b; - } - TypeScript.min = min; - var AstPath = (function () { - function AstPath() { - this.asts = []; - this.top = -1; - } - AstPath.reverseIndexOf = function reverseIndexOf(items, index) { - return (items === null || items.length <= index) ? null : items[items.length - index - 1]; - } - AstPath.prototype.clone = function () { - var clone = new AstPath(); - clone.asts = this.asts.map(function (value) { - return value; - }); - clone.top = this.top; - return clone; - }; - AstPath.prototype.pop = function () { - var head = this.ast(); - this.up(); - while(this.asts.length > this.count()) { - this.asts.pop(); - } - return head; - }; - AstPath.prototype.push = function (ast) { - while(this.asts.length > this.count()) { - this.asts.pop(); - } - this.top = this.asts.length; - this.asts.push(ast); - }; - AstPath.prototype.up = function () { - if(this.top <= -1) { - throw new Error("Invalid call to 'up'"); - } - this.top--; - }; - AstPath.prototype.down = function () { - if(this.top == this.ast.length - 1) { - throw new Error("Invalid call to 'down'"); - } - this.top++; - }; - AstPath.prototype.nodeType = function () { - if(this.ast() == null) { - return TypeScript.NodeType.None; - } - return this.ast().nodeType; - }; - AstPath.prototype.ast = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); - }; - AstPath.prototype.parent = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); - }; - AstPath.prototype.count = function () { - return this.top + 1; - }; - AstPath.prototype.get = function (index) { - return this.asts[index]; - }; - AstPath.prototype.isNameOfClass = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfInterface = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfArgument = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfVariable = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfModule = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfFunction = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isChildOfScript = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; - }; - AstPath.prototype.isChildOfModule = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; - }; - AstPath.prototype.isChildOfClass = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; - }; - AstPath.prototype.isArgumentOfClassConstructor = function () { - var ast = lastOf(this.asts); - return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); - }; - AstPath.prototype.isChildOfInterface = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; - }; - AstPath.prototype.isTopLevelImplicitModule = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfScript = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfSwitch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfModule = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfClass = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfInterface = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfBlock = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFor = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCase = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfTry = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCatch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDoWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfForIn = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWith = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFinally = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; - }; - AstPath.prototype.isDefaultCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; - }; - AstPath.prototype.isListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfObjectLit = function () { - return this.isListOfObjectLit(); - }; - AstPath.prototype.isEmptyListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; - }; - AstPath.prototype.isMemberOfObjectLit = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; - }; - AstPath.prototype.isNameOfMemberOfObjectLit = function () { - return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; - }; - AstPath.prototype.isListOfArrayLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isTargetOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; - }; - AstPath.prototype.isMemberOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; - }; - AstPath.prototype.isItemOfList = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; - }; - AstPath.prototype.isThenOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isElseOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDefaultCase = function () { - return this.isBodyOfCase(); - }; - AstPath.prototype.isSingleStatementList = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; - }; - AstPath.prototype.isArgumentListOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentOfFunction = function () { - return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; - }; - AstPath.prototype.isArgumentListOfCall = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentListOfNew = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isSynthesizedBlock = function () { - return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; - }; - return AstPath; - })(); - TypeScript.AstPath = AstPath; - function isValidAstNode(ast) { - if(ast === null) { - return false; - } - if(ast.minChar === -1 || ast.limChar === -1) { - return false; - } - return true; - } - TypeScript.isValidAstNode = isValidAstNode; - var AstPathContext = (function () { - function AstPathContext() { - this.path = new TypeScript.AstPath(); - } - return AstPathContext; - })(); - TypeScript.AstPathContext = AstPathContext; - (function (GetAstPathOptions) { - GetAstPathOptions._map = []; - GetAstPathOptions.Default = 0; - GetAstPathOptions.EdgeInclusive = 1; - GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; - })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); - var GetAstPathOptions = TypeScript.GetAstPathOptions; - function getAstPathToPosition(script, pos, options) { - if (typeof options === "undefined") { options = GetAstPathOptions.Default; } - var lookInComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - var minChar = comments[i].minChar; - var limChar = comments[i].limChar; - if(!comments[i].isBlockComment) { - limChar++; - } - if(pos >= minChar && pos < limChar) { - ctx.path.push(comments[i]); - } - } - } - }; - var pre = function (cur, parent, walker) { - if(isValidAstNode(cur)) { - var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; - var minChar = cur.minChar; - var limChar = cur.limChar + (inclusive ? 1 : 0); - if(pos >= minChar && pos < limChar) { - var previous = ctx.path.ast(); - if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { - ctx.path.push(cur); - } else { - } - } - if(pos < limChar) { - lookInComments(cur.preComments); - } - if(pos >= minChar) { - lookInComments(cur.postComments); - } - if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { - walker.options.goChildren = (minChar <= pos && pos <= limChar); - } - } - return cur; - }; - var ctx = new AstPathContext(); - TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); - return ctx.path; - } - TypeScript.getAstPathToPosition = getAstPathToPosition; - function getTokenizationOffset(script, position) { - var bestOffset = 0; - var pre = function (cur, parent, walker) { - if(TypeScript.isValidAstNode(cur)) { - if(cur.minChar <= position) { - bestOffset = max(bestOffset, cur.minChar); - } - if(cur.minChar > position || cur.limChar < bestOffset) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return bestOffset; - } - TypeScript.getTokenizationOffset = getTokenizationOffset; - function walkAST(ast, callback) { - var pre = function (cur, parent, walker) { - var path = walker.state; - path.push(cur); - callback(path, walker); - return cur; - }; - var post = function (cur, parent, walker) { - var path = walker.state; - path.pop(); - return cur; - }; - var path = new AstPath(); - TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); - } - TypeScript.walkAST = walkAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstLogger = (function () { - function AstLogger(logger) { - this.logger = logger; - } - AstLogger.prototype.logScript = function (script) { - var _this = this; - this.logLinemap(script.locationInfo.lineMap); - var stack = []; - var pre = function (cur, parent) { - stack.push(cur); - var indent = (stack.length - 1) * 2; - _this.logComments(script, cur.preComments, indent); - _this.logNode(script, cur, indent); - _this.logComments(script, cur.postComments, indent); - return cur; - }; - var post = function (cur, parent) { - stack.pop(); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre, post); - }; - AstLogger.prototype.logNode = function (script, cur, indent) { - var msg = this.addPadding("", indent, "| ", true); - msg = msg.concat("+ " + cur.treeViewLabel()); - msg = this.addPadding(msg, 70, " ", false); - msg = msg + this.addLineColumn(script, cur.minChar); - msg = this.addPadding(msg, 80, " ", false); - msg = msg + "=> "; - msg = msg + this.addLineColumn(script, cur.limChar); - msg = this.addPadding(msg, 102, " ", false); - msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); - msg = this.addPadding(msg, 115, " ", false); - msg = msg.concat("sym=" + (cur).sym); - msg = this.addPadding(msg, 135, " ", false); - msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); - this.logger.log(msg); - }; - AstLogger.prototype.logComments = function (script, comments, indent) { - if(comments == null) { - return; - } - for(var i = 0; i < comments.length; i++) { - this.logNode(script, comments[i], indent); - } - }; - AstLogger.prototype.logLinemap = function (linemap) { - var result = "["; - for(var i = 0; i < linemap.length; i++) { - if(i > 0) { - result += ","; - } - result += linemap[i]; - } - result += "]"; - this.logger.log("linemap: " + result); - }; - AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { - var result = (leftPadding ? "" : s); - for(var i = s.length; i < targetLength; i++) { - result = result + paddingString; - } - result = result + (leftPadding ? s : ""); - return result; - }; - AstLogger.prototype.addLineColumn = function (script, position) { - var lineInfo = { - line: -1, - col: -1 - }; - TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); - if(lineInfo.col !== -1) { - lineInfo.col++; - } - return "(" + lineInfo.line + ", " + lineInfo.col + ")"; - }; - return AstLogger; - })(); - TypeScript.AstLogger = AstLogger; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Binder = (function () { - function Binder(checker) { - this.checker = checker; - } - Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { - var extendsList = null; - if(typeLinks) { - extendsList = new Array(); - for(var i = 0, len = typeLinks.length; i < len; i++) { - extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); - } - } - return extendsList; - }; - Binder.prototype.resolveBases = function (scope, type) { - type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); - var i = 0, len = type.extendsList.length; - var derivedIsClass = type.isClassInstance(); - for(; i < len; i++) { - var baseIsClass = type.extendsList[i].isClassInstance(); - if(type.extendsList[i] != this.checker.anyType) { - var baseRef = type.extendsTypeLinks[i].ast; - if(derivedIsClass) { - if(!baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); - } - } else { - if(baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); - } - } - } - } - type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); - if(type.implementsList) { - for(i = 0 , len = type.implementsList.length; i < len; i++) { - var iface = type.implementsList[i]; - var baseRef = type.implementsTypeLinks[i].ast; - if(iface.isClassInstance()) { - if(derivedIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); - } - } - } - } - }; - Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { - var supplyVar = !(signatureGroup.hasImplementation); - for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { - var signature = signatureGroup.signatures[i]; - if(instanceType) { - signature.returnType.type = instanceType; - } else { - this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - this.bindSymbol(scope, signature.parameters[j]); - } - if(signature.hasVariableArgList) { - var lastParam = signature.parameters[paramLen - 1]; - lastParam.argsOffset = paramLen - 1; - if(!lastParam.getType().isArray()) { - this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); - lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); - } - } - } - }; - Binder.prototype.bindType = function (scope, type, instanceType) { - if(instanceType) { - this.bindType(scope, instanceType, null); - } - if(type.hasMembers()) { - var members = type.members; - var ambientMembers = type.ambientMembers; - var typeMembers = type.getAllEnclosedTypes(); - var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); - var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); - var agg = new TypeScript.SymbolAggregateScope(type.symbol); - var prevCurrentModDecl = this.checker.currentModDecl; - var prevBindStatus = this.checker.inBind; - agg.addParentScope(memberScope); - agg.addParentScope(scope); - if(type.isModuleType()) { - this.checker.currentModDecl = type.symbol.declAST; - this.checker.inBind = true; - } - if(members) { - this.bind(agg, type.members.allMembers); - } - if(typeMembers) { - this.bind(agg, typeMembers.allMembers); - } - if(ambientMembers) { - this.bind(agg, ambientMembers.allMembers); - } - if(ambientTypeMembers) { - this.bind(agg, ambientTypeMembers.allMembers); - } - this.checker.currentModDecl = prevCurrentModDecl; - this.checker.inBind = prevBindStatus; - } - if(type.extendsTypeLinks) { - this.resolveBases(scope, type); - } - if(type.construct) { - this.resolveSignatureGroup(type.construct, scope, instanceType); - } - if(type.call) { - this.resolveSignatureGroup(type.call, scope, null); - } - if(type.index) { - this.resolveSignatureGroup(type.index, scope, null); - } - if(type.elementType) { - this.bindType(scope, type.elementType, null); - } - }; - Binder.prototype.bindSymbol = function (scope, symbol) { - if(!symbol.bound) { - var prevLocationInfo = this.checker.locationInfo; - if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[symbol.unitIndex]; - } - switch(symbol.kind()) { - case TypeScript.SymbolKind.Type: { - if(symbol.flags & TypeScript.SymbolFlags.Bound) { - break; - } - var typeSymbol = symbol; - typeSymbol.flags |= TypeScript.SymbolFlags.Bound; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { - this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); - if(typeSymbol.type.isModuleType()) { - for(var i = 0; i < typeSymbol.expansions.length; i++) { - this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); - } - } - } - break; - - } - case TypeScript.SymbolKind.Field: { - this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); - break; - - } - case TypeScript.SymbolKind.Parameter: { - this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); - break; - - } - } - this.checker.locationInfo = prevLocationInfo; - } - symbol.bound = true; - }; - Binder.prototype.bind = function (scope, table) { - table.map(function (key, sym, binder) { - binder.bindSymbol(scope, sym); - }, this); - }; - return Binder; - })(); - TypeScript.Binder = Binder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Base64Format = (function () { - function Base64Format() { } - Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - Base64Format.encode = function encode(inValue) { - if(inValue < 64) { - return Base64Format.encodedValues.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - Base64Format.decodeChar = function decodeChar(inChar) { - if(inChar.length === 1) { - return Base64Format.encodedValues.indexOf(inChar); - } else { - throw TypeError('"' + inChar + '" must have length 1'); - } - } - return Base64Format; - })(); - var Base64VLQFormat = (function () { - function Base64VLQFormat() { } - Base64VLQFormat.encode = function encode(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 + Base64Format.encode(currentDigit); - }while(inValue > 0) - return encodedStr; - } - Base64VLQFormat.decode = function decode(inString) { - var result = 0; - var negative = false; - var shift = 0; - for(var i = 0; i < inString.length; i++) { - var byte = Base64Format.decodeChar(inString[i]); - if(i === 0) { - if((byte & 1) === 1) { - negative = true; - } - result = (byte >> 1) & 15; - } else { - result = result | ((byte & 31) << shift); - } - shift += (i == 0) ? 4 : 5; - if((byte & 32) === 32) { - } else { - return { - value: negative ? -(result) : result, - rest: inString.substr(i + 1) - }; - } - } - throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); - } - return Base64VLQFormat; - })(); - TypeScript.Base64VLQFormat = Base64VLQFormat; -})(TypeScript || (TypeScript = {})); -var JSON2 = { -}; -((function () { - 'use strict'; - function f(n) { - return n < 10 ? '0' + n : n; - } - if(typeof Date.prototype.toJSON !== 'function') { - Date.prototype.toJSON = function (key) { - return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; - }; - var strProto = String.prototype; - var numProto = Number.prototype; - numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { -'\b': '\\b', -'\t': '\\t', -'\n': '\\n', -'\f': '\\f', -'\r': '\\r', -'"': '\\"', -'\\': '\\\\' }, rep; - function quote(string) { - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - function str(key, holder) { - var i, k = null, v, length, mind = gap, partial, value = holder[key]; - if(value && typeof value === 'object' && typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - if(typeof rep === 'function') { - value = rep.call(holder, key, value); - } - switch(typeof value) { - case 'string': { - return quote(value); - - } - case 'number': { - return isFinite(value) ? String(value) : 'null'; - - } - case 'boolean': - case 'null': { - return String(value); - - } - case 'object': { - if(!value) { - return 'null'; - } - gap += indent; - partial = []; - if(Object.prototype.toString.apply(value, []) === '[object Array]') { - length = value.length; - for(i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - if(rep && typeof rep === 'object') { - length = rep.length; - for(i = 0; i < length; i += 1) { - if(typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - for(k in value) { - if(Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; - gap = mind; - return v; - - } - } - } - if(typeof JSON2.stringify !== 'function') { - JSON2.stringify = function (value, replacer, space) { - var i; - gap = ''; - indent = ''; - if(typeof space === 'number') { - for(i = 0; i < space; i += 1) { - indent += ' '; - } - } else { - if(typeof space === 'string') { - indent = space; - } - } - rep = replacer; - if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - return str('', { - '': value - }); - }; - } - if(typeof JSON2.parse !== 'function') { - JSON2.parse = function (text, reviver) { - var j; - function walk(holder, key) { - var k = null, v, value = holder[key]; - if(value && typeof value === 'object') { - for(k in value) { - if(Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if(v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - text = String(text); - cx.lastIndex = 0; - if(cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - j = eval('(' + text + ')'); - return typeof reviver === 'function' ? walk({ - '': j - }, '') : j; - } - throw new SyntaxError('JSON.parse'); - }; - } -})()); -var TypeScript; -(function (TypeScript) { - var SourceMapPosition = (function () { - function SourceMapPosition() { } - return SourceMapPosition; - })(); - TypeScript.SourceMapPosition = SourceMapPosition; - var SourceMapping = (function () { - function SourceMapping() { - this.start = new SourceMapPosition(); - this.end = new SourceMapPosition(); - this.nameIndex = -1; - this.childMappings = []; - } - return SourceMapping; - })(); - TypeScript.SourceMapping = SourceMapping; - var SourceMapper = (function () { - function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter) { - this.jsFile = jsFile; - this.sourceMapOut = sourceMapOut; - this.errorReporter = errorReporter; - this.sourceMappings = []; - this.currentMappings = []; - this.names = []; - this.currentNameIndex = []; - this.currentMappings.push(this.sourceMappings); - jsFileName = TypeScript.switchToForwardSlashes(jsFileName); - this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); - var removalIndex = jsFileName.lastIndexOf(this.jsFileName); - var fixedPath = jsFileName.substring(0, removalIndex); - this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); - } - SourceMapper.MapFileExtension = ".map"; - SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { - var sourceMapper = allSourceMappers[0]; - sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); - var sourceMapOut = sourceMapper.sourceMapOut; - var mappingsString = ""; - var tsFiles = []; - var prevEmittedColumn = 0; - var prevEmittedLine = 0; - var prevSourceColumn = 0; - var prevSourceLine = 0; - var prevSourceIndex = 0; - var prevNameIndex = 0; - var namesList = []; - var namesCount = 0; - var emitComma = false; - var recordedPosition = null; - for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { - sourceMapper = allSourceMappers[sourceMapperIndex]; - var currentSourceIndex = tsFiles.length; - tsFiles.push(sourceMapper.tsFileName); - if(sourceMapper.names.length > 0) { - namesList.push.apply(namesList, sourceMapper.names); - } - var recordSourceMapping = function (mappedPosition, nameIndex) { - if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { - return; - } - if(prevEmittedLine !== mappedPosition.emittedLine) { - while(prevEmittedLine < mappedPosition.emittedLine) { - prevEmittedColumn = 0; - mappingsString = mappingsString + ";"; - prevEmittedLine++; - } - emitComma = false; - } else { - if(emitComma) { - mappingsString = mappingsString + ","; - } - } - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); - prevEmittedColumn = mappedPosition.emittedColumn; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); - prevSourceIndex = currentSourceIndex; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); - prevSourceLine = mappedPosition.sourceLine - 1; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); - prevSourceColumn = mappedPosition.sourceColumn; - if(nameIndex >= 0) { - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); - prevNameIndex = namesCount + nameIndex; - } - emitComma = true; - recordedPosition = mappedPosition; - }; - var recordSourceMappingSiblings = function (sourceMappings) { - for(var i = 0; i < sourceMappings.length; i++) { - var sourceMapping = sourceMappings[i]; - recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); - recordSourceMappingSiblings(sourceMapping.childMappings); - recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); - } - }; - recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); - namesCount = namesCount + sourceMapper.names.length; - } - if(mappingsString != "") { - sourceMapOut.Write(JSON2.stringify({ - version: 3, - file: sourceMapper.jsFileName, - sources: tsFiles, - names: namesList, - mappings: mappingsString - })); - } - try { - sourceMapOut.Close(); - } catch (ex) { - sourceMapper.errorReporter.emitterError(null, ex.message); - } - } - return SourceMapper; - })(); - TypeScript.SourceMapper = SourceMapper; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (EmitContainer) { - EmitContainer._map = []; - EmitContainer._map[0] = "Prog"; - EmitContainer.Prog = 0; - EmitContainer._map[1] = "Module"; - EmitContainer.Module = 1; - EmitContainer._map[2] = "DynamicModule"; - EmitContainer.DynamicModule = 2; - EmitContainer._map[3] = "Class"; - EmitContainer.Class = 3; - EmitContainer._map[4] = "Constructor"; - EmitContainer.Constructor = 4; - EmitContainer._map[5] = "Function"; - EmitContainer.Function = 5; - EmitContainer._map[6] = "Args"; - EmitContainer.Args = 6; - EmitContainer._map[7] = "Interface"; - EmitContainer.Interface = 7; - })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); - var EmitContainer = TypeScript.EmitContainer; - var EmitState = (function () { - function EmitState() { - this.column = 0; - this.line = 0; - this.pretty = false; - this.inObjectLiteral = false; - this.container = EmitContainer.Prog; - } - return EmitState; - })(); - TypeScript.EmitState = EmitState; - var EmitOptions = (function () { - function EmitOptions(settings) { - this.ioHost = null; - this.outputMany = true; - this.commonDirectoryPath = ""; - this.minWhitespace = settings.minWhitespace; - this.propagateConstants = settings.propagateConstants; - this.emitComments = settings.emitComments; - this.outputOption = settings.outputOption; - } - EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { - if(this.outputMany) { - var updatedFileName = fileName; - if(this.outputOption != "") { - updatedFileName = fileName.replace(this.commonDirectoryPath, ""); - updatedFileName = this.outputOption + updatedFileName; - } - return extensionChanger(updatedFileName, false); - } else { - return extensionChanger(this.outputOption, true); - } - }; - return EmitOptions; - })(); - TypeScript.EmitOptions = EmitOptions; - var Indenter = (function () { - function Indenter() { - this.indentAmt = 0; - } - Indenter.indentStep = 4; - Indenter.indentStepString = " "; - Indenter.indentStrings = []; - Indenter.prototype.increaseIndent = function () { - this.indentAmt += Indenter.indentStep; - }; - Indenter.prototype.decreaseIndent = function () { - this.indentAmt -= Indenter.indentStep; - }; - Indenter.prototype.getIndent = function () { - var indentString = Indenter.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { - indentString += Indenter.indentStepString; - } - Indenter.indentStrings[this.indentAmt] = indentString; - } - return indentString; - }; - return Indenter; - })(); - TypeScript.Indenter = Indenter; - var Emitter = (function () { - function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { - this.checker = checker; - this.emittingFileName = emittingFileName; - this.outfile = outfile; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.prologueEmitted = false; - this.thisClassNode = null; - this.thisFnc = null; - this.moduleDeclList = []; - this.moduleName = ""; - this.emitState = new EmitState(); - this.indenter = new Indenter(); - this.ambientModule = false; - this.modAliasId = null; - this.firstModAlias = null; - this.allSourceMappers = []; - this.sourceMapper = null; - this.captureThisStmtString = "var _this = this;"; - this.varListCountStack = [ - 0 - ]; - } - Emitter.prototype.setSourceMappings = function (mapper) { - this.allSourceMappers.push(mapper); - this.sourceMapper = mapper; - }; - Emitter.prototype.writeToOutput = function (s) { - this.outfile.Write(s); - this.emitState.column += s.length; - }; - Emitter.prototype.writeToOutputTrimmable = function (s) { - if(this.emitOptions.minWhitespace) { - s = s.replace(/[\s]*/g, ''); - } - this.writeToOutput(s); - }; - Emitter.prototype.writeLineToOutput = function (s) { - if(this.emitOptions.minWhitespace) { - this.writeToOutput(s); - var c = s.charCodeAt(s.length - 1); - if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { - this.writeToOutput(' '); - } - } else { - this.outfile.WriteLine(s); - this.emitState.column = 0; - this.emitState.line++; - } - }; - Emitter.prototype.writeCaptureThisStatement = function (ast) { - this.emitIndent(); - this.recordSourceMappingStart(ast); - this.writeToOutput(this.captureThisStmtString); - this.recordSourceMappingEnd(ast); - this.writeLineToOutput(""); - }; - Emitter.prototype.setInVarBlock = function (count) { - this.varListCountStack[this.varListCountStack.length - 1] = count; - }; - Emitter.prototype.setInObjectLiteral = function (val) { - var temp = this.emitState.inObjectLiteral; - this.emitState.inObjectLiteral = val; - return temp; - }; - Emitter.prototype.setContainer = function (c) { - var temp = this.emitState.container; - this.emitState.container = c; - return temp; - }; - Emitter.prototype.getIndentString = function () { - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - Emitter.prototype.emitIndent = function () { - this.writeToOutput(this.getIndentString()); - }; - Emitter.prototype.emitCommentInPlace = function (comment) { - this.recordSourceMappingStart(comment); - var text = comment.getText(); - var hadNewLine = false; - if(comment.isBlockComment) { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.writeToOutput(text[0]); - if(text.length > 1 || comment.endsLine) { - this.writeLineToOutput(""); - for(var i = 1; i < text.length; i++) { - this.emitIndent(); - this.writeLineToOutput(text[i]); - } - hadNewLine = true; - } - } else { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.writeLineToOutput(text[0]); - hadNewLine = true; - } - if(hadNewLine) { - this.emitIndent(); - } else { - this.writeToOutput(" "); - } - this.recordSourceMappingEnd(comment); - }; - Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { - var comments = pre ? ast.preComments : ast.postComments; - if(ast.isParenthesized && !pre) { - this.writeToOutput(")"); - } - if(this.emitOptions.emitComments && comments && comments.length != 0) { - for(var i = 0; i < comments.length; i++) { - this.emitCommentInPlace(comments[i]); - } - } - if(ast.isParenthesized && pre) { - this.writeToOutput("("); - } - }; - Emitter.prototype.emitObjectLiteral = function (content) { - this.writeLineToOutput("{"); - this.indenter.increaseIndent(); - var inObjectLiteral = this.setInObjectLiteral(true); - this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); - this.setInObjectLiteral(inObjectLiteral); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - }; - Emitter.prototype.emitArrayLiteral = function (content) { - this.writeToOutput("["); - if(content) { - this.writeLineToOutput(""); - this.indenter.increaseIndent(); - this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); - this.indenter.decreaseIndent(); - this.emitIndent(); - } - this.writeToOutput("]"); - }; - Emitter.prototype.emitNew = function (target, args) { - this.writeToOutput("new "); - if(target.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = target; - if(typeRef.arrayCount) { - this.writeToOutput("Array()"); - } else { - this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); - this.writeToOutput("()"); - } - } else { - this.emitJavascript(target, TypeScript.TokenID.Tilde, false); - this.recordSourceMappingStart(args); - this.writeToOutput("("); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } - }; - Emitter.prototype.tryEmitConstant = function (dotExpr) { - if(!this.emitOptions.propagateConstants) { - return false; - } - var propertyName = dotExpr.operand2; - if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { - if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { - if(propertyName.sym.declAST) { - var boundDecl = propertyName.sym.declAST; - if(boundDecl.init && (boundDecl.init.nodeType == TypeScript.NodeType.NumberLit)) { - var numLit = boundDecl.init; - this.writeToOutput(numLit.value.toString()); - var comment = " /* "; - comment += propertyName.actualText; - comment += " */ "; - this.writeToOutput(comment); - return true; - } - } - } - } - return false; - }; - Emitter.prototype.emitCall = function (callNode, target, args) { - if(!this.emitSuperCall(callNode)) { - if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput("("); - } - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("_super.call"); - } else { - this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); - } - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput(")"); - } - this.recordSourceMappingStart(args); - this.writeToOutput("("); - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("this"); - if(args && args.members.length) { - this.writeToOutput(", "); - } - } - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } else { - this.indenter.decreaseIndent(); - this.indenter.decreaseIndent(); - var constructorCall = new TypeScript.ASTList(); - constructorCall.members[0] = callNode; - this.emitConstructorCalls(constructorCall, this.thisClassNode); - this.indenter.increaseIndent(); - this.indenter.increaseIndent(); - } - } - }; - Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - this.recordSourceMappingStart(classDecl); - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - baseSymbol = (baseExpr).target.type.symbol; - } else { - baseSymbol = baseExpr.type.symbol; - } - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.emitIndent(); - this.writeToOutput("_super.call(this"); - var args = (baseExpr).arguments; - if(args && (args.members.length > 0)) { - this.writeToOutput(", "); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - } else { - if(baseExpr.type && (baseExpr.type.isClassInstance())) { - this.emitIndent(); - this.writeToOutput(classDecl.name.actualText + "._super.constructor"); - this.writeToOutput(".call(this)"); - } - } - } - this.recordSourceMappingEnd(classDecl); - }; - Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { - var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); - var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); - this.emitParensAndCommentsInPlace(funcDecl, true); - if(shouldParenthesize) { - this.writeToOutput("("); - } - this.recordSourceMappingStart(funcDecl); - if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { - this.writeToOutput("function "); - } - if(printName) { - var id = funcDecl.getNameText(); - if(id && !funcDecl.isAccessor()) { - if(funcDecl.name) { - this.recordSourceMappingStart(funcDecl.name); - } - this.writeToOutput(id); - if(funcDecl.name) { - this.recordSourceMappingEnd(funcDecl.name); - } - } - } - this.writeToOutput("("); - var argsLen = 0; - var i = 0; - var arg; - var defaultArgs = []; - if(funcDecl.arguments) { - var tempContainer = this.setContainer(EmitContainer.Args); - argsLen = funcDecl.arguments.members.length; - var printLen = argsLen; - if(funcDecl.variableArgList) { - printLen--; - } - for(i = 0; i < printLen; i++) { - arg = funcDecl.arguments.members[i]; - if(arg.init) { - defaultArgs.push(arg); - } - this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); - if(i < (printLen - 1)) { - this.writeToOutput(", "); - } - } - this.setContainer(tempContainer); - } - this.writeLineToOutput(") {"); - if(funcDecl.isConstructor) { - this.recordSourceMappingNameStart("constructor"); - } else { - if(funcDecl.isGetAccessor()) { - this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); - } else { - if(funcDecl.isSetAccessor()) { - this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); - } else { - this.recordSourceMappingNameStart(funcDecl.getNameText()); - } - } - } - this.indenter.increaseIndent(); - for(i = 0; i < defaultArgs.length; i++) { - var arg = defaultArgs[i]; - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); - this.writeLineToOutput("; }"); - this.recordSourceMappingEnd(arg); - } - if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { - if(funcDecl.arguments) { - argsLen = funcDecl.arguments.members.length; - for(i = 0; i < argsLen; i++) { - arg = funcDecl.arguments.members[i]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - this.emitConstructorCalls(bases, classDecl); - } - } - if(hasSelfRef) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.variableArgList) { - argsLen = funcDecl.arguments.members.length; - var lastArg = funcDecl.arguments.members[argsLen - 1]; - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var "); - this.recordSourceMappingStart(lastArg.id); - this.writeToOutput(lastArg.id.actualText); - this.recordSourceMappingEnd(lastArg.id); - this.writeLineToOutput(" = [];"); - this.recordSourceMappingEnd(lastArg); - this.emitIndent(); - this.writeToOutput("for ("); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var _i = 0;"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput(" "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput("; "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i++"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(") {"); - this.indenter.increaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { - var nProps = (this.thisClassNode.members).members.length; - for(var i = 0; i < nProps; i++) { - if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(funcDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(funcDecl.endingToken); - this.recordSourceMappingEnd(funcDecl); - if(shouldParenthesize) { - this.writeToOutput(")"); - } - this.recordSourceMappingEnd(funcDecl); - this.emitParensAndCommentsInPlace(funcDecl, false); - if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition) || funcDecl.isConstructor)) { - this.writeLineToOutput(""); - } else { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { - if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { - this.writeLineToOutput(";"); - } - } - } - }; - Emitter.prototype.emitJavascriptModule = function (moduleDecl) { - var modName = moduleDecl.name.actualText; - if(TypeScript.isTSFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 3)); - } else { - if(TypeScript.isSTRFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 4)); - } - } - if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { - var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); - var prevOutFile = this.outfile; - var prevOutFileName = this.emittingFileName; - var prevAllSourceMappers = this.allSourceMappers; - var prevSourceMapper = this.sourceMapper; - var prevColumn = this.emitState.column; - var prevLine = this.emitState.line; - var temp = this.setContainer(EmitContainer.Module); - var svModuleName = this.moduleName; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; - var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); - this.moduleName = moduleDecl.name.actualText; - if(isDynamicMod) { - var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); - var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; - modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); - if(this.emitOptions.ioHost) { - if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { - this.emittingFileName = modFilePath; - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); - if(prevSourceMapper != null) { - this.allSourceMappers = []; - var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); - this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter)); - this.emitState.column = 0; - this.emitState.line = 0; - } - } else { - TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); - } - } - this.setContainer(EmitContainer.DynamicModule); - this.recordSourceMappingStart(moduleDecl); - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - var dependencyList = "[\"require\", \"exports\""; - var importList = "require, exports"; - var importStatement = null; - for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { - importStatement = (moduleDecl.mod).importedModules[i]; - if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { - if(i <= (moduleDecl.mod).importedModules.length - 1) { - dependencyList += ", "; - importList += ", "; - } - importList += "__" + importStatement.id.actualText + "__"; - dependencyList += importStatement.firstAliasedModToString(); - } - } - for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { - dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; - } - dependencyList += "]"; - this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); - } else { - } - } else { - if(!isExported) { - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("var "); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(moduleDecl); - this.emitIndent(); - } - this.writeToOutput("("); - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("function ("); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(") {"); - } - if(!isWholeFile) { - this.recordSourceMappingNameStart(this.moduleName); - } - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.increaseIndent(); - } - if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { - this.writeCaptureThisStatement(moduleDecl); - } - this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.decreaseIndent(); - } - this.emitIndent(); - if(isDynamicMod) { - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("})"); - } else { - } - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl); - if(this.outfile != prevOutFile) { - this.Close(); - if(prevSourceMapper != null) { - this.allSourceMappers = prevAllSourceMappers; - this.sourceMapper = prevSourceMapper; - this.emitState.column = prevColumn; - this.emitState.line = prevLine; - } - this.outfile = prevOutFile; - this.emittingFileName = prevOutFileName; - } - } else { - var containingMod = null; - if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { - containingMod = moduleDecl.type.symbol.container.declAST; - } - var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); - this.recordSourceMappingStart(moduleDecl.endingToken); - if(temp == EmitContainer.Prog && isExported) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); - } else { - if(isExported || temp == EmitContainer.Prog) { - var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); - } else { - if(!isExported && temp != EmitContainer.Prog) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); - } else { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeLineToOutput(")();"); - } - } - } - this.recordSourceMappingEnd(moduleDecl); - if(temp != EmitContainer.Prog && isExported) { - this.emitIndent(); - this.recordSourceMappingStart(moduleDecl); - if(parentIsDynamic) { - this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); - } else { - this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); - } - this.recordSourceMappingEnd(moduleDecl); - } - } - this.setContainer(temp); - this.moduleName = svModuleName; - this.moduleDeclList.length--; - } - }; - Emitter.prototype.emitIndex = function (operand1, operand2) { - var temp = this.setInObjectLiteral(false); - this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); - this.writeToOutput("["); - this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput("]"); - this.setInObjectLiteral(temp); - }; - Emitter.prototype.emitStringLiteral = function (text) { - this.writeToOutput(text); - }; - Emitter.prototype.emitJavascriptFunction = function (funcDecl) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { - return; - } - var temp; - var tempFnc = this.thisFnc; - this.thisFnc = funcDecl; - if(funcDecl.isConstructor) { - temp = this.setContainer(EmitContainer.Constructor); - } else { - temp = this.setContainer(EmitContainer.Function); - } - var bases = null; - var hasSelfRef = false; - var funcName = funcDecl.getNameText(); - if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { - var tempLit = this.setInObjectLiteral(false); - if(this.thisClassNode) { - bases = this.thisClassNode.extendsList; - } - hasSelfRef = Emitter.shouldCaptureThis(funcDecl); - this.recordSourceMappingStart(funcDecl); - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { - this.writeToOutput("this." + funcName + " = "); - this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); - } else { - this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); - } - this.setInObjectLiteral(tempLit); - } - this.setContainer(temp); - this.thisFnc = tempFnc; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition)) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { - if(this.thisClassNode) { - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - } else { - if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { - this.emitIndent(); - var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - } - }; - Emitter.prototype.emitAmbientVarDecl = function (varDecl) { - if(varDecl.init) { - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.recordSourceMappingEnd(varDecl); - this.writeToOutput(";"); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.varListCount = function () { - return this.varListCountStack[this.varListCountStack.length - 1]; - }; - Emitter.prototype.emitVarDeclVar = function () { - if(this.varListCount() >= 0) { - this.writeToOutput("var "); - this.setInVarBlock(-this.varListCount()); - } - return true; - }; - Emitter.prototype.onEmitVar = function () { - if(this.varListCount() > 0) { - this.setInVarBlock(this.varListCount() - 1); - } else { - if(this.varListCount() < 0) { - this.setInVarBlock(this.varListCount() + 1); - } - } - }; - Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { - if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { - this.emitAmbientVarDecl(varDecl); - this.onEmitVar(); - } else { - var sym = varDecl.sym; - var hasInitializer = (varDecl.init != null); - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { - var type = (sym.container).type; - if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { - if(this.emitState.container != EmitContainer.Args) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { - this.writeToOutput(sym.container.name + "."); - } else { - this.writeToOutput("this."); - } - } - } else { - if(type.hasImplementation()) { - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - this.emitVarDeclVar(); - } else { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { - this.writeToOutput("."); - } else { - if(this.emitState.container == EmitContainer.DynamicModule) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(this.moduleName + "."); - } - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { - this.writeToOutput("this."); - } else { - this.emitVarDeclVar(); - } - } - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - this.emitVarDeclVar(); - } - } - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - if(hasInitializer) { - this.writeToOutputTrimmable(" = "); - this.varListCountStack.push(0); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.varListCountStack.pop(); - } - this.onEmitVar(); - if((tokenId != TypeScript.TokenID.OpenParen)) { - if(this.varListCount() < 0) { - this.writeToOutput(", "); - } else { - if(tokenId != TypeScript.TokenID.For) { - this.writeToOutputTrimmable(";"); - } - } - } - this.recordSourceMappingEnd(varDecl); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.declEnclosed = function (moduleDecl) { - if(moduleDecl == null) { - return true; - } - for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { - if(this.moduleDeclList[i] == moduleDecl) { - return true; - } - } - return false; - }; - Emitter.prototype.emitJavascriptName = function (name, addThis) { - var sym = name.sym; - this.emitParensAndCommentsInPlace(name, true); - this.recordSourceMappingStart(name); - if(!name.isMissing()) { - if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { - if(sym.container && (sym.container.name != TypeScript.globalId)) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } else { - if(sym.kind() == TypeScript.SymbolKind.Field) { - var fieldSym = sym; - if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { - if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { - if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } - } else { - if(sym.isInstanceProperty()) { - this.emitThis(); - this.writeToOutput("."); - } - } - } else { - if(sym.kind() == TypeScript.SymbolKind.Type) { - if(sym.isInstanceProperty()) { - var typeSym = sym; - var type = typeSym.type; - if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { - this.emitThis(); - this.writeToOutput("."); - } - } else { - if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { - this.writeToOutput(sym.container.name + "."); - } - } - } - } - } - } else { - if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { - this.writeToOutput("this."); - } - } - } - if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { - var moduleDecl = sym.declAST; - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("__" + this.modAliasId + "__;"); - } else { - var modPath = name.actualText; - var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); - modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); - modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); - this.writeToOutput("require(" + modPath + ")"); - } - } else { - this.writeToOutput(name.actualText); - } - } - this.recordSourceMappingEnd(name); - this.emitParensAndCommentsInPlace(name, false); - }; - Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { - if(stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); - if(emitEmptyBod || hasContents) { - var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); - this.recordSourceMappingStart(stmts); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(" {"); - this.indenter.increaseIndent(); - } - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - } - this.recordSourceMappingEnd(stmts); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else { - if(emitEmptyBod) { - this.writeToOutput("{ }"); - } - } - }; - Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if(stmts.nodeType != TypeScript.NodeType.Block) { - if(stmts.nodeType == TypeScript.NodeType.List) { - var stmtList = stmts; - if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { - this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); - this.writeLineToOutput(""); - } else { - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - }; - Emitter.prototype.recordSourceMappingNameStart = function (name) { - if(this.sourceMapper) { - var finalName = name; - if(!name) { - finalName = ""; - } else { - if(this.sourceMapper.currentNameIndex.length > 0) { - finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex.length - 1] + "." + name; - } - } - this.sourceMapper.names.push(finalName); - this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); - } - }; - Emitter.prototype.recordSourceMappingNameEnd = function () { - if(this.sourceMapper) { - this.sourceMapper.currentNameIndex.pop(); - } - }; - Emitter.prototype.recordSourceMappingStart = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - var lineCol = { - line: -1, - col: -1 - }; - var sourceMapping = new TypeScript.SourceMapping(); - sourceMapping.start.emittedColumn = this.emitState.column; - sourceMapping.start.emittedLine = this.emitState.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); - sourceMapping.start.sourceColumn = lineCol.col; - sourceMapping.start.sourceLine = lineCol.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); - sourceMapping.end.sourceColumn = lineCol.col; - sourceMapping.end.sourceLine = lineCol.line; - if(this.sourceMapper.currentNameIndex.length > 0) { - sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; - } - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - siblings.push(sourceMapping); - this.sourceMapper.currentMappings.push(sourceMapping.childMappings); - } - }; - Emitter.prototype.recordSourceMappingEnd = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - this.sourceMapper.currentMappings.pop(); - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - var sourceMapping = siblings[siblings.length - 1]; - sourceMapping.end.emittedColumn = this.emitState.column; - sourceMapping.end.emittedLine = this.emitState.line; - } - }; - Emitter.prototype.Close = function () { - if(this.sourceMapper != null) { - TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); - } - try { - this.outfile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if (typeof emitPrologue === "undefined") { emitPrologue = false; } - if(ast == null) { - return; - } else { - if(ast.nodeType != TypeScript.NodeType.List) { - this.emitPrologue(emitPrologue); - this.emitJavascript(ast, tokenId, startLine); - } else { - var list = ast; - if(list.members.length == 0) { - return; - } - this.emitParensAndCommentsInPlace(ast, true); - var len = list.members.length; - for(var i = 0; i < len; i++) { - if(emitPrologue) { - if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { - this.emitPrologue(requiresExtendsBlock); - emitPrologue = false; - } - } - if(i == 1 && emitClassPropertiesAfterSuperCall) { - var constructorDecl = (this.thisClassNode).constructorDecl; - if(constructorDecl && constructorDecl.arguments) { - var argsLen = constructorDecl.arguments.members.length; - for(var iArg = 0; iArg < argsLen; iArg++) { - var arg = constructorDecl.arguments.members[iArg]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - var nProps = (this.thisClassNode.members).members.length; - for(var iMember = 0; iMember < nProps; iMember++) { - if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[iMember]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - var emitNode = list.members[i]; - var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); - if(onlyStatics ? !isStaticDecl : isStaticDecl) { - continue; - } - this.emitJavascript(emitNode, tokenId, startLine); - if(delimiter && (i < (len - 1))) { - if(startLine) { - this.writeLineToOutput(delimiter); - } else { - this.writeToOutput(delimiter); - } - } else { - if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { - this.writeLineToOutput(""); - } - } - } - this.emitParensAndCommentsInPlace(ast, false); - } - } - }; - Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { - if(ast == null) { - return; - } - if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { - if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { - this.emitIndent(); - } - } - ast.emit(this, tokenId, startLine); - if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { - this.writeToOutput(";"); - } - }; - Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { - if(!(funcDecl.accessorSymbol).hasBeenEmitted) { - var accessorSymbol = funcDecl.accessorSymbol; - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); - this.indenter.increaseIndent(); - if(accessorSymbol.getter) { - var getter = accessorSymbol.getter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(getter); - this.writeToOutput("get: "); - this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); - this.writeLineToOutput(","); - } - if(accessorSymbol.setter) { - var setter = accessorSymbol.setter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(setter); - this.writeToOutput("set: "); - this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); - this.writeLineToOutput(","); - } - this.emitIndent(); - this.writeLineToOutput("enumerable: true,"); - this.emitIndent(); - this.writeLineToOutput("configurable: true"); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("});"); - this.recordSourceMappingEnd(funcDecl); - accessorSymbol.hasBeenEmitted = true; - } - }; - Emitter.prototype.emitPrototypeMember = function (member, className) { - if(member.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = member; - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, className, true); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); - this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); - this.writeLineToOutput(";"); - } - } else { - if(member.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = member; - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(className + ".prototype." + varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.recordSourceMappingEnd(varDecl); - this.writeLineToOutput(";"); - } - } - } - }; - Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { - if(base.members) { - var baseSymbol = base.symbol; - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - base.members.allMembers.map(function (key, s, c) { - var sym = s; - if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { - this.recordSourceMappingStart(sym.declAST); - this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); - this.recordSourceMappingEnd(sym.declAST); - } - }, null); - } - if(base.extendsList) { - for(var i = 0, len = base.extendsList.length; i < len; i++) { - this.emitAddBaseMethods(className, base.extendsList[i], classDecl); - } - } - }; - Emitter.prototype.emitJavascriptClass = function (classDecl) { - if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { - var svClassNode = this.thisClassNode; - var i = 0; - this.thisClassNode = classDecl; - var className = classDecl.name.actualText; - this.emitParensAndCommentsInPlace(classDecl, true); - var temp = this.setContainer(EmitContainer.Class); - this.recordSourceMappingStart(classDecl); - if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { - this.writeToOutput("this." + className); - } else { - this.writeToOutput("var " + className); - } - var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; - var baseNameDecl = null; - var baseName = null; - if(hasBaseClass) { - this.writeLineToOutput(" = (function (_super) {"); - } else { - this.writeLineToOutput(" = (function () {"); - } - this.recordSourceMappingNameStart(className); - this.indenter.increaseIndent(); - if(hasBaseClass) { - baseNameDecl = classDecl.extendsList.members[0]; - baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; - this.emitIndent(); - this.writeLineToOutput("__extends(" + className + ", _super);"); - } - this.emitIndent(); - var constrDecl = classDecl.constructorDecl; - if(constrDecl) { - this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); - } else { - var wroteProps = 0; - this.recordSourceMappingStart(classDecl); - this.indenter.increaseIndent(); - this.writeToOutput("function " + classDecl.name.actualText + "() {"); - this.recordSourceMappingNameStart("constructor"); - if(hasBaseClass) { - this.writeLineToOutput(""); - this.emitIndent(); - this.writeLineToOutput("_super.apply(this, arguments);"); - wroteProps++; - } - if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { - this.writeCaptureThisStatement(classDecl); - } - var members = (this.thisClassNode.members).members; - for(var i = 0; i < members.length; i++) { - if(members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.writeLineToOutput(""); - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - wroteProps++; - } - } - } - if(wroteProps) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } else { - this.writeLineToOutput(" }"); - this.indenter.decreaseIndent(); - } - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl); - } - var membersLen = classDecl.members.members.length; - for(var j = 0; j < membersLen; j++) { - var memberDecl = classDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var fn = memberDecl; - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { - if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { - this.emitPrototypeMember(fn, className); - } else { - if(fn.isAccessor()) { - this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(fn); - this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); - this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); - this.writeLineToOutput(";"); - } - } - } - } else { - if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = memberDecl; - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(varDecl); - } - } - } else { - throw Error("We want to catch this"); - } - } - } - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeLineToOutput("return " + className + ";"); - this.recordSourceMappingEnd(classDecl.endingToken); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl.endingToken); - this.recordSourceMappingStart(classDecl); - this.writeToOutput(")("); - if(hasBaseClass) { - this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); - } - this.writeToOutput(");"); - this.recordSourceMappingEnd(classDecl); - if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { - this.writeLineToOutput(""); - this.emitIndent(); - var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(classDecl); - this.writeToOutput(modName + "." + className + " = " + className + ";"); - this.recordSourceMappingEnd(classDecl); - } - this.emitIndent(); - this.recordSourceMappingEnd(classDecl); - this.emitParensAndCommentsInPlace(classDecl, false); - this.setContainer(temp); - this.thisClassNode = svClassNode; - } - }; - Emitter.prototype.emitPrologue = function (reqInherits) { - if(!this.prologueEmitted) { - if(reqInherits) { - this.prologueEmitted = true; - this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); - this.writeLineToOutput(" function __() { this.constructor = d; }"); - this.writeLineToOutput(" __.prototype = b.prototype;"); - this.writeLineToOutput(" d.prototype = new __();"); - this.writeLineToOutput("};"); - } - if(this.checker.mustCaptureGlobalThis) { - this.prologueEmitted = true; - this.writeLineToOutput(this.captureThisStmtString); - } - } - }; - Emitter.prototype.emitSuperReference = function () { - this.writeToOutput("_super.prototype"); - }; - Emitter.prototype.emitSuperCall = function (callEx) { - if(callEx.target.nodeType == TypeScript.NodeType.Dot) { - var dotNode = callEx.target; - if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { - this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); - this.writeToOutput(".call("); - this.emitThis(); - if(callEx.arguments && callEx.arguments.members.length > 0) { - this.writeToOutput(", "); - this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - return true; - } - } - return false; - }; - Emitter.prototype.emitThis = function () { - if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { - this.writeToOutput("_this"); - } else { - this.writeToOutput("this"); - } - }; - Emitter.shouldCaptureThis = function shouldCaptureThis(func) { - return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); - } - Emitter.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitOptions.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return Emitter; - })(); - TypeScript.Emitter = Emitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ErrorReporter = (function () { - function ErrorReporter(outfile) { - this.outfile = outfile; - this.parser = null; - this.checker = null; - this.lineCol = { - line: 0, - col: 0 - }; - this.emitAsComments = true; - this.hasErrors = false; - this.pushToErrorSink = false; - this.errorSink = []; - } - ErrorReporter.prototype.getCapturedErrors = function () { - return this.errorSink; - }; - ErrorReporter.prototype.freeCapturedErrors = function () { - this.errorSink = []; - }; - ErrorReporter.prototype.captureError = function (emsg) { - this.errorSink[this.errorSink.length] = emsg; - }; - ErrorReporter.prototype.setErrOut = function (outerr) { - this.outfile = outerr; - this.emitAsComments = false; - }; - ErrorReporter.prototype.emitPrefix = function () { - if(this.emitAsComments) { - this.outfile.Write("// "); - } - this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); - }; - ErrorReporter.prototype.writePrefix = function (ast) { - if(ast) { - this.setError(ast); - } else { - this.lineCol.line = 0; - this.lineCol.col = 0; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.writePrefixFromSym = function (symbol) { - if(symbol && this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); - } else { - this.lineCol.line = -1; - this.lineCol.col = -1; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.setError = function (ast) { - if(ast) { - ast.flags |= TypeScript.ASTFlags.Error; - if(this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); - } - } - }; - ErrorReporter.prototype.reportError = function (ast, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(ast && this.parser.errorRecovery && this.parser.errorCallback) { - var len = (ast.limChar - ast.minChar); - this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefix(ast); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(this.parser.errorRecovery && this.parser.errorCallback) { - this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefixFromSym(symbol); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.emitterError = function (ast, message) { - this.reportError(ast, message); - throw Error("EmitError"); - }; - ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { - this.reportError(ast, "Duplicate identifier '" + name + "'"); - }; - ErrorReporter.prototype.showRef = function (ast, text, symbol) { - var defLineCol = { - line: -1, - col: -1 - }; - this.parser.getSourceLineCol(defLineCol, symbol.location); - this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); - }; - ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); - }; - ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not refer to a value"); - }; - ErrorReporter.prototype.styleError = function (ast, msg) { - var bkThrow = this.pushToErrorSink; - this.pushToErrorSink = false; - this.reportError(ast, "STYLE: " + msg); - this.pushToErrorSink = bkThrow; - }; - ErrorReporter.prototype.simpleError = function (ast, msg) { - this.reportError(ast, msg); - }; - ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { - this.reportErrorFromSym(sym, msg); - }; - ErrorReporter.prototype.invalidSuperReference = function (ast) { - this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); - }; - ErrorReporter.prototype.valueCannotBeModified = function (ast) { - this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); - }; - ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { - var targetType = ast.target.type; - var typeName = targetType.getScopedTypeName(scope); - if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { - this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); - } else { - var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; - this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); - } - }; - ErrorReporter.prototype.indexLHS = function (ast, scope) { - var targetType = ast.operand1.type.getScopedTypeName(scope); - var indexType = ast.operand2.type.getScopedTypeName(scope); - this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); - }; - ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { - if(!t1) { - t1 = this.checker.anyType; - } - if(!t2) { - t2 = this.checker.anyType; - } - var reason = comparisonInfo ? comparisonInfo.message : ""; - if(op) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } else { - this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } - }; - ErrorReporter.prototype.expectedClassOrInterface = function (ast) { - this.simpleError(ast, "Expected var, class, interface, or module"); - }; - ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); - }; - return ErrorReporter; - })(); - TypeScript.ErrorReporter = ErrorReporter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeContext) { - TypeContext._map = []; - TypeContext.NoTypes = 0; - TypeContext.ArraySuffix = 1; - TypeContext.Primitive = 2; - TypeContext.Named = 4; - TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; - TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; - })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); - var TypeContext = TypeScript.TypeContext; - (function (ParseState) { - ParseState._map = []; - ParseState._map[0] = "None"; - ParseState.None = 0; - ParseState._map[1] = "StartScript"; - ParseState.StartScript = 1; - ParseState._map[2] = "StartStatementList"; - ParseState.StartStatementList = 2; - ParseState._map[3] = "StartStatement"; - ParseState.StartStatement = 3; - ParseState._map[4] = "StartFncDecl"; - ParseState.StartFncDecl = 4; - ParseState._map[5] = "FncDeclName"; - ParseState.FncDeclName = 5; - ParseState._map[6] = "FncDeclArgs"; - ParseState.FncDeclArgs = 6; - ParseState._map[7] = "FncDeclReturnType"; - ParseState.FncDeclReturnType = 7; - ParseState._map[8] = "ForInit"; - ParseState.ForInit = 8; - ParseState._map[9] = "ForInitAfterVar"; - ParseState.ForInitAfterVar = 9; - ParseState._map[10] = "ForCondStart"; - ParseState.ForCondStart = 10; - ParseState._map[11] = "EndStmtList"; - ParseState.EndStmtList = 11; - ParseState._map[12] = "EndScript"; - ParseState.EndScript = 12; - })(TypeScript.ParseState || (TypeScript.ParseState = {})); - var ParseState = TypeScript.ParseState; - var QuickParseResult = (function () { - function QuickParseResult(Script, endLexState) { - this.Script = Script; - this.endLexState = endLexState; - } - return QuickParseResult; - })(); - TypeScript.QuickParseResult = QuickParseResult; - var Parser = (function () { - function Parser() { - this.varLists = []; - this.scopeLists = []; - this.staticsLists = []; - this.scanner = new TypeScript.Scanner(); - this.currentToken = null; - this.needTerminator = false; - this.inFunction = false; - this.inInterfaceDecl = false; - this.currentClassDecl = null; - this.inFncDecl = false; - this.anonId = new TypeScript.Identifier("_anonymous"); - this.style_requireSemi = false; - this.style_funcInLoop = true; - this.incremental = false; - this.errorRecovery = false; - this.outfile = undefined; - this.errorCallback = null; - this.state = ParseState.StartStatementList; - this.ambientModule = false; - this.ambientClass = false; - this.topLevel = true; - this.allowImportDeclaration = true; - this.currentUnitIndex = (-1); - this.prevIDTok = null; - this.statementInfoStack = new Array(); - this.hasTopLevelImportOrExport = false; - this.strictMode = false; - this.nestingLevel = 0; - this.prevExpr = null; - this.currentClassDefinition = null; - this.parsingClassConstructorDefinition = false; - this.parsingDeclareFile = false; - this.amdDependencies = []; - this.inferPropertiesFromThisAssignment = false; - this.requiresExtendsBlock = false; - this.fname = ""; - } - Parser.prototype.resetStmtStack = function () { - this.statementInfoStack = new Array(); - }; - Parser.prototype.inLoop = function () { - for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { - if(this.statementInfoStack[j].stmt.isLoop()) { - return true; - } - } - return false; - }; - Parser.prototype.pushStmt = function (stmt, labels) { - var info = { - stmt: stmt, - labels: labels - }; - this.statementInfoStack.push(info); - }; - Parser.prototype.popStmt = function () { - return this.statementInfoStack.pop(); - }; - Parser.prototype.resolveJumpTarget = function (jump) { - var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); - var len = this.statementInfoStack.length; - for(var i = len - 1; i >= 0; i--) { - var info = this.statementInfoStack[i]; - if(jump.target) { - if(info.labels && (info.labels.members.length > 0)) { - for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { - var label = info.labels.members[j]; - if(label.id.text == resolvedTarget) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - } else { - if(info.stmt.isLoop()) { - jump.setResolvedTarget(this, info.stmt); - return; - } else { - if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - } - if(jump.target) { - this.reportParseError("could not find enclosing statement with label " + jump.target); - } else { - if(jump.nodeType == TypeScript.NodeType.Break) { - this.reportParseError("break statement requires enclosing loop or switch"); - } else { - this.reportParseError("continue statement requires enclosing loop"); - } - } - }; - Parser.prototype.setErrorRecovery = function (outfile) { - this.outfile = outfile; - this.errorRecovery = true; - }; - Parser.prototype.getSourceLineCol = function (lineCol, minChar) { - TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); - }; - Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { - var id = new TypeScript.Identifier(text, hasEscapeSequence); - id.minChar = minChar; - return id; - }; - Parser.prototype.reportParseStyleError = function (message) { - this.reportParseError("STYLE: " + message); - }; - Parser.prototype.reportParseError = function (message, startPos, pos) { - if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } - if (typeof pos === "undefined") { pos = this.scanner.pos; } - var len = Math.max(1, pos - startPos); - if(this.errorCallback) { - this.errorCallback(startPos, len, message, this.currentUnitIndex); - } else { - if(this.errorRecovery) { - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, startPos); - if(this.outfile) { - this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); - } - } else { - throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); - } - } - }; - Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(tokenId, errorRecoverySet, errorText); - }; - Parser.prototype.skip = function (errorRecoverySet) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; - var ersTok = TypeScript.ErrorRecoverySet.None; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - var pendingRightCurlies = 0; - while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { - if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - pendingRightCurlies++; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - pendingRightCurlies--; - } - } - this.currentToken = this.scanner.scan(); - ersTok = TypeScript.ErrorRecoverySet.None; - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - } - }; - Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - if(this.currentToken.tokenId != tokenId) { - errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; - this.reportParseError(errorText); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - } - } else { - this.currentToken = this.scanner.scan(); - } - }; - Parser.prototype.pushDeclLists = function () { - this.staticsLists.push(new TypeScript.ASTList()); - this.varLists.push(new TypeScript.ASTList()); - this.scopeLists.push(new TypeScript.ASTList()); - }; - Parser.prototype.popDeclLists = function () { - this.staticsLists.pop(); - this.varLists.pop(); - this.scopeLists.pop(); - }; - Parser.prototype.topVarList = function () { - return this.varLists[this.varLists.length - 1]; - }; - Parser.prototype.topScopeList = function () { - return this.scopeLists[this.scopeLists.length - 1]; - }; - Parser.prototype.topStaticsList = function () { - return this.staticsLists[this.staticsLists.length - 1]; - }; - Parser.prototype.parseComment = function (comment) { - if(comment) { - var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); - c.minChar = comment.startPos; - c.limChar = comment.startPos + comment.value.length; - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, c.minChar); - c.minLine = lineCol.line; - this.getSourceLineCol(lineCol, c.limChar); - c.limLine = lineCol.line; - if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { - var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); - if(dependencyPath) { - this.amdDependencies.push(dependencyPath); - } - if(TypeScript.getImplicitImport(comment.value)) { - this.hasTopLevelImportOrExport = true; - } - } - return c; - } else { - return null; - } - }; - Parser.prototype.parseCommentsInner = function (comments) { - if(comments) { - var commentASTs = new Array(); - for(var i = 0; i < comments.length; i++) { - commentASTs.push(this.parseComment(comments[i])); - } - return commentASTs; - } else { - return null; - } - }; - Parser.prototype.parseComments = function () { - var comments = this.scanner.getComments(); - return this.parseCommentsInner(comments); - }; - Parser.prototype.parseCommentsForLine = function (line) { - var comments = this.scanner.getCommentsForLine(line); - return this.parseCommentsInner(comments); - }; - Parser.prototype.combineComments = function (comment1, comment2) { - if(comment1 == null) { - return comment2; - } else { - if(comment2 == null) { - return comment1; - } else { - return comment1.concat(comment2); - } - } - }; - Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Enum declaration requires identifier"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.startPos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - this.pushDeclLists(); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); - mapDecl.varFlags |= TypeScript.VarFlags.Exported; - mapDecl.varFlags |= TypeScript.VarFlags.Private; - mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); - mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); - members.append(mapDecl); - var lastValue = null; - for(; ; ) { - var minChar = this.scanner.startPos; - var limChar; - var memberName = null; - var memberValue = null; - var preComments = null; - var postComments = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } else { - this.reportParseError("Expected identifer of enum member"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - } - } - } - limChar = this.scanner.pos; - preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - postComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - this.currentToken = this.scanner.scan(); - memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - lastValue = memberValue; - limChar = memberValue.limChar; - } else { - if(lastValue == null) { - memberValue = new TypeScript.NumberLiteral(0); - lastValue = memberValue; - } else { - memberValue = new TypeScript.NumberLiteral(lastValue.value + 1); - lastValue = memberValue; - } - var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); - members.append(map); - } - var member = new TypeScript.VarDecl(memberName, this.nestingLevel); - member.minChar = minChar; - member.limChar = limChar; - member.init = memberValue; - member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); - member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); - if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { - member.varFlags |= TypeScript.VarFlags.Constant; - } - member.preComments = preComments; - members.append(member); - member.postComments = postComments; - member.varFlags |= TypeScript.VarFlags.Exported; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { - continue; - } - } - break; - } - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - members.limChar = this.scanner.lastTokenLimChar(); - var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), this.topScopeList(), endingToken); - modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; - this.popDeclLists(); - modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return modDecl; - }; - Parser.prototype.parseDottedName = function (enclosedList) { - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.preComments = this.parseComments(); - enclosedList[enclosedList.length] = id; - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - this.parseDottedName(enclosedList); - } - } else { - this.reportParseError("need identifier after '.'"); - } - }; - Parser.prototype.isValidImportPath = function (importPath) { - importPath = TypeScript.stripQuotes(importPath); - if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { - return false; - } - return true; - }; - Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { - var name = null; - var alias = null; - var importDecl = null; - var minChar = this.scanner.startPos; - var isDynamicImport = false; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - } else { - this.reportParseError("Expected identifer after 'import'"); - name = new TypeScript.MissingIdentifier(); - } - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - var aliasPreComments = this.parseComments(); - var limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Module) { - limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } else { - if(!this.allowImportDeclaration) { - this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); - } - } - var aliasText = this.currentToken.getText(); - alias = TypeScript.Identifier.fromToken(this.currentToken); - alias.minChar = this.scanner.startPos; - alias.limChar = this.scanner.pos; - if(!this.isValidImportPath((alias).text)) { - this.reportParseError("Invalid import path"); - } - isDynamicImport = true; - this.currentToken = this.scanner.scan(); - alias.preComments = aliasPreComments; - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - alias.preComments = aliasPreComments; - } - } - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(alias) { - alias.postComments = this.parseComments(); - } - } - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - limChar = this.scanner.pos; - } - } else { - this.reportParseError("Expected module name"); - alias = new TypeScript.MissingIdentifier(); - alias.minChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - alias.limChar = this.scanner.startPos; - } else { - alias.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - alias.flags |= TypeScript.ASTFlags.Error; - limChar = alias.limChar; - } - importDecl = new TypeScript.ImportDeclaration(name, alias); - importDecl.isDynamicImport = isDynamicImport; - importDecl.minChar = minChar; - importDecl.limChar = limChar; - return importDecl; - }; - Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var svAmbient = this.ambientModule; - var svTopLevel = this.topLevel; - this.topLevel = false; - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.ambientModule = true; - } - this.currentToken = this.scanner.scan(); - var name = null; - var enclosedList = null; - this.pushDeclLists(); - var minChar = this.scanner.startPos; - var isDynamicMod = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var nameText = this.currentToken.getText(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - isDynamicMod = true; - if(!this.ambientModule) { - this.reportParseError("Only ambient dynamic modules may have string literal names"); - } - if(!svTopLevel) { - this.reportParseError("Dynamic modules may not be nested within other modules"); - } - } - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - this.reportParseError("Module name missing"); - name = new TypeScript.Identifier(""); - name.minChar = minChar; - name.limChar = minChar; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - enclosedList = new Array(); - this.parseDottedName(enclosedList); - } - if(name == null) { - name = new TypeScript.MissingIdentifier(); - } - var moduleBody = new TypeScript.ASTList(); - var bodyMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(svTopLevel && isDynamicMod) { - this.allowImportDeclaration = true; - } else { - this.allowImportDeclaration = false; - } - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); - moduleBody.minChar = bodyMinChar; - moduleBody.limChar = this.scanner.pos; - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var limChar = this.scanner.lastTokenLimChar(); - var moduleDecl; - this.allowImportDeclaration = svTopLevel; - if(enclosedList && (enclosedList.length > 0)) { - var len = enclosedList.length; - var innerName = enclosedList[len - 1]; - var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), this.topScopeList(), endingToken); - innerDecl.preComments = preComments; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - innerDecl.minChar = minChar; - innerDecl.limChar = limChar; - this.popDeclLists(); - var outerModBod; - for(var i = len - 2; i >= 0; i--) { - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - innerName = enclosedList[i]; - innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); - outerModBod.minChar = innerDecl.minChar = minChar; - outerModBod.limChar = innerDecl.limChar = limChar; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - outerModBod.minChar = minChar; - outerModBod.limChar = limChar; - moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); - } else { - moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), this.topScopeList(), endingToken); - moduleDecl.preComments = preComments; - this.popDeclLists(); - } - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - if(isDynamicMod) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; - } - this.ambientModule = svAmbient; - this.topLevel = svTopLevel; - moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - moduleDecl.limChar = moduleBody.limChar; - return moduleDecl; - }; - Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { - var result = new TypeScript.TypeReference(term, 0); - result.minChar = minChar; - while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { - this.currentToken = this.scanner.scan(); - result.arrayCount++; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); - } - result.limChar = this.scanner.lastTokenLimChar(); - return result; - }; - Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var op2 = TypeScript.Identifier.fromToken(this.currentToken); - op2.minChar = this.scanner.startPos; - op2.limChar = this.scanner.pos; - var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); - dotNode.minChar = term.minChar; - dotNode.limChar = op2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); - } else { - this.reportParseError("need identifier after '.'"); - if(this.errorRecovery) { - term.flags |= TypeScript.ASTFlags.DotLHS; - term.limChar = this.scanner.lastTokenLimChar(); - return term; - } else { - var eop2 = new TypeScript.MissingIdentifier(); - eop2.minChar = this.scanner.pos; - eop2.limChar = this.scanner.pos; - var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); - edotNode.flags |= TypeScript.ASTFlags.Error; - edotNode.minChar = term.minChar; - edotNode.limChar = eop2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); - } - } - } else { - if(tail) { - return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); - } else { - return term; - } - } - }; - Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { - var minChar = this.scanner.startPos; - var isConstructorMember = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Void: { - if(!allowVoid) { - this.reportParseError("void not a valid type in this context"); - } - - } - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.String: { - var text = TypeScript.tokenTable[this.currentToken.tokenId].text; - var predefinedIdentifier = new TypeScript.Identifier(text); - predefinedIdentifier.minChar = minChar; - predefinedIdentifier.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); - } - - case TypeScript.TokenID.Identifier: { - var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); - ident.limChar = this.scanner.pos; - return this.parseNamedType(errorRecoverySet, minChar, ident, true); - - } - case TypeScript.TokenID.OpenBrace: { - return this.parseObjectType(minChar, errorRecoverySet); - - } - case TypeScript.TokenID.New: { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { - this.reportParseError("Expected '('"); - } else { - isConstructorMember = true; - } - - } - case TypeScript.TokenID.OpenParen: { - var formals = new TypeScript.ASTList(); - var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); - this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); - var returnType = this.parseTypeReference(errorRecoverySet, true); - var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); - funcDecl.returnTypeAnnotation = returnType; - funcDecl.variableArgList = variableArgList; - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - if(isConstructorMember) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = null; - } - funcDecl.minChar = minChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); - } - - default: { - this.reportParseError("Expected type name"); - var etr = new TypeScript.TypeReference(null, 0); - etr.flags |= TypeScript.ASTFlags.Error; - etr.minChar = this.scanner.pos; - etr.limChar = this.scanner.pos; - return etr; - - } - } - }; - Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { - this.currentToken = this.scanner.scan(); - var members = new TypeScript.ASTList(); - members.minChar = minChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); - interfaceDecl.minChar = minChar; - interfaceDecl.limChar = members.limChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); - }; - Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { - this.state = ParseState.StartStatementList; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - var savedInFunction = this.inFunction; - this.inFunction = true; - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); - bod.minChar = bodMinChar; - bod.limChar = this.scanner.pos; - this.inFunction = savedInFunction; - var ec = new TypeScript.EndCode(); - ec.minChar = bod.limChar; - ec.limChar = ec.minChar; - bod.append(ec); - }; - Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { - this.pushDeclLists(); - var svStmtStack = this.statementInfoStack; - this.resetStmtStack(); - var bod = null; - var wasShorthand = false; - var isAnonLambda = false; - var limChar; - if(requiresSignature) { - limChar = this.scanner.pos; - if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { - this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - } else { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); - } - } else { - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { - if(isMethod) { - this.reportParseError("'=>' may not be used for class methods"); - } - wasShorthand = true; - this.currentToken = this.scanner.scan(); - } - if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.returnExpression = retExpr; - retStmt.minChar = retExpr.minChar; - retStmt.limChar = retExpr.limChar; - bod.minChar = bodMinChar; - bod.append(retStmt); - } else { - isAnonLambda = wasShorthand; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - } - limChar = this.scanner.pos; - } - var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); - this.popDeclLists(); - var scopeList = this.topScopeList(); - scopeList.append(funcDecl); - var staticFuncDecl = false; - if(!requiresSignature) { - if(!wasShorthand || isAnonLambda) { - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = this.scanner.startPos; - funcDecl.endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(isAnonLambda) { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - } - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = bod.members[0].minChar; - funcDecl.endingToken.limChar = bod.members[0].limChar; - } - } - funcDecl.minChar = minChar; - funcDecl.limChar = limChar; - if(!requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Definition; - } - this.statementInfoStack = svStmtStack; - return funcDecl; - }; - Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { - var _this = this; - var translateBinExOperand = function (operand) { - if(operand.nodeType == TypeScript.NodeType.Comma) { - return _this.transformAnonymousArgsIntoFormals(formals, operand); - } else { - if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { - var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; - var arg = new TypeScript.ArgDecl(opArg); - arg.preComments = opArg.preComments; - arg.postComments = opArg.postComments; - arg.minChar = operand.minChar; - arg.limChar = operand.limChar; - if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - arg.isOptional = true; - } - if(operand.nodeType == TypeScript.NodeType.Asg) { - arg.init = (operand).operand2; - } - formals.append(arg); - return arg.isOptional || arg.init; - } else { - _this.reportParseError("Invalid lambda argument"); - } - } - return false; - }; - if(argList) { - if(argList.nodeType == TypeScript.NodeType.Comma) { - var commaList = argList; - if(commaList.operand1.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); - } - if(commaList.operand2.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); - } - var isOptional = translateBinExOperand(commaList.operand1); - isOptional = translateBinExOperand(commaList.operand2) || isOptional; - return isOptional; - } else { - return translateBinExOperand(argList); - } - } - }; - Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { - formals.minChar = this.scanner.startPos; - if(isIndexer) { - this.currentToken = this.scanner.scan(); - } else { - if(!isLambda) { - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); - } - } - var sawEllipsis = false; - var firstArg = true; - var hasOptional = false; - var haveFirstArgID = false; - if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { - hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); - haveFirstArgID = true; - } - while(true) { - var munchedArg = false; - var argFlags = TypeScript.VarFlags.None; - var argMinChar = this.scanner.startPos; - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { - this.reportParseError("Static properties can not be declared as parameter properties"); - this.currentToken = this.scanner.scan(); - } - } - } - if(argFlags != TypeScript.VarFlags.None) { - if(!isClassConstr) { - this.reportParseError("only constructor parameters can be properties"); - } - this.currentToken = this.scanner.scan(); - if(TypeScript.isModifier(this.currentToken)) { - this.reportParseError("Multiple modifiers may not be applied to parameters"); - this.currentToken = this.scanner.scan(); - } - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - this.currentToken = this.scanner.scan(); - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - sawEllipsis = true; - this.currentToken = this.scanner.scan(); - if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - sawEllipsis = false; - } - } - } - var argId = null; - if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - argId = TypeScript.Identifier.fromToken(this.currentToken); - argId.minChar = this.scanner.startPos; - argId.limChar = this.scanner.pos; - } - if(haveFirstArgID || argId) { - munchedArg = true; - var type = null; - var arg = null; - if(haveFirstArgID && formals.members.length) { - arg = formals.members[formals.members.length - 1]; - if(arg.isOptional) { - hasOptional = true; - } - } else { - arg = new TypeScript.ArgDecl(argId); - if(isGetter) { - this.reportParseError("Property getters may not take any arguments"); - } - if(isSetter && !firstArg) { - this.reportParseError("Property setters may only take one argument"); - } - arg.minChar = argMinChar; - arg.preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - arg.isOptional = true; - hasOptional = true; - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - type = this.parseTypeReference(errorRecoverySet, false); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(isSig) { - this.reportParseError("Arguments in signatures may not have default values"); - } - hasOptional = true; - this.currentToken = this.scanner.scan(); - arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); - } - if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { - this.reportParseError("Optional parameters may only be followed by other optional parameters"); - } - if(sawEllipsis && arg.isOptionalArg()) { - this.reportParseError("Varargs may not be optional or have default parameters"); - } - if(sawEllipsis && !type) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - } - arg.postComments = this.parseComments(); - arg.typeExpr = type; - arg.limChar = this.scanner.lastTokenLimChar(); - arg.varFlags |= argFlags; - if(!haveFirstArgID) { - formals.append(arg); - } else { - haveFirstArgID = false; - } - } - firstArg = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - if((munchedArg) && (!sawEllipsis)) { - this.currentToken = this.scanner.scan(); - continue; - } else { - this.reportParseError("Unexpected ',' in argument list"); - if(this.errorRecovery) { - this.currentToken = this.scanner.scan(); - continue; - } - } - } else { - break; - } - } - if(isIndexer) { - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } else { - if(expectClosingRParen) { - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } - } - formals.limChar = this.scanner.lastTokenLimChar(); - return sawEllipsis; - }; - Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var prevInConstr = this.parsingClassConstructorDefinition; - this.parsingClassConstructorDefinition = false; - var name = null; - var fnMin = this.scanner.startPos; - var minChar = this.scanner.pos; - var prevNestingLevel = this.nestingLevel; - var preComments = this.parseComments(); - var isLambda = !!lambdaArgContext; - this.nestingLevel = 0; - if((!this.style_funcInLoop) && this.inLoop()) { - this.reportParseStyleError("function declaration in loop"); - } - if(!isMethod && !isStatic && !indexer && !lambdaArgContext) { - this.currentToken = this.scanner.scan(); - this.state = ParseState.StartFncDecl; - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - if(isDecl) { - this.reportParseError("Function declaration must include identifier"); - this.nestingLevel = prevNestingLevel; - return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); - } - } else { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } else { - if(methodName) { - name = methodName; - } - } - this.state = ParseState.FncDeclName; - var args = new TypeScript.ASTList(); - var variableArgList = false; - var isOverload = false; - var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); - var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); - } - this.state = ParseState.FncDeclArgs; - var returnType = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { - this.reportParseError("Property setters may not declare a return type"); - } - returnType = this.parseTypeReference(errorRecoverySet, true); - } - if(indexer && args.members.length == 0) { - this.reportParseError("Index signatures require a parameter type to be specified"); - } - this.state = ParseState.FncDeclReturnType; - if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { - this.reportParseError("Expected '=>'"); - } - if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && (!isMethod || !(this.ambientModule || this.ambientClass || this.inInterfaceDecl)) && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - isOverload = true; - isDecl = false; - requiresSignature = true; - } - var svInFncDecl = this.inFncDecl; - this.inFncDecl = true; - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); - this.inFncDecl = svInFncDecl; - funcDecl.variableArgList = variableArgList; - funcDecl.isOverload = isOverload; - if(!requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Definition; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(indexer) { - funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; - } - funcDecl.returnTypeAnnotation = returnType; - if(isMethod) { - funcDecl.fncFlags |= TypeScript.FncFlags.Method; - funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; - } - funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - this.nestingLevel = prevNestingLevel; - this.parsingClassConstructorDefinition = prevInConstr; - funcDecl.preComments = preComments; - return funcDecl; - }; - Parser.prototype.convertToTypeReference = function (ast) { - var result; - switch(ast.nodeType) { - case TypeScript.NodeType.TypeRef: { - return ast; - - } - case TypeScript.NodeType.Name: { - result = new TypeScript.TypeReference(ast, 0); - result.minChar = ast.minChar; - result.limChar = ast.limChar; - return result; - - } - case TypeScript.NodeType.Index: { - var expr = ast; - result = this.convertToTypeReference(expr.operand1); - if(result) { - result.arrayCount++; - result.minChar = expr.minChar; - result.limChar = expr.limChar; - return result; - } else { - var etr = new TypeScript.AST(TypeScript.NodeType.Error); - return etr; - } - } - - } - return null; - }; - Parser.prototype.parseArgList = function (errorRecoverySet) { - var args = new TypeScript.ASTList(); - args.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { - while(true) { - if(args.members.length > 65535) { - this.reportParseError("max number of args exceeded"); - break; - } - var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - args.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - } - args.limChar = this.scanner.pos; - return args; - }; - Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { - var keyword = true; - var currentList = extendsList; - for(; ; ) { - if(keyword) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - currentList = implementsList; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - } - this.currentToken = this.scanner.scan(); - keyword = false; - } - var baseName = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var minChar = this.scanner.startPos; - baseName = TypeScript.Identifier.fromToken(this.currentToken); - baseName.minChar = minChar; - baseName.limChar = this.scanner.pos; - baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); - } else { - this.reportParseError("Expected base name"); - if(this.errorRecovery) { - baseName = new TypeScript.MissingIdentifier(); - baseName.minChar = this.scanner.pos; - baseName.limChar = this.scanner.pos; - baseName.flags |= TypeScript.ASTFlags.Error; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - if(isClass) { - this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); - } else { - this.reportParseError("Interfaces may not be extended with a call expression"); - } - } else { - currentList.append(baseName); - } - if(isClass && currentList == extendsList && extendsList.members.length > 1) { - this.reportParseError("A class may only extend one other class"); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - continue; - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - currentList = extendsList; - keyword = true; - continue; - } - } - break; - } - }; - Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - this.reportParseError("const modifier is implicit for class"); - } - if(this.parsingDeclareFile || this.ambientModule) { - modifiers |= TypeScript.Modifiers.Ambient; - modifiers |= TypeScript.Modifiers.Exported; - } - var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; - var svAmbientClass = this.ambientClass; - this.ambientClass = classIsMarkedAsAmbient; - this.currentToken = this.scanner.scan(); - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("class missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - var requiresSignature = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); - } - var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); - this.currentClassDefinition = classDecl; - this.parseClassElements(classDecl, errorRecoverySet, modifiers); - if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - classDecl.varFlags |= TypeScript.VarFlags.Exported; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - classDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - classDecl.varFlags |= TypeScript.VarFlags.Class; - this.ambientClass = svAmbientClass; - classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return classDecl; - }; - Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { - var modifiers = parentModifiers; - var resetModifiers = false; - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); - this.nestingLevel++; - var currentMemberMinChar = this.scanner.startPos; - var wasGetOrSetId = false; - while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - var scanNext = true; - var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Duplicate 'get' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Getter already marked as a setter"); - } - modifiers |= TypeScript.Modifiers.Getter; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Duplicate 'set' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Setter already marked as a getter"); - } - modifiers |= TypeScript.Modifiers.Setter; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Private; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Public; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Static) { - if(modifiers & TypeScript.Modifiers.Static) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Static; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { - if(modifiers != parentModifiers) { - this.reportParseError("Constructors may not have modifiers"); - } - this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - resetModifiers = true; - } else { - if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { - var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); - var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - if(wasGetOrSetId) { - modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); - wasGetOrSetId = false; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - } else { - if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Property accessors must be functions"); - } - var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); - if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - scanNext = false; - } - } else { - if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - scanNext = false; - varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Expected ';'"); - scanNext = false; - } - } - } - } - resetModifiers = true; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Super) { - this.reportParseError("Base class initializers must be the first statement in a class definition"); - } else { - if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { - wasGetOrSetId = true; - scanNext = false; - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); - resetModifiers = true; - } - } - } - } - } - } - } - } - } - } - if(scanNext) { - this.currentToken = this.scanner.scan(); - } - if(resetModifiers) { - modifiers = parentModifiers; - currentMemberMinChar = this.scanner.startPos; - resetModifiers = false; - } - } - var membersLimChar = this.scanner.pos; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - classDecl.endingToken = new TypeScript.ASTSpan(); - classDecl.endingToken.minChar = this.scanner.startPos; - classDecl.endingToken.limChar = this.scanner.pos; - if(!this.currentClassDefinition.members.members.length) { - this.currentClassDefinition.preComments = this.parseComments(); - } - this.currentToken = this.scanner.scan(); - } - this.nestingLevel--; - this.currentClassDefinition.members.minChar = membersMinChar; - this.currentClassDefinition.members.limChar = membersLimChar; - this.currentClassDefinition.limChar = membersLimChar; - this.currentClassDefinition = null; - }; - Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { - this.parsingClassConstructorDefinition = true; - var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - var args = new TypeScript.ASTList(); - var variableArgList = false; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); - if(args.members.length > 0) { - var lastArg = args.members[args.members.length - 1]; - } - } - var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; - if(requiresSignature) { - for(var i = 0; i < args.members.length; i++) { - var arg = args.members[i]; - if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { - this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); - } - } - } - if(!requiresSignature) { - this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; - } - var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); - constructorFuncDecl.preComments = preComments; - if(requiresSignature && !isAmbient) { - constructorFuncDecl.isOverload = true; - } - constructorFuncDecl.variableArgList = variableArgList; - this.currentClassDecl = null; - constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); - constructorFuncDecl.classDecl = this.currentClassDefinition; - if(isAmbient) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(requiresSignature) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; - } - if(this.currentClassDefinition.constructorDecl) { - if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { - this.reportParseError("Duplicate constructor definition"); - } - } - if(isAmbient || !constructorFuncDecl.isSignature()) { - this.currentClassDefinition.constructorDecl = constructorFuncDecl; - } - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; - this.parsingClassConstructorDefinition = false; - return constructorFuncDecl; - }; - Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.minChar = minChar; - var isStatic = false; - varDecl.preComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(!(modifiers & TypeScript.Modifiers.Static)) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - varDecl.limChar = this.scanner.pos; - } - if(modifiers & TypeScript.Modifiers.Static) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - isStatic = true; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } else { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - if(isDeclaredInConstructor) { - varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; - } - if(!isDeclaredInConstructor && !isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; - } - this.currentClassDefinition.knownMemberNames[text.actualText] = true; - if(!isDeclaredInConstructor) { - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; - } - varDecl.postComments = this.parseComments(); - return varDecl; - }; - Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); - var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; - if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { - this.reportParseError("Property accessors may not be declared in ambient classes"); - } - var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } - var funcDecl = ast; - funcDecl.minChar = minChar; - if(funcDecl.bod !== null) { - funcDecl.limChar = funcDecl.bod.limChar; - } - if(modifiers & TypeScript.Modifiers.Private) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); - } - } - funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; - return funcDecl; - }; - Parser.prototype.parseTypeMember = function (errorRecoverySet) { - var minChar = this.scanner.startPos; - var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); - if(propertyDecl) { - propertyDecl.minChar = minChar; - if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - } - } - return propertyDecl; - }; - Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; - while(true) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.CloseBrace: - case TypeScript.TokenID.EndOfFile: { - members.limChar = this.scanner.pos; - return; - - } - } - var element = this.parseTypeMember(errorRecoverySet); - if(element) { - members.append(element); - } - } - }; - Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - this.currentToken = this.scanner.scan(); - var minChar = this.scanner.pos; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("interface missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - this.reportParseError("Expected 'extends'"); - } - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - extendsList.minChar = this.scanner.startPos; - this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Private; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Public; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; - } - interfaceDecl.limChar = members.limChar; - interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return interfaceDecl; - }; - Parser.prototype.makeVarDecl = function (id, nest) { - var varDecl = new TypeScript.VarDecl(id, nest); - var currentVarList = this.topVarList(); - if(currentVarList) { - currentVarList.append(varDecl); - } - return varDecl; - }; - Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic) { - var text = null; - var minChar = this.scanner.startPos; - var nameLimChar = minChar; - var isNew = false; - var isIndexer = false; - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - requireSignature = true; - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { - if(!requireSignature && !isStatic) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - text = new TypeScript.MissingIdentifier(); - } - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.New) { - if(requireSignature) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - isNew = true; - } - } - if(!isNew) { - if(!requireSignature) { - this.currentToken = this.scanner.scan(); - } - text = new TypeScript.Identifier("new"); - text.minChar = this.scanner.pos - 3; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - } - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { - isIndexer = true; - text = new TypeScript.Identifier("__item"); - } else { - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - var eminChar = this.scanner.startPos; - var curpos = this.scanner.pos; - this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); - if(this.scanner.pos == curpos) { - this.currentToken = this.scanner.scan(); - } - var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - epd.flags |= TypeScript.ASTFlags.Error; - epd.minChar = eminChar; - epd.limChar = this.scanner.lastTokenLimChar(); - return epd; - } - } else { - if(wasAccessorID) { - text = TypeScript.Identifier.fromToken(this.prevIDTok); - text.minChar = this.scanner.lastTokenLimChar() - 3; - text.limChar = this.scanner.lastTokenLimChar(); - nameLimChar = text.limChar; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { - this.currentToken = this.scanner.scan(); - } - this.prevIDTok = null; - } else { - text = TypeScript.Identifier.fromToken(this.currentToken); - text.minChar = this.scanner.startPos; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - if(this.inInterfaceDecl && text) { - text.flags |= TypeScript.ASTFlags.OptionalName; - } else { - this.reportParseError("Optional properties may only be declared on interface or object types"); - } - this.currentToken = this.scanner.scan(); - } - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { - var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; - if(isIndexer) { - ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; - } - var ast = this.parseFncDecl(ers, true, requireSignature, !this.inFncDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); - var funcDecl; - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } else { - funcDecl = ast; - } - if(funcDecl.name) { - funcDecl.name.minChar = minChar; - funcDecl.name.limChar = nameLimChar; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(modifiers & TypeScript.Modifiers.Ambient) { - this.reportParseError("Property accessors may not be declared in ambient types"); - } - } - if(text == null) { - if(isNew) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = this.currentClassDecl; - } else { - funcDecl.hint = "_call"; - funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; - } - } - return funcDecl; - } else { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.preComments = this.parseComments(); - varDecl.minChar = minChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(requireSignature) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.text; - funcDecl.boundToProperty = varDecl; - } else { - if(isAccessor) { - this.reportParseError("Accessors may only be functions"); - } - } - } else { - varDecl.limChar = this.scanner.pos; - } - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - return varDecl; - } - }; - Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { - var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); - var minChar = this.scanner.startPos; - var varDecl = null; - var declList = null; - var multivar = false; - this.currentToken = this.scanner.scan(); - var varDeclPreComments = this.parseComments(); - while(true) { - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - this.reportParseError("Expected identifier in variable declaration"); - if(this.errorRecovery) { - varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - varDecl.minChar = minChar; - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); - if(this.strictMode && (varDeclName.text == "eval")) { - this.reportParseError("'eval' may not name a variable in strict mode"); - } - varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); - varDecl.id.minChar = this.scanner.startPos; - varDecl.id.limChar = this.scanner.pos; - varDecl.preComments = varDeclPreComments; - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - varDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - varDecl.varFlags |= TypeScript.VarFlags.Exported; - } - varDecl.minChar = minChar; - if(declList) { - declList.append(varDecl); - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - var prevInFncDecl = this.inFncDecl; - this.inFncDecl = false; - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - this.inFncDecl = prevInFncDecl; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { - this.reportParseError("Ambient variable can not have an initializer"); - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.actualText; - } - } else { - if(isConst) { - this.reportParseError("const declaration requires initializer"); - } - varDecl.limChar = this.scanner.pos; - } - varDecl.postComments = this.parseCommentsForLine(this.scanner.line); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - if(declList) { - declList.limChar = varDecl.limChar; - return declList; - } else { - return varDecl; - } - } - if(!multivar) { - declList = new TypeScript.ASTList(); - declList.minChar = varDecl.minChar; - declList.append(varDecl); - multivar = true; - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.startPos; - } - }; - Parser.prototype.parseMemberList = function (errorRecoverySet) { - var elements = new TypeScript.ASTList(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - return elements; - } - var idHint = null; - var memberName = null; - var memberExpr = null; - var member = null; - var minChar = this.scanner.startPos; - var isSet = false; - var skippedTokenForGetSetId = false; - var getSetTok = null; - var getSetStartPos = 0; - var getSetPos = 0; - for(; ; ) { - var accessorPattern = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { - isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; - getSetTok = this.currentToken; - getSetStartPos = this.scanner.startPos; - getSetPos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = isSet ? "set" : "get"; - idHint = idHint + this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - accessorPattern = true; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { - this.reportParseError("Expected identifier, string or number as accessor name"); - } else { - skippedTokenForGetSetId = true; - memberName = TypeScript.Identifier.fromToken(getSetTok); - memberName.minChar = getSetStartPos; - memberName.limChar = getSetPos; - } - } - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - idHint = this.currentToken.getText(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { - var ntok = this.currentToken; - idHint = ntok.value.toString(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - this.reportParseError("Expected identifier, string or number as member name"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); - memberName.limChar = this.scanner.lastTokenLimChar(); - } - } - } - } - } - if(!skippedTokenForGetSetId) { - this.currentToken = this.scanner.scan(); - } else { - skippedTokenForGetSetId = false; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - memberName.flags |= TypeScript.ASTFlags.OptionalName; - this.currentToken = this.scanner.scan(); - } - if(accessorPattern) { - var args = new TypeScript.ASTList(); - this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); - if(isSet && funcDecl.returnTypeAnnotation) { - this.reportParseError("Property setters may not declare a return type"); - } - funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - funcDecl.hint = idHint; - memberExpr = funcDecl; - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { - this.reportParseError("Expected 'new' on array declaration in member definition"); - } - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else { - this.reportParseError("Expected ':' in member definition"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - elements.flags |= TypeScript.ASTFlags.Error; - elements.minChar = minChar; - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - } - } - } - idHint = null; - elements.append(member); - member.limChar = this.scanner.lastTokenLimChar(); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } - } - if(member) { - elements.limChar = member.limChar; - } - elements.minChar = minChar; - return elements; - }; - Parser.prototype.parseArrayList = function (errorRecoverySet) { - var elements = null; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - return elements; - } else { - elements = new TypeScript.ASTList(); - elements.minChar = this.scanner.startPos; - } - var arg; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { - arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - } else { - arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - } - elements.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - }; - Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { - var arrayLiteral = null; - arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); - return arrayLiteral; - }; - Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { - var ast = null; - var sawId = false; - var inNew = false; - var minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var parseAsLambda = false; - var expectlambdaRParen = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Any: - case TypeScript.TokenID.String: { - var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); - if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { - ast = new TypeScript.TypeReference(tid, 0); - sawId = true; - } else { - ast = tid; - sawId = true; - } - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.This: { - ast = new TypeScript.AST(TypeScript.NodeType.This); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.Super: { - ast = new TypeScript.AST(TypeScript.NodeType.Super); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.True: { - ast = new TypeScript.AST(TypeScript.NodeType.True); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - - } - case TypeScript.TokenID.False: { - ast = new TypeScript.AST(TypeScript.NodeType.False); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - - } - case TypeScript.TokenID.Null: { - ast = new TypeScript.AST(TypeScript.NodeType.Null); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - - } - case TypeScript.TokenID.New: { - minChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); - if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { - this.reportParseError("Cannot invoke 'new' on this expression"); - } else { - ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - inNew = true; - } - break; - - } - case TypeScript.TokenID.Function: { - minChar = this.scanner.pos; - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - break; - - } - } - if(ast == null) { - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var idText = this.currentToken.getText(); - ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); - sawId = true; - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; - } - limChar = this.scanner.lastTokenLimChar(); - } - } - if(inCast) { - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - } - if(ast == null) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: { - minChar = this.scanner.pos; - var prevTokId = this.scanner.previousToken().tokenId; - this.currentToken = this.scanner.scan(); - var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; - if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - parseAsLambda = true; - expectlambdaRParen = false; - this.currentToken = this.scanner.scan(); - } else { - if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - parseAsLambda = true; - expectlambdaRParen = true; - } else { - ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); - limChar = this.scanner.lastTokenLimChar(); - parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); - expectlambdaRParen = true; - } - } - if((ast && !parseAsLambda)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); - break; - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast.isParenthesized = true; - } - break; - - } - case TypeScript.TokenID.NumberLiteral: { - var numTok = this.currentToken; - this.currentToken = this.scanner.scan(); - ast = new TypeScript.NumberLiteral(numTok.value, numTok.hasEmptyFraction); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - - case TypeScript.TokenID.StringLiteral: { - ast = new TypeScript.StringLiteral(this.currentToken.getText()); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - - } - case TypeScript.TokenID.RegularExpressionLiteral: { - var rtok = this.currentToken; - ast = new TypeScript.RegexLiteral(rtok.regex); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - - case TypeScript.TokenID.OpenBracket: { - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); - ast.minChar = minChar; - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - - } - case TypeScript.TokenID.OpenBrace: { - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - members.minChar = minChar; - members.limChar = limChar; - break; - - } - case TypeScript.TokenID.LessThan: { - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); - (ast).castTerm = term; - break; - - } - default: { - if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - parseAsLambda = true; - ast = this.prevExpr; - } else { - this.reportParseError("Check format of expression term"); - if(this.errorRecovery) { - var ident = new TypeScript.MissingIdentifier(); - ident.minChar = minChar; - ident.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - } else { - limChar = this.scanner.lastTokenLimChar(); - } - ast = ident; - } - } - - } - } - } - if(parseAsLambda) { - if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - } else { - if(ast) { - ast.isParenthesized = true; - } - } - } - if(sawId && (typeContext != TypeContext.NoTypes)) { - typeContext |= TypeContext.ArraySuffix; - } - var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); - if(postFix) { - if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { - var binExpr = postFix; - if(binExpr.operand2 == null) { - postFix = this.convertToTypeReference(postFix); - } - } - postFix.minChar = minChar; - postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); - return postFix; - } else { - return new TypeScript.AST(TypeScript.NodeType.Error); - } - }; - Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { - var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: lambdaArgs - }, expectClosingRParen); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - if(!skipNextRParen) { - ast.flags |= TypeScript.ASTFlags.SkipNextRParen; - } - ast.limChar = this.scanner.lastTokenLimChar(); - ; ; - return ast; - }; - Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { - if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } - var ast = null; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - var canAssign = true; - var idHint = null; - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - var exprIsAnonLambda = false; - if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { - canAssign = false; - this.currentToken = this.scanner.scan(); - var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); - if((tokenInfo.unopNodeType == TypeScript.NodeType.Pos) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { - ast = tempExpr; - } else { - if((tokenInfo.unopNodeType == TypeScript.NodeType.Neg) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { - var numLit = tempExpr; - numLit.value = (-numLit.value); - if(numLit.value == 0) { - numLit.isNegativeZero = true; - } - ast = tempExpr; - } else { - ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); - ast.limChar = tempExpr.limChar; - } - } - ast.minChar = minChar; - } else { - ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); - var id; - var temp; - if(ast.nodeType == TypeScript.NodeType.Name) { - id = ast; - idHint = id.actualText; - } else { - if(ast.nodeType == TypeScript.NodeType.Dot) { - var subsumedExpr = false; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { - if((ast).operand2.nodeType == TypeScript.NodeType.Name) { - var op2ID = ((ast).operand2); - if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { - ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); - subsumedExpr = true; - } - } - } - if(!subsumedExpr) { - temp = ast; - while(temp.nodeType == TypeScript.NodeType.Dot) { - var binExpr = temp; - temp = binExpr.operand2; - } - if(temp.nodeType == TypeScript.NodeType.Name) { - id = temp; - idHint = id.actualText; - } - } - } - } - if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { - canAssign = false; - var operand = ast; - ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); - ast.limChar = this.scanner.pos; - ast.minChar = operand.minChar; - this.currentToken = this.scanner.scan(); - } - } - for(; ; ) { - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { - break; - } - if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { - break; - } - if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { - if(tokenInfo.binopPrecedence < minPrecedence) { - break; - } - if(!canAssign) { - this.reportParseError("illegal assignment"); - } - } else { - if(tokenInfo.binopPrecedence <= minPrecedence) { - break; - } - } - if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { - exprIsAnonLambda = true; - canAssign = false; - ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); - break; - } - this.currentToken = this.scanner.scan(); - canAssign = false; - if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { - if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { - exprIsAnonLambda = true; - canAssign = true; - } else { - this.prevExpr = ast; - var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - this.prevExpr = null; - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); - } - } else { - var tc = TypeContext.NoTypes; - var binExpr2; - binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); - if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = binExpr2.operand2; - funcDecl.hint = idHint; - } - binExpr2.minChar = ast.minChar; - binExpr2.limChar = this.scanner.lastTokenLimChar(); - idHint = null; - ast = binExpr2; - } - } - if(canAssign) { - ast.flags |= TypeScript.ASTFlags.Writeable; - } - if(!exprIsAnonLambda) { - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - ast.preComments = preComments; - ast.postComments = this.parseCommentsForLine(this.scanner.line); - } - return ast; - }; - Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { - var count = 0; - if(!ast) { - ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - ast.isParenthesized = true; - } - ast.minChar = lhsMinChar; - ast.limChar = lhsLimChar; - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: { - if(inNew) { - var callExpr = ast; - callExpr.arguments = this.parseArgList(errorRecoverySet); - inNew = false; - } else { - if(!allowCall) { - return ast; - } - ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); - ast.minChar = lhsMinChar; - } - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - break; - - } - case TypeScript.TokenID.OpenBracket: { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { - this.currentToken = this.scanner.scan(); - if(ast.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = ast; - typeRef.arrayCount++; - } else { - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); - } - ast.limChar = this.scanner.pos; - break; - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - - } - case TypeScript.TokenID.Dot: { - var name = null; - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { - ast.flags |= TypeScript.ASTFlags.DotLHS; - name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Expected identifier following dot"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); - return ast; - } else { - name = new TypeScript.MissingIdentifier(); - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - } - - case TypeScript.TokenID.EqualsGreaterThan: { - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: ast - }, false); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - - } - default: { - return ast; - - } - } - } - }; - Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{'"); - if(this.errorRecovery) { - var etryNode = tryNode; - etryNode.minChar = minChar; - etryNode.limChar = this.scanner.lastTokenLimChar(); - etryNode.flags |= TypeScript.ASTFlags.Error; - return etryNode; - } - } - tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - tryNode.minChar = minChar; - tryNode.limChar = tryNode.body.limChar; - tryNode.preComments = preComments; - tryNode.postComments = this.parseComments(); - return tryNode; - }; - Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { - var catchMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("Expected identifier in catch header"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = this.scanner.pos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); - param.id.minChar = this.scanner.startPos; - param.id.limChar = this.scanner.pos; - param.minChar = param.id.minChar; - param.limChar = param.id.limChar; - this.currentToken = this.scanner.scan(); - var statementPos = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start catch body"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = statementPos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var catchNode = new TypeScript.Catch(param, catchStmt); - catchNode.statement.minChar = catchMinChar; - catchNode.statement.limChar = statementPos; - catchNode.minChar = catchMinChar; - catchNode.limChar = catchStmt.limChar; - catchNode.preComments = preComments; - catchNode.postComments = this.parseComments(); - return catchNode; - }; - Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { - var finMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start body of finally statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); - efin.flags |= TypeScript.ASTFlags.Error; - efin.minChar = this.scanner.startPos; - efin.limChar = this.scanner.pos; - return efin; - } - } - var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var fin = new TypeScript.Finally(finBody); - fin.minChar = finMinChar; - fin.limChar = fin.body.limChar; - fin.preComments = preComments; - fin.postComments = this.parseComments(); - return fin; - }; - Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { - var tryPart = new TypeScript.Try(null); - var tryMinChar = this.scanner.startPos; - this.pushStmt(tryPart, labelList); - this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - this.popStmt(); - var tc = null; - var tf = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { - var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - tc = new TypeScript.TryCatch(tryPart, catchPart); - tc.minChar = tryPart.minChar; - tc.limChar = catchPart.limChar; - } - if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { - if(tc == null) { - this.reportParseError("try with neither catch nor finally"); - if(this.errorRecovery) { - var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - etf.flags |= TypeScript.ASTFlags.Error; - etf.minChar = this.scanner.startPos; - etf.limChar = this.scanner.pos; - return etf; - } - return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - } else { - return tc; - } - } else { - if(tc) { - tryPart = tc; - } - var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); - tf = new TypeScript.TryFinally(tryPart, finallyPart); - tf.minChar = tryMinChar; - tf.limChar = finallyPart.limChar; - return tf; - } - }; - Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { - var ast = null; - var labelList = null; - var astList = null; - var temp; - var modifiers = TypeScript.Modifiers.None; - var minChar = this.scanner.startPos; - var forInOk = false; - var needTerminator = false; - var fnOrVar = null; - var preComments = this.parseComments(); - this.state = ParseState.StartStatement; - function isAmbient() { - return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); - } - function mayNotBeExported() { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportError("Statement may not be exported"); - } - } - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.EndOfFile: { - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.pos; - break; - - } - case TypeScript.TokenID.Function: { - if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { - this.currentToken = this.scanner.scan(); - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false); - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - this.reportParseError("function keyword can only introduce function declaration"); - } else { - if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - } - ast = fnOrVar; - if(this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } else { - ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, isAmbient(), modifiers, null, true); - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - if(this.ambientModule) { - this.reportParseError("function declaration not permitted within ambient module"); - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } - break; - - } - case TypeScript.TokenID.Module: { - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); - preComments = null; - } - break; - - } - case TypeScript.TokenID.Import: { - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportParseError("export keyword not permitted on import declaration"); - } - ast = this.parseImportDeclaration(errorRecoverySet, modifiers); - needTerminator = true; - } - break; - - } - case TypeScript.TokenID.Export: { - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("'export' statements are only allowed at the global and module levels"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } - modifiers |= TypeScript.Modifiers.Exported; - this.currentToken = this.scanner.scan(); - break; - - } - case TypeScript.TokenID.Private: { - modifiers |= TypeScript.Modifiers.Private; - this.currentToken = this.scanner.scan(); - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - minChar = this.scanner.pos; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - - } - case TypeScript.TokenID.Public: { - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.pos; - modifiers |= TypeScript.Modifiers.Public; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { - this.reportParseError("'property' statements are only allowed within classes"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - - } - case TypeScript.TokenID.Declare: { - if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { - this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); - } - if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); - } - modifiers |= TypeScript.Modifiers.Ambient; - this.currentToken = this.scanner.scan(); - break; - - } - case TypeScript.TokenID.Class: { - if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("class not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); - } - break; - - } - case TypeScript.TokenID.Interface: { - if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("interface not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); - } - break; - - } - case TypeScript.TokenID.Var: { - var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); - if(declAst.nodeType == TypeScript.NodeType.VarDecl) { - ast = declAst; - } else { - ast = new TypeScript.Block(declAst, false); - } - needTerminator = true; - break; - - } - case TypeScript.TokenID.Static: { - if(this.currentClassDecl == null) { - this.reportParseError("Statics may only be class members"); - } - mayNotBeExported(); - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else { - if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - } - } - } - if(isAmbient()) { - modifiers |= TypeScript.Modifiers.Ambient; - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); - var staticsList = this.topStaticsList(); - if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - staticsList.append(fnOrVar); - } - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - break; - - } - case TypeScript.TokenID.For: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("syntax error: for statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - this.state = ParseState.ForInit; - forInOk = true; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Var: { - temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); - break; - - } - case TypeScript.TokenID.Semicolon: { - temp = null; - this.state = ParseState.ForCondStart; - break; - - } - default: { - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); - break; - - } - } - this.state = ParseState.ForInitAfterVar; - if(this.currentToken.tokenId == TypeScript.TokenID.In) { - if((temp == null) || (!forInOk)) { - this.reportParseError("malformed for statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - ast.flags |= TypeScript.ASTFlags.Error; - } - } else { - this.currentToken = this.scanner.scan(); - var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); - forInStmt.limChar = this.scanner.pos; - forInStmt.statement.minChar = minChar; - forInStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); - this.pushStmt(forInStmt, labelList); - forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forInStmt.minChar = minChar; - ast = forInStmt; - } - } else { - var forStmt = new TypeScript.ForStatement(temp); - forStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - forStmt.cond = null; - } else { - forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = forStmt; - ast.flags |= TypeScript.ASTFlags.Error; - } - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - forStmt.incr = null; - } else { - forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - this.pushStmt(forStmt, labelList); - forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forStmt.limChar = forStmt.body.limChar; - ast = forStmt; - } - break; - - } - case TypeScript.TokenID.With: { - { - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); - } - if(this.strictMode) { - this.reportParseError("'with' statements are not available in strict mode"); - } - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'with' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var withStmt = new TypeScript.WithStatement(expr); - withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - withStmt.minChar = minChar; - withStmt.limChar = withStmt.body.limChar; - ast = withStmt; - } - break; - - } - case TypeScript.TokenID.Switch: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'switch' statement does not take modifiers"); - } - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - switchStmt.statement.minChar = minChar; - switchStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var caseListMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); - switchStmt.defaultCase = null; - switchStmt.caseList = new TypeScript.ASTList(); - var caseStmt = null; - this.pushStmt(switchStmt, labelList); - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { - var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); - caseStmt = new TypeScript.CaseStatement(); - caseStmt.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(isDefault) { - switchStmt.defaultCase = caseStmt; - } else { - caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - caseStmt.body = new TypeScript.ASTList(); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); - caseStmt.limChar = caseStmt.body.limChar; - switchStmt.caseList.append(caseStmt); - } else { - break; - } - } - switchStmt.caseList.minChar = caseListMinChar; - switchStmt.caseList.limChar = this.scanner.pos; - switchStmt.limChar = switchStmt.caseList.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - this.popStmt(); - ast = switchStmt; - break; - } - - case TypeScript.TokenID.While: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'while' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); - var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - whileStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(whileStmt, labelList); - whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - whileStmt.limChar = whileStmt.body.limChar; - this.popStmt(); - ast = whileStmt; - break; - } - - case TypeScript.TokenID.Do: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'do' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var doStmt = new TypeScript.DoWhileStatement(); - doStmt.minChar = minChar; - this.pushStmt(doStmt, labelList); - doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); - this.popStmt(); - doStmt.whileAST = new TypeScript.Identifier("while"); - doStmt.whileAST.minChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); - doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - doStmt.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast = doStmt; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - break; - } - - case TypeScript.TokenID.If: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("if statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ifStmt.minChar = minChar; - ifStmt.statement.minChar = minChar; - ifStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(ifStmt, labelList); - ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.thenBod.limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Else) { - this.currentToken = this.scanner.scan(); - ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.elseBod.limChar; - } - this.popStmt(); - ast = ifStmt; - break; - } - - case TypeScript.TokenID.Try: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("try statement does not take modifiers"); - } - minChar = this.scanner.startPos; - ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); - break; - } - - case TypeScript.TokenID.OpenBrace: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("block does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var block = new TypeScript.Block(new TypeScript.ASTList(), true); - this.pushStmt(block, labelList); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); - this.popStmt(); - block.statements.minChar = minChar; - block.statements.limChar = this.scanner.pos; - block.minChar = block.statements.minChar; - block.limChar = block.statements.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = block; - break; - } - - case TypeScript.TokenID.Semicolon: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifier can not appear here"); - } - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - this.currentToken = this.scanner.scan(); - break; - - } - case TypeScript.TokenID.Break: - case TypeScript.TokenID.Continue: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before jump statement"); - } - var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { - jump.target = this.currentToken.getText(); - this.currentToken = this.scanner.scan(); - } - this.resolveJumpTarget(jump); - ast = jump; - needTerminator = true; - break; - } - - case TypeScript.TokenID.Return: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before return statement"); - } - if(!this.inFunction) { - this.reportParseError("return statement outside of function body"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.minChar = minChar; - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - needTerminator = true; - retStmt.limChar = this.scanner.lastTokenLimChar(); - ast = retStmt; - break; - } - - case TypeScript.TokenID.Throw: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before a throw statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } else { - this.reportParseError("throw with no target"); - temp = null; - } - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); - ast.limChar = this.scanner.lastTokenLimChar(); - needTerminator = true; - break; - - } - case TypeScript.TokenID.Enum: { - this.currentToken = this.scanner.scan(); - ast = this.parseEnumDecl(errorRecoverySet, modifiers); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - (ast).modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).modFlags |= TypeScript.ModuleFlags.Exported; - } - break; - - } - case TypeScript.TokenID.Debugger: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before debugger statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var debuggerStmt = new TypeScript.DebuggerStatement(); - debuggerStmt.minChar = minChar; - needTerminator = true; - debuggerStmt.limChar = this.scanner.lastTokenLimChar(); - ast = debuggerStmt; - break; - - } - default: { - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before an expression statement or label"); - } - minChar = this.scanner.startPos; - var svPos = this.scanner.pos; - temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.scanner.pos == svPos) { - this.currentToken = this.scanner.scan(); - ast = temp; - } else { - if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { - if(labelList == null) { - labelList = new TypeScript.ASTList(); - } - labelList.append(new TypeScript.Label(temp)); - this.currentToken = this.scanner.scan(); - } else { - ast = temp; - needTerminator = true; - } - } - - } - } - if(ast) { - break; - } - } - if(needTerminator) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Semicolon: { - this.currentToken = this.scanner.scan(); - ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; - break; - - } - case TypeScript.TokenID.EndOfFile: { - ast.limChar = this.scanner.pos; - - } - case TypeScript.TokenID.CloseBrace: { - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - break; - - } - default: { - if(!this.scanner.lastTokenHadNewline()) { - this.reportParseError("Expected ';'"); - } else { - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - } - break; - - } - } - } - if(labelList) { - ast = new TypeScript.LabeledStatement(labelList, ast); - } - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - if(preComments) { - ast.preComments = preComments; - } - if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { - this.reportParseError("statement not permitted within ambient module"); - } - ast.flags |= TypeScript.ASTFlags.IsStatement; - return ast; - }; - Parser.prototype.okAmbientModuleMember = function (ast) { - var nt = ast.nodeType; - return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).isMethod())); - }; - Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { - var directivePrologue = sourceElms; - statements.minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; - var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; - this.state = ParseState.StartStatementList; - var oldStrictMode = this.strictMode; - this.nestingLevel++; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - this.state = ParseState.EndStmtList; - statements.limChar = limChar; - if(statements.members.length == 0) { - statements.preComments = this.parseComments(); - } else { - statements.postComments = this.parseComments(); - } - this.strictMode = oldStrictMode; - this.nestingLevel--; - return; - } - var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); - if(stmt) { - stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - statements.append(stmt); - limChar = stmt.limChar; - if(directivePrologue) { - if(stmt.nodeType == TypeScript.NodeType.QString) { - var qstring = stmt; - if(qstring.text == "\"use strict\"") { - statements.flags |= TypeScript.ASTFlags.StrictMode; - this.strictMode = true; - } else { - directivePrologue = false; - } - } else { - directivePrologue = false; - } - } - } - } - }; - Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { - var svGenTarget = TypeScript.moduleGenTarget; - try { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; - var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); - return new QuickParseResult(script, this.scanner.lexState); - }finally { - TypeScript.moduleGenTarget = svGenTarget; - } - }; - Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { - if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } - var _this = this; - this.ambientModule = false; - this.topLevel = true; - this.hasTopLevelImportOrExport = false; - this.requiresExtendsBlock = false; - this.fname = filename; - this.currentUnitIndex = unitIndex; - this.amdDependencies = []; - this.scanner.resetComments(); - this.scanner.setErrorHandler(function (message) { - return _this.reportParseError(message); - }); - this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var minChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.pushDeclLists(); - var bod = new TypeScript.ASTList(); - bod.minChar = minChar; - this.state = ParseState.StartScript; - this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); - while(true) { - this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); - if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { - break; - } - var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; - this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); - this.currentToken = this.scanner.scan(); - } - this.state = ParseState.EndScript; - bod.limChar = this.scanner.pos; - var topLevelMod = null; - if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { - var correctedFileName = TypeScript.switchToForwardSlashes(filename); - var id = new TypeScript.Identifier(correctedFileName); - topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), this.topScopeList(), null); - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; - topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; - if(this.parsingDeclareFile) { - topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; - } - topLevelMod.minChar = minChar; - topLevelMod.limChar = this.scanner.pos; - topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); - topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; - topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - topLevelMod.amdDependencies = this.amdDependencies; - bod = new TypeScript.ASTList(); - bod.minChar = topLevelMod.minChar; - bod.limChar = topLevelMod.limChar; - bod.append(topLevelMod); - } - var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); - script.bod = bod; - this.popDeclLists(); - script.minChar = minChar; - script.limChar = this.scanner.pos; - script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); - script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - script.isDeclareFile = this.parsingDeclareFile; - script.topLevelMod = topLevelMod; - script.containsUnicodeChar = this.scanner.seenUnicodeChar; - script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - script.requiresExtendsBlock = this.requiresExtendsBlock; - return script; - }; - return Parser; - })(); - TypeScript.Parser = Parser; - function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { - var fragment = sourceText.getText(minChar, limChar); - logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); - var quickParser = new Parser(); - quickParser.setErrorRecovery(null); - quickParser.errorCallback = errorCapture; - var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); - quickParser.currentClassDecl = quickClassDecl; - var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); - return result; - } - TypeScript.quickParse = quickParse; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var PrintContext = (function () { - function PrintContext(outfile, parser) { - this.outfile = outfile; - this.parser = parser; - this.builder = ""; - this.indent1 = " "; - this.indentStrings = []; - this.indentAmt = 0; - } - PrintContext.prototype.increaseIndent = function () { - this.indentAmt++; - }; - PrintContext.prototype.decreaseIndent = function () { - this.indentAmt--; - }; - PrintContext.prototype.startLine = function () { - if(this.builder.length > 0) { - TypeScript.CompilerDiagnostics.Alert(this.builder); - } - var indentString = this.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i++) { - indentString += this.indent1; - } - this.indentStrings[this.indentAmt] = indentString; - } - this.builder += indentString; - }; - PrintContext.prototype.write = function (s) { - this.builder += s; - }; - PrintContext.prototype.writeLine = function (s) { - this.builder += s; - this.outfile.WriteLine(this.builder); - this.builder = ""; - }; - return PrintContext; - })(); - TypeScript.PrintContext = PrintContext; - function prePrintAST(ast, parent, walker) { - var pc = walker.state; - ast.print(pc); - pc.increaseIndent(); - return ast; - } - TypeScript.prePrintAST = prePrintAST; - function postPrintAST(ast, parent, walker) { - var pc = walker.state; - pc.decreaseIndent(); - return ast; - } - TypeScript.postPrintAST = postPrintAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - TypeScript.LexEOF = (-1); - TypeScript.LexCodeNWL = 10; - TypeScript.LexCodeRET = 13; - TypeScript.LexCodeLS = 8232; - TypeScript.LexCodePS = 8233; - TypeScript.LexCodeTAB = 9; - TypeScript.LexCodeVTAB = 11; - TypeScript.LexCode_e = 'e'.charCodeAt(0); - TypeScript.LexCode_E = 'E'.charCodeAt(0); - TypeScript.LexCode_x = 'x'.charCodeAt(0); - TypeScript.LexCode_X = 'X'.charCodeAt(0); - TypeScript.LexCode_a = 'a'.charCodeAt(0); - TypeScript.LexCode_A = 'A'.charCodeAt(0); - TypeScript.LexCode_f = 'f'.charCodeAt(0); - TypeScript.LexCode_F = 'F'.charCodeAt(0); - TypeScript.LexCode_g = 'g'.charCodeAt(0); - TypeScript.LexCode_m = 'm'.charCodeAt(0); - TypeScript.LexCode_i = 'i'.charCodeAt(0); - TypeScript.LexCode_u = 'u'.charCodeAt(0); - TypeScript.LexCode_0 = '0'.charCodeAt(0); - TypeScript.LexCode_9 = '9'.charCodeAt(0); - TypeScript.LexCode_8 = '8'.charCodeAt(0); - TypeScript.LexCode_7 = '7'.charCodeAt(0); - TypeScript.LexCodeBSL = '\\'.charCodeAt(0); - TypeScript.LexCodeSHP = '#'.charCodeAt(0); - TypeScript.LexCodeBNG = '!'.charCodeAt(0); - TypeScript.LexCodeQUO = '"'.charCodeAt(0); - TypeScript.LexCodeAPO = '\''.charCodeAt(0); - TypeScript.LexCodePCT = '%'.charCodeAt(0); - TypeScript.LexCodeAMP = '&'.charCodeAt(0); - TypeScript.LexCodeLPR = '('.charCodeAt(0); - TypeScript.LexCodeRPR = ')'.charCodeAt(0); - TypeScript.LexCodePLS = '+'.charCodeAt(0); - TypeScript.LexCodeMIN = '-'.charCodeAt(0); - TypeScript.LexCodeMUL = '*'.charCodeAt(0); - TypeScript.LexCodeSLH = '/'.charCodeAt(0); - TypeScript.LexCodeXOR = '^'.charCodeAt(0); - TypeScript.LexCodeCMA = ','.charCodeAt(0); - TypeScript.LexCodeDOT = '.'.charCodeAt(0); - TypeScript.LexCodeLT = '<'.charCodeAt(0); - TypeScript.LexCodeEQ = '='.charCodeAt(0); - TypeScript.LexCodeGT = '>'.charCodeAt(0); - TypeScript.LexCodeQUE = '?'.charCodeAt(0); - TypeScript.LexCodeLBR = '['.charCodeAt(0); - TypeScript.LexCodeRBR = ']'.charCodeAt(0); - TypeScript.LexCodeUSC = '_'.charCodeAt(0); - TypeScript.LexCodeLC = '{'.charCodeAt(0); - TypeScript.LexCodeRC = '}'.charCodeAt(0); - TypeScript.LexCodeBAR = '|'.charCodeAt(0); - TypeScript.LexCodeTIL = '~'.charCodeAt(0); - TypeScript.LexCodeCOL = ':'.charCodeAt(0); - TypeScript.LexCodeSMC = ';'.charCodeAt(0); - TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); - TypeScript.LexCodeDollar = '$'.charCodeAt(0); - TypeScript.LexCodeSpace = 32; - TypeScript.LexCodeAtSign = '@'.charCodeAt(0); - TypeScript.LexCodeASCIIChars = 128; - TypeScript.LexKeywordTable = undefined; - var autoToken = new Array(TypeScript.LexCodeASCIIChars); - var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); - var unicodeES3IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 543, - 546, - 563, - 592, - 685, - 688, - 696, - 699, - 705, - 720, - 721, - 736, - 740, - 750, - 750, - 890, - 890, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 974, - 976, - 983, - 986, - 1011, - 1024, - 1153, - 1164, - 1220, - 1223, - 1224, - 1227, - 1228, - 1232, - 1269, - 1272, - 1273, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1569, - 1594, - 1600, - 1610, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1786, - 1788, - 1808, - 1808, - 1810, - 1836, - 1920, - 1957, - 2309, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2699, - 2701, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2784, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2870, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 2997, - 2999, - 3001, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3294, - 3294, - 3296, - 3297, - 3333, - 3340, - 3342, - 3344, - 3346, - 3368, - 3370, - 3385, - 3424, - 3425, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3805, - 3840, - 3840, - 3904, - 3911, - 3913, - 3946, - 3976, - 3979, - 4096, - 4129, - 4131, - 4135, - 4137, - 4138, - 4176, - 4181, - 4256, - 4293, - 4304, - 4342, - 4352, - 4441, - 4447, - 4514, - 4520, - 4601, - 4608, - 4614, - 4616, - 4678, - 4680, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4742, - 4744, - 4744, - 4746, - 4749, - 4752, - 4782, - 4784, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4814, - 4816, - 4822, - 4824, - 4846, - 4848, - 4878, - 4880, - 4880, - 4882, - 4885, - 4888, - 4894, - 4896, - 4934, - 4936, - 4954, - 5024, - 5108, - 5121, - 5740, - 5743, - 5750, - 5761, - 5786, - 5792, - 5866, - 6016, - 6067, - 6176, - 6263, - 6272, - 6312, - 7680, - 7835, - 7840, - 7929, - 7936, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8319, - 8319, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8497, - 8499, - 8505, - 8544, - 8579, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12346, - 12353, - 12436, - 12445, - 12446, - 12449, - 12538, - 12540, - 12542, - 12549, - 12588, - 12593, - 12686, - 12704, - 12727, - 13312, - 13312, - 19893, - 19893, - 19968, - 19968, - 40869, - 40869, - 40960, - 42124, - 44032, - 44032, - 55203, - 55203, - 63744, - 64045, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65138, - 65140, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500 - ]; - var unicodeES3IdCont = [ - 768, - 846, - 864, - 866, - 1155, - 1158, - 1425, - 1441, - 1443, - 1465, - 1467, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1476, - 1611, - 1621, - 1632, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 2305, - 2307, - 2364, - 2364, - 2366, - 2381, - 2385, - 2388, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2562, - 2562, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2662, - 2673, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2883, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2918, - 2927, - 2946, - 2947, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3047, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3174, - 3183, - 3202, - 3203, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3302, - 3311, - 3330, - 3331, - 3390, - 3395, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3984, - 3991, - 3993, - 4028, - 4038, - 4038, - 4140, - 4146, - 4150, - 4153, - 4160, - 4169, - 4182, - 4185, - 4969, - 4977, - 6068, - 6099, - 6112, - 6121, - 6160, - 6169, - 6313, - 6313, - 8255, - 8256, - 8400, - 8412, - 8417, - 8417, - 12330, - 12335, - 12441, - 12442, - 12539, - 12539, - 64286, - 64286, - 65056, - 65059, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343, - 65381, - 65381 - ]; - var unicodeES5IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 705, - 710, - 721, - 736, - 740, - 748, - 748, - 750, - 750, - 880, - 884, - 886, - 887, - 890, - 893, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 1013, - 1015, - 1153, - 1162, - 1319, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1568, - 1610, - 1646, - 1647, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1774, - 1775, - 1786, - 1788, - 1791, - 1791, - 1808, - 1808, - 1810, - 1839, - 1869, - 1957, - 1969, - 1969, - 1994, - 2026, - 2036, - 2037, - 2042, - 2042, - 2048, - 2069, - 2074, - 2074, - 2084, - 2084, - 2088, - 2088, - 2112, - 2136, - 2208, - 2208, - 2210, - 2220, - 2308, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2417, - 2423, - 2425, - 2431, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2493, - 2493, - 2510, - 2510, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2785, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2869, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2929, - 2929, - 2947, - 2947, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 3001, - 3024, - 3024, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3133, - 3133, - 3160, - 3161, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3261, - 3261, - 3294, - 3294, - 3296, - 3297, - 3313, - 3314, - 3333, - 3340, - 3342, - 3344, - 3346, - 3386, - 3389, - 3389, - 3406, - 3406, - 3424, - 3425, - 3450, - 3455, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3807, - 3840, - 3840, - 3904, - 3911, - 3913, - 3948, - 3976, - 3980, - 4096, - 4138, - 4159, - 4159, - 4176, - 4181, - 4186, - 4189, - 4193, - 4193, - 4197, - 4198, - 4206, - 4208, - 4213, - 4225, - 4238, - 4238, - 4256, - 4293, - 4295, - 4295, - 4301, - 4301, - 4304, - 4346, - 4348, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4744, - 4746, - 4749, - 4752, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4822, - 4824, - 4880, - 4882, - 4885, - 4888, - 4954, - 4992, - 5007, - 5024, - 5108, - 5121, - 5740, - 5743, - 5759, - 5761, - 5786, - 5792, - 5866, - 5870, - 5872, - 5888, - 5900, - 5902, - 5905, - 5920, - 5937, - 5952, - 5969, - 5984, - 5996, - 5998, - 6000, - 6016, - 6067, - 6103, - 6103, - 6108, - 6108, - 6176, - 6263, - 6272, - 6312, - 6314, - 6314, - 6320, - 6389, - 6400, - 6428, - 6480, - 6509, - 6512, - 6516, - 6528, - 6571, - 6593, - 6599, - 6656, - 6678, - 6688, - 6740, - 6823, - 6823, - 6917, - 6963, - 6981, - 6987, - 7043, - 7072, - 7086, - 7087, - 7098, - 7141, - 7168, - 7203, - 7245, - 7247, - 7258, - 7293, - 7401, - 7404, - 7406, - 7409, - 7413, - 7414, - 7424, - 7615, - 7680, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8305, - 8305, - 8319, - 8319, - 8336, - 8348, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8505, - 8508, - 8511, - 8517, - 8521, - 8526, - 8526, - 8544, - 8584, - 11264, - 11310, - 11312, - 11358, - 11360, - 11492, - 11499, - 11502, - 11506, - 11507, - 11520, - 11557, - 11559, - 11559, - 11565, - 11565, - 11568, - 11623, - 11631, - 11631, - 11648, - 11670, - 11680, - 11686, - 11688, - 11694, - 11696, - 11702, - 11704, - 11710, - 11712, - 11718, - 11720, - 11726, - 11728, - 11734, - 11736, - 11742, - 11823, - 11823, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12348, - 12353, - 12438, - 12445, - 12447, - 12449, - 12538, - 12540, - 12543, - 12549, - 12589, - 12593, - 12686, - 12704, - 12730, - 12784, - 12799, - 13312, - 13312, - 19893, - 19893, - 19968, - 19968, - 40908, - 40908, - 40960, - 42124, - 42192, - 42237, - 42240, - 42508, - 42512, - 42527, - 42538, - 42539, - 42560, - 42606, - 42623, - 42647, - 42656, - 42735, - 42775, - 42783, - 42786, - 42888, - 42891, - 42894, - 42896, - 42899, - 42912, - 42922, - 43000, - 43009, - 43011, - 43013, - 43015, - 43018, - 43020, - 43042, - 43072, - 43123, - 43138, - 43187, - 43250, - 43255, - 43259, - 43259, - 43274, - 43301, - 43312, - 43334, - 43360, - 43388, - 43396, - 43442, - 43471, - 43471, - 43520, - 43560, - 43584, - 43586, - 43588, - 43595, - 43616, - 43638, - 43642, - 43642, - 43648, - 43695, - 43697, - 43697, - 43701, - 43702, - 43705, - 43709, - 43712, - 43712, - 43714, - 43714, - 43739, - 43741, - 43744, - 43754, - 43762, - 43764, - 43777, - 43782, - 43785, - 43790, - 43793, - 43798, - 43808, - 43814, - 43816, - 43822, - 43968, - 44002, - 44032, - 44032, - 55203, - 55203, - 55216, - 55238, - 55243, - 55291, - 63744, - 64109, - 64112, - 64217, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500 - ]; - var unicodeES5IdCont = [ - 768, - 879, - 1155, - 1159, - 1425, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1477, - 1479, - 1479, - 1552, - 1562, - 1611, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 1984, - 1993, - 2027, - 2035, - 2070, - 2073, - 2075, - 2083, - 2085, - 2087, - 2089, - 2093, - 2137, - 2139, - 2276, - 2302, - 2304, - 2307, - 2362, - 2364, - 2366, - 2383, - 2385, - 2391, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2561, - 2563, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2641, - 2641, - 2662, - 2673, - 2677, - 2677, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2786, - 2787, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2884, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2914, - 2915, - 2918, - 2927, - 2946, - 2946, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3046, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3170, - 3171, - 3174, - 3183, - 3202, - 3203, - 3260, - 3260, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3298, - 3299, - 3302, - 3311, - 3330, - 3331, - 3390, - 3396, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3426, - 3427, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3981, - 3991, - 3993, - 4028, - 4038, - 4038, - 4139, - 4158, - 4160, - 4169, - 4182, - 4185, - 4190, - 4192, - 4194, - 4196, - 4199, - 4205, - 4209, - 4212, - 4226, - 4237, - 4239, - 4253, - 4957, - 4959, - 5906, - 5908, - 5938, - 5940, - 5970, - 5971, - 6002, - 6003, - 6068, - 6099, - 6109, - 6109, - 6112, - 6121, - 6155, - 6157, - 6160, - 6169, - 6313, - 6313, - 6432, - 6443, - 6448, - 6459, - 6470, - 6479, - 6576, - 6592, - 6600, - 6601, - 6608, - 6617, - 6679, - 6683, - 6741, - 6750, - 6752, - 6780, - 6783, - 6793, - 6800, - 6809, - 6912, - 6916, - 6964, - 6980, - 6992, - 7001, - 7019, - 7027, - 7040, - 7042, - 7073, - 7085, - 7088, - 7097, - 7142, - 7155, - 7204, - 7223, - 7232, - 7241, - 7248, - 7257, - 7376, - 7378, - 7380, - 7400, - 7405, - 7405, - 7410, - 7412, - 7616, - 7654, - 7676, - 7679, - 8204, - 8205, - 8255, - 8256, - 8276, - 8276, - 8400, - 8412, - 8417, - 8417, - 8421, - 8432, - 11503, - 11505, - 11647, - 11647, - 11744, - 11775, - 12330, - 12335, - 12441, - 12442, - 42528, - 42537, - 42607, - 42607, - 42612, - 42621, - 42655, - 42655, - 42736, - 42737, - 43010, - 43010, - 43014, - 43014, - 43019, - 43019, - 43043, - 43047, - 43136, - 43137, - 43188, - 43204, - 43216, - 43225, - 43232, - 43249, - 43264, - 43273, - 43302, - 43309, - 43335, - 43347, - 43392, - 43395, - 43443, - 43456, - 43472, - 43481, - 43561, - 43574, - 43587, - 43587, - 43596, - 43597, - 43600, - 43609, - 43643, - 43643, - 43696, - 43696, - 43698, - 43700, - 43703, - 43704, - 43710, - 43711, - 43713, - 43713, - 43755, - 43759, - 43765, - 43766, - 44003, - 44010, - 44012, - 44013, - 44016, - 44025, - 64286, - 64286, - 65024, - 65039, - 65056, - 65062, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343 - ]; - function LexLookUpUnicodeMap(code, map) { - var lo = 0; - var hi = map.length; - var mid; - while(lo + 1 < hi) { - mid = lo + (hi - lo) / 2; - mid -= mid % 2; - if(map[mid] <= code && code <= map[mid + 1]) { - return true; - } - if(code < map[mid]) { - hi = mid; - } else { - lo = mid + 2; - } - } - return false; - } - TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; - function LexIsUnicodeDigit(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdCont); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdCont); - } - } - TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; - function LexIsUnicodeIdStart(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdStart); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdStart); - } - } - TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; - function LexInitialize() { - TypeScript.initializeStaticTokens(); - autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; - autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; - autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; - autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; - autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; - autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; - autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; - autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; - autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; - autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; - TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); - for(var i in (TypeScript.TokenID)._map) { - if((i) <= TypeScript.TokenID.LimKeyword) { - TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); - } - } - for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { - if(LexIsIdentifierStartChar(j)) { - lexIdStartTable[j] = true; - } else { - lexIdStartTable[j] = false; - } - } - } - TypeScript.LexInitialize = LexInitialize; - function LexAdjustIndent(code, indentAmt) { - if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { - return indentAmt + 1; - } else { - if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { - return indentAmt - 1; - } else { - return indentAmt; - } - } - } - TypeScript.LexAdjustIndent = LexAdjustIndent; - function LexIsIdentifierStartChar(code) { - return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); - } - TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; - function LexIsDigit(code) { - return ((code >= 48) && (code <= 57)); - } - TypeScript.LexIsDigit = LexIsDigit; - function LexIsIdentifierChar(code) { - return lexIdStartTable[code] || LexIsDigit(code); - } - TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; - function LexMatchingOpen(code) { - if(code == TypeScript.LexCodeRBR) { - return TypeScript.LexCodeLBR; - } else { - if(code == TypeScript.LexCodeRC) { - return TypeScript.LexCodeLC; - } else { - if(code == TypeScript.LexCodeRPR) { - return TypeScript.LexCodeLPR; - } else { - return 0; - } - } - } - } - TypeScript.LexMatchingOpen = LexMatchingOpen; - (function (NumberScanState) { - NumberScanState._map = []; - NumberScanState._map[0] = "Start"; - NumberScanState.Start = 0; - NumberScanState._map[1] = "InFraction"; - NumberScanState.InFraction = 1; - NumberScanState._map[2] = "InEmptyFraction"; - NumberScanState.InEmptyFraction = 2; - NumberScanState._map[3] = "InExponent"; - NumberScanState.InExponent = 3; - })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); - var NumberScanState = TypeScript.NumberScanState; - (function (LexState) { - LexState._map = []; - LexState._map[0] = "Start"; - LexState.Start = 0; - LexState._map[1] = "InMultilineComment"; - LexState.InMultilineComment = 1; - LexState._map[2] = "InMultilineSingleQuoteString"; - LexState.InMultilineSingleQuoteString = 2; - LexState._map[3] = "InMultilineDoubleQuoteString"; - LexState.InMultilineDoubleQuoteString = 3; - })(TypeScript.LexState || (TypeScript.LexState = {})); - var LexState = TypeScript.LexState; - (function (LexMode) { - LexMode._map = []; - LexMode._map[0] = "Line"; - LexMode.Line = 0; - LexMode._map[1] = "File"; - LexMode.File = 1; - })(TypeScript.LexMode || (TypeScript.LexMode = {})); - var LexMode = TypeScript.LexMode; - (function (CommentStyle) { - CommentStyle._map = []; - CommentStyle._map[0] = "Line"; - CommentStyle.Line = 0; - CommentStyle._map[1] = "Block"; - CommentStyle.Block = 1; - })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); - var CommentStyle = TypeScript.CommentStyle; - var StringSourceText = (function () { - function StringSourceText(text) { - this.text = text; - } - StringSourceText.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringSourceText.prototype.getLength = function () { - return this.text.length; - }; - return StringSourceText; - })(); - TypeScript.StringSourceText = StringSourceText; - var SourceTextSegment = (function () { - function SourceTextSegment(segmentStart, segmentEnd, segment) { - this.segmentStart = segmentStart; - this.segmentEnd = segmentEnd; - this.segment = segment; - } - SourceTextSegment.prototype.charCodeAt = function (index) { - return this.segment.charCodeAt(index - this.segmentStart); - }; - SourceTextSegment.prototype.substring = function (start, end) { - return this.segment.substring(start - this.segmentStart, end - this.segmentStart); - }; - return SourceTextSegment; - })(); - TypeScript.SourceTextSegment = SourceTextSegment; - var AggerateSourceTextSegment = (function () { - function AggerateSourceTextSegment(seg1, seg2) { - this.seg1 = seg1; - this.seg2 = seg2; - } - AggerateSourceTextSegment.prototype.charCodeAt = function (index) { - if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { - return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); - } - return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); - }; - AggerateSourceTextSegment.prototype.substring = function (start, end) { - if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { - return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); - } - return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); - }; - return AggerateSourceTextSegment; - })(); - TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; - var ScannerTextStream = (function () { - function ScannerTextStream(sourceText) { - this.sourceText = sourceText; - this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); - this.len = this.sourceText.getLength(); - } - ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); - ScannerTextStream.prototype.max = function (a, b) { - return a >= b ? a : b; - }; - ScannerTextStream.prototype.min = function (a, b) { - return a <= b ? a : b; - }; - ScannerTextStream.prototype.fetchSegment = function (start, end) { - if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg.seg1; - } - if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg; - } - var prev = this.agg.seg1; - var s = prev.segmentEnd; - var e = TypeScript.max(s + 512, end); - e = TypeScript.min(e, this.len); - var src = this.sourceText.getText(s, e); - var newSeg = new SourceTextSegment(s, e, src); - this.agg.seg2 = prev; - this.agg.seg1 = newSeg; - return this.agg; - }; - ScannerTextStream.prototype.charCodeAt = function (index) { - return this.fetchSegment(index, index + 1).charCodeAt(index); - }; - ScannerTextStream.prototype.substring = function (start, end) { - return this.fetchSegment(start, end).substring(start, end); - }; - return ScannerTextStream; - })(); - TypeScript.ScannerTextStream = ScannerTextStream; - var SavedTokens = (function () { - function SavedTokens() { - this.prevToken = null; - this.curSavedToken = null; - this.prevSavedToken = null; - this.prevToken = null; - this.currentToken = 0; - this.tokens = new Array(); - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.lexState = LexState.Start; - this.commentStack = new Array(); - this.lineMap = []; - } - SavedTokens.prototype.previousToken = function () { - return this.prevToken; - }; - SavedTokens.prototype.close = function () { - this.currentToken = 0; - }; - SavedTokens.prototype.addToken = function (tok, scanner) { - this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); - }; - SavedTokens.prototype.scan = function () { - this.startLine = this.line; - this.startPos = this.col; - if(this.currentTokenIndex == this.currentTokens.length) { - if(this.line < this.lineMap.length) { - this.line++; - this.col = 0; - this.currentTokenIndex = 0; - this.currentTokens = this.tokensByLine[this.line]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(this.currentTokenIndex < this.currentTokens.length) { - this.prevToken = this.curSavedToken.tok; - this.prevSavedToken = this.curSavedToken; - this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; - var curToken = this.curSavedToken.tok; - this.pos = this.curSavedToken.limChar; - this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); - this.startPos = this.curSavedToken.minChar; - this.prevLine = this.line; - return curToken; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - }; - SavedTokens.prototype.syncToTok = function (offset) { - this.line = getLineNumberFromPosition(this.lineMap, offset); - this.currentTokenIndex = 0; - var tmpCol = offset - this.lineMap[this.line]; - while((this.lexStateByLine[this.line] == LexState.InMultilineComment) && (this.line > 0)) { - this.line--; - tmpCol = 0; - } - var lenMin1 = this.lineMap.length - 1; - this.currentTokens = this.tokensByLine[this.line]; - while((this.currentTokens.length == 0) && (this.line < lenMin1)) { - this.line++; - this.currentTokens = this.tokensByLine[this.line]; - tmpCol = 0; - } - if(this.line <= lenMin1) { - while((this.currentTokenIndex < this.currentTokens.length) && (tmpCol > this.currentTokens[this.currentTokenIndex].limChar)) { - this.currentTokenIndex++; - } - if(this.currentTokenIndex < this.currentTokens.length) { - this.col = this.currentTokens[this.currentTokenIndex].minChar; - return this.col + this.lineMap[this.line]; - } - } - return -1; - }; - SavedTokens.prototype.lastTokenLimChar = function () { - if(this.prevSavedToken !== null) { - return this.prevSavedToken.limChar; - } else { - return 0; - } - }; - SavedTokens.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - SavedTokens.prototype.pushComment = function (comment) { - this.commentStack.push(comment); - }; - SavedTokens.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - SavedTokens.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - SavedTokens.prototype.resetComments = function () { - this.commentStack = []; - }; - SavedTokens.prototype.setSourceText = function (newSrc, textMode) { - }; - SavedTokens.prototype.setErrorHandler = function (reportError) { - }; - SavedTokens.prototype.getLookAheadToken = function () { - throw new Error("Invalid operation."); - }; - return SavedTokens; - })(); - TypeScript.SavedTokens = SavedTokens; - var Scanner = (function () { - function Scanner() { - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.pos = 0; - this.startPos = 0; - this.len = 0; - this.lineMap = []; - this.ch = TypeScript.LexEOF; - this.lexState = LexState.Start; - this.mode = LexMode.File; - this.scanComments = true; - this.interveningWhitespace = false; - this.interveningWhitespacePos = 0; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.commentStack = new Array(); - this.saveScan = null; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - this.startCol = this.col; - this.startLine = this.line; - this.lineMap[1] = 0; - if(!TypeScript.LexKeywordTable) { - LexInitialize(); - } - } - Scanner.prototype.previousToken = function () { - return this.prevTok; - }; - Scanner.prototype.setSourceText = function (newSrc, textMode) { - this.mode = textMode; - this.scanComments = (this.mode === LexMode.Line); - this.pos = 0; - this.interveningWhitespacePos = 0; - this.startPos = 0; - this.line = 1; - this.col = 0; - this.startCol = this.col; - this.startLine = this.line; - this.len = 0; - this.src = newSrc.getText(0, newSrc.getLength()); - this.len = this.src.length; - this.lineMap = []; - this.lineMap[1] = 0; - this.commentStack = []; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - }; - Scanner.prototype.setErrorHandler = function (reportError) { - this.reportError = reportError; - }; - Scanner.prototype.setSaveScan = function (savedTokens) { - this.saveScan = savedTokens; - }; - Scanner.prototype.setText = function (newSrc, textMode) { - this.setSourceText(new StringSourceText(newSrc), textMode); - }; - Scanner.prototype.setScanComments = function (value) { - this.scanComments = value; - }; - Scanner.prototype.getLexState = function () { - return this.lexState; - }; - Scanner.prototype.tokenStart = function () { - this.startPos = this.pos; - this.startLine = this.line; - this.startCol = this.col; - this.interveningWhitespace = false; - }; - Scanner.prototype.peekChar = function () { - if(this.pos < this.len) { - return this.src.charCodeAt(this.pos); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.peekCharAt = function (index) { - if(index < this.len) { - return this.src.charCodeAt(index); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.IsHexDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.IsOctalDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.scanHexDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanOctalDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsOctalDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanDecimalNumber = function (state) { - var atLeastOneDigit = false; - var svPos = this.pos; - var svCol = this.col; - for(; ; ) { - if(LexIsDigit(this.ch)) { - atLeastOneDigit = true; - if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { - state = NumberScanState.InFraction; - } - this.nextChar(); - } else { - if(this.ch == TypeScript.LexCodeDOT) { - if(state == NumberScanState.Start) { - this.nextChar(); - state = NumberScanState.InEmptyFraction; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } else { - if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { - if(state == NumberScanState.Start) { - if(atLeastOneDigit) { - atLeastOneDigit = false; - this.nextChar(); - state = NumberScanState.InExponent; - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else { - if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { - this.nextChar(); - state = NumberScanState.InExponent; - atLeastOneDigit = false; - } else { - if(atLeastOneDigit) { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } - } else { - if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { - if(state == NumberScanState.InExponent) { - if(!atLeastOneDigit) { - this.nextChar(); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else { - if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); - } - } - } - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); - } - } - } - } - } - } - }; - Scanner.prototype.scanNumber = function () { - if(this.peekChar() == TypeScript.LexCode_0) { - switch(this.peekCharAt(this.pos + 1)) { - case TypeScript.LexCode_x: - case TypeScript.LexCode_X: { - this.advanceChar(2); - return this.scanHexDigits(); - - } - case TypeScript.LexCode_8: - case TypeScript.LexCode_9: - case TypeScript.LexCodeDOT: { - return this.scanDecimalNumber(NumberScanState.Start); - - } - default: { - return this.scanOctalDigits(); - - } - } - } else { - return this.scanDecimalNumber(NumberScanState.Start); - } - }; - Scanner.prototype.scanFraction = function () { - return this.scanDecimalNumber(NumberScanState.InFraction); - }; - Scanner.prototype.newLine = function () { - this.col = 0; - if(this.mode == LexMode.File) { - this.line++; - this.lineMap[this.line] = this.pos + 1; - } - }; - Scanner.prototype.finishMultilineComment = function () { - var ch2; - this.lexState = LexState.InMultilineComment; - while(this.pos < this.len) { - if(this.ch == TypeScript.LexCodeMUL) { - ch2 = this.peekCharAt(this.pos + 1); - if(ch2 == TypeScript.LexCodeSLH) { - this.advanceChar(2); - if(this.mode == LexMode.File) { - this.tokenStart(); - } - this.lexState = LexState.Start; - return true; - } - } else { - if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - this.nextChar(); - return false; - } - } else { - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - } - } - this.nextChar(); - } - return false; - }; - Scanner.prototype.pushComment = function (comment) { - this.commentStack.push(comment); - }; - Scanner.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - Scanner.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - Scanner.prototype.resetComments = function () { - this.commentStack = []; - }; - Scanner.prototype.endsLine = function (c) { - return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); - }; - Scanner.prototype.finishSinglelineComment = function () { - while(this.pos < this.len) { - if(this.endsLine(this.ch)) { - break; - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - this.nextChar(); - } - if(this.mode == LexMode.File) { - this.tokenStart(); - } - }; - Scanner.prototype.tokenText = function () { - return this.src.substring(this.startPos, this.pos); - }; - Scanner.prototype.findClosingSLH = function () { - var index = this.pos; - var ch2 = this.src.charCodeAt(index); - var prevCh = 0; - var liveEsc = false; - while(!this.endsLine(ch2) && (index < this.len)) { - if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { - return index; - } - prevCh = ch2; - index++; - if(liveEsc) { - liveEsc = false; - } else { - liveEsc = (prevCh == TypeScript.LexCodeBSL); - } - ch2 = this.src.charCodeAt(index); - } - return -1; - }; - Scanner.prototype.speculateRegex = function () { - if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { - return null; - } - var svPos = this.pos; - var svCol = this.col; - var index = this.findClosingSLH(); - if(index > 0) { - var pattern = this.src.substring(svPos, index); - var flags = ""; - this.pos = index + 1; - this.ch = this.peekChar(); - var flagsStart = this.pos; - while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { - this.nextChar(); - } - if((this.pos - flagsStart) > 3) { - return null; - } else { - flags = this.src.substring(flagsStart, this.pos); - } - var regex = undefined; - try { - regex = new RegExp(pattern, flags); - } catch (regexException) { - } - if(regex) { - this.col = svCol + (this.pos - this.startPos); - return new TypeScript.RegularExpressionLiteralToken(regex); - } - } - this.pos = svPos; - this.col = svCol; - return null; - }; - Scanner.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - Scanner.prototype.lastTokenLimChar = function () { - return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; - }; - Scanner.prototype.advanceChar = function (amt) { - this.pos += amt; - this.col += amt; - this.ch = this.peekChar(); - }; - Scanner.prototype.nextChar = function () { - this.pos++; - this.col++; - this.ch = this.peekChar(); - }; - Scanner.prototype.getLookAheadToken = function () { - var prevLine = this.prevLine; - var line = this.line; - var col = this.col; - var pos = this.pos; - var startPos = this.startPos; - var startCol = this.startCol; - var startLine = this.startLine; - var ch = this.ch; - var prevTok = this.prevTok; - var lexState = this.lexState; - var interveningWhitespace = this.interveningWhitespace; - var interveningWhitespacePos = this.interveningWhitespacePos; - var leftCurlyCount = this.leftCurlyCount; - var rightCurlyCount = this.rightCurlyCount; - var seenUnicodeChar = this.seenUnicodeChar; - var seenUnicodeCharInComment = this.seenUnicodeCharInComment; - var commentStackLength = this.commentStack.length; - var lookAheadToken = this.scan(); - this.prevLine = prevLine; - this.line = line; - this.col = col; - this.pos = pos; - this.startPos = startPos; - this.startCol = startCol; - this.startLine = startLine; - this.ch = ch; - this.prevTok = prevTok; - this.lexState = lexState; - this.interveningWhitespace = interveningWhitespace; - this.interveningWhitespacePos = interveningWhitespacePos; - this.leftCurlyCount = leftCurlyCount; - this.rightCurlyCount = rightCurlyCount; - this.seenUnicodeChar = seenUnicodeChar; - this.seenUnicodeCharInComment = seenUnicodeCharInComment; - this.commentStack.length = commentStackLength; - return lookAheadToken; - }; - Scanner.prototype.scanInLine = function () { - if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { - this.ch = this.peekChar(); - var commentLine = this.line; - this.finishMultilineComment(); - if(this.startPos < this.pos) { - var commentText = this.src.substring(this.startPos, this.pos); - this.tokenStart(); - return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } else { - if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { - this.ch = TypeScript.LexCodeAPO; - this.lexState = LexState.Start; - return this.scanStringConstant(); - } else { - if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { - this.ch = TypeScript.LexCodeQUO; - this.lexState = LexState.Start; - return this.scanStringConstant(); - } - } - } - this.prevLine = this.line; - var prevTok = this.innerScan(); - if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { - this.prevTok = prevTok; - } - return prevTok; - }; - Scanner.prototype.scan = function () { - this.prevLine = this.line; - this.prevTok = this.innerScan(); - if(this.saveScan) { - this.saveScan.addToken(this.prevTok, this); - } - return this.prevTok; - }; - Scanner.prototype.isValidUnicodeIdentifierChar = function () { - var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); - this.seenUnicodeChar = this.seenUnicodeChar || valid; - return valid; - }; - Scanner.prototype.scanStringConstant = function () { - var endCode = this.ch; - this.nextChar(); - scanStringConstantLoop: -for(; ; ) { - switch(this.ch) { - case TypeScript.LexEOF: { - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - - } - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: { - this.seenUnicodeChar = true; - - } - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: { - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - - } - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: { - if(this.ch == endCode) { - this.nextChar(); - break scanStringConstantLoop; - } - break; - - } - case TypeScript.LexCodeBSL: { - this.nextChar(); - switch(this.ch) { - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: - case TypeScript.LexCodeBSL: { - this.nextChar(); - continue scanStringConstantLoop; - - } - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: { - this.seenUnicodeChar = true; - - } - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: { - if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { - this.nextChar(); - } - this.nextChar(); - this.newLine(); - if(this.mode == LexMode.Line) { - this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; - break scanStringConstantLoop; - } - break; - - } - case TypeScript.LexCode_x: - case TypeScript.LexCode_u: { - var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; - this.nextChar(); - for(var i = 0; i < expectedHexDigits; i++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - break; - } - } - continue scanStringConstantLoop; - - } - } - break; - - } - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeChar = true; - } - this.nextChar(); - } - return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); - }; - Scanner.prototype.scanIdentifier = function () { - var hasEscape = false; - var isFirstChar = (this.ch == TypeScript.LexCodeBSL); - var hasUnicode = false; - for(; ; ) { - while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { - this.nextChar(); - } - if(this.ch == TypeScript.LexCodeBSL) { - this.nextChar(); - if(this.ch == TypeScript.LexCode_u) { - this.nextChar(); - for(var h = 0; h < 4; h++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } - var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); - if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { - } else { - this.reportScannerError("Invalid identifier character"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - hasEscape = true; - isFirstChar = false; - continue; - } - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - break; - } - var id; - var text = this.src.substring(this.startPos, this.pos); - if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { - return TypeScript.staticTokens[id]; - } else { - return new TypeScript.IdentifierToken(text, hasEscape); - } - }; - Scanner.prototype.innerScan = function () { - var rtok; - this.tokenStart(); - this.ch = this.peekChar(); - start: -while(this.pos < this.len) { - if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { - return this.scanIdentifier(); - } else { - if(this.ch == TypeScript.LexCodeSpace) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - do { - this.nextChar(); - }while(this.ch == TypeScript.LexCodeSpace) - if(this.mode == LexMode.Line) { - var whitespaceText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); - } else { - this.tokenStart(); - this.interveningWhitespace = true; - } - } else { - if(this.ch == TypeScript.LexCodeSLH) { - this.nextChar(); - var commentText; - if(this.ch == TypeScript.LexCodeSLH) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.finishSinglelineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else { - if(this.ch == TypeScript.LexCodeMUL) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.nextChar(); - this.finishMultilineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var endsLine = this.endsLine(this.peekChar()); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else { - var regexTok = this.speculateRegex(); - if(regexTok) { - return regexTok; - } else { - if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Slash]; - } - } - } - } - } else { - if(this.ch == TypeScript.LexCodeSMC) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - } else { - if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { - return this.scanStringConstant(); - } else { - if(autoToken[this.ch]) { - var atok = autoToken[this.ch]; - if(atok.tokenId == TypeScript.TokenID.OpenBrace) { - this.leftCurlyCount++; - } else { - if(atok.tokenId == TypeScript.TokenID.CloseBrace) { - this.rightCurlyCount++; - } - } - this.nextChar(); - return atok; - } else { - if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { - rtok = this.scanNumber(); - if(rtok) { - return rtok; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } else { - switch(this.ch) { - case TypeScript.LexCodeTAB: - case TypeScript.LexCodeVTAB: { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - if(this.mode == LexMode.Line) { - do { - this.nextChar(); - }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)) - var wsText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); - } else { - this.interveningWhitespace = true; - } - - } - case 255: - case 254: - case 239: - case 187: - case 191: - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - case TypeScript.LexCodeNWL: - case TypeScript.LexCodeRET: { - if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - this.nextChar(); - this.tokenStart(); - this.interveningWhitespace = true; - break; - - } - case TypeScript.LexCodeDOT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } else { - this.nextChar(); - rtok = this.scanFraction(); - if(rtok) { - return rtok; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } - } - - case TypeScript.LexCodeEQ: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; - } - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Equals]; - } - } - - } - case TypeScript.LexCodeBNG: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; - } - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; - } - - } - case TypeScript.LexCodePLS: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Plus]; - } - } - - } - case TypeScript.LexCodeMIN: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Minus]; - } - } - - } - case TypeScript.LexCodeMUL: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; - } - - } - case TypeScript.LexCodePCT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Percent]; - } - - } - case TypeScript.LexCodeLT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; - } - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; - } - } - - } - case TypeScript.LexCodeGT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; - } else { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { - this.advanceChar(4); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; - } else { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; - } - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; - } - } - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; - } - } - - } - case TypeScript.LexCodeXOR: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Caret]; - } - - } - case TypeScript.LexCodeBAR: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Bar]; - } - } - - } - case TypeScript.LexCodeAMP: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; - } else { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.And]; - } - } - - } - default: { - this.reportScannerError("Invalid character"); - this.nextChar(); - continue start; - - } - } - } - } - } - } - } - } - } - } - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - }; - Scanner.prototype.reportScannerError = function (message) { - if(this.reportError) { - this.reportError(message); - } - }; - return Scanner; - })(); - TypeScript.Scanner = Scanner; - function convertTokToIDName(tok) { - return convertTokToIDBase(tok, true, false); - } - TypeScript.convertTokToIDName = convertTokToIDName; - function convertTokToID(tok, strictMode) { - return convertTokToIDBase(tok, false, strictMode); - } - TypeScript.convertTokToID = convertTokToID; - function convertTokToIDBase(tok, identifierName, strictMode) { - if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { - var tokInfo = TypeScript.lookupToken(tok.tokenId); - if(tokInfo != undefined) { - var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; - if(strictMode) { - resFlags |= TypeScript.Reservation.JavascriptFutureStrict; - } - if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { - return true; - } - } else { - return false; - } - } else { - return false; - } - } - function getLineNumberFromPosition(lineMap, position) { - if(position === -1) { - return 0; - } - var min = 0; - var max = lineMap.length - 1; - while(min < max) { - var med = (min + max) >> 1; - if(position < lineMap[med]) { - max = med - 1; - } else { - if(position < lineMap[med + 1]) { - min = max = med; - } else { - min = med + 1; - } - } - } - return min; - } - TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; - function getSourceLineColFromMap(lineCol, minChar, lineMap) { - var line = getLineNumberFromPosition(lineMap, minChar); - if(line > 0) { - lineCol.line = line; - lineCol.col = (minChar - lineMap[line]); - } - } - TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; - function getLineColumnFromPosition(script, position) { - var result = { - line: -1, - col: -1 - }; - getSourceLineColFromMap(result, position, script.locationInfo.lineMap); - if(result.col >= 0) { - result.col++; - } - return result; - } - TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; - function getPositionFromLineColumn(script, line, column) { - return script.locationInfo.lineMap[line] + (column - 1); - } - TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; - function isPrimitiveTypeToken(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.String: { - return true; - - } - } - return false; - } - TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; - function isModifier(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Public: - case TypeScript.TokenID.Private: - case TypeScript.TokenID.Static: { - return true; - - } - } - return false; - } - TypeScript.isModifier = isModifier; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AssignScopeContext = (function () { - function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { - this.scopeChain = scopeChain; - this.typeFlow = typeFlow; - this.modDeclChain = modDeclChain; - } - return AssignScopeContext; - })(); - TypeScript.AssignScopeContext = AssignScopeContext; - function pushAssignScope(scope, context, type, classType, fnc) { - var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); - chain.thisType = type; - chain.classType = classType; - chain.fnc = fnc; - context.scopeChain = chain; - } - TypeScript.pushAssignScope = pushAssignScope; - function popAssignScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popAssignScope = popAssignScope; - function instanceCompare(a, b) { - if(((a == null) || (!a.isInstanceProperty()))) { - return b; - } else { - return a; - } - } - TypeScript.instanceCompare = instanceCompare; - function instanceFilterStop(s) { - return s.isInstanceProperty(); - } - TypeScript.instanceFilterStop = instanceFilterStop; - var ScopeSearchFilter = (function () { - function ScopeSearchFilter(select, stop) { - this.select = select; - this.stop = stop; - this.result = null; - } - ScopeSearchFilter.prototype.reset = function () { - this.result = null; - }; - ScopeSearchFilter.prototype.update = function (b) { - this.result = this.select(this.result, b); - if(this.result) { - return this.stop(this.result); - } else { - return false; - } - }; - return ScopeSearchFilter; - })(); - TypeScript.ScopeSearchFilter = ScopeSearchFilter; - TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); - function preAssignModuleScopes(ast, context) { - var moduleDecl = ast; - var memberScope = null; - var aggScope = null; - if(moduleDecl.name && moduleDecl.mod) { - moduleDecl.name.sym = moduleDecl.mod.symbol; - } - var mod = moduleDecl.mod; - if(!mod) { - return; - } - memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); - mod.memberScope = memberScope; - context.modDeclChain.push(moduleDecl); - context.typeFlow.checker.currentModDecl = moduleDecl; - aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - mod.containedScope = aggScope; - if(mod.symbol) { - context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); - } - } - TypeScript.preAssignModuleScopes = preAssignModuleScopes; - function preAssignClassScopes(ast, context) { - var classDecl = ast; - var memberScope = null; - var aggScope = null; - if(classDecl.name && classDecl.type) { - classDecl.name.sym = classDecl.type.symbol; - } - var classType = ast.type; - if(classType) { - var classSym = classType.symbol; - memberScope = context.typeFlow.checker.scopeOf(classType); - aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - classType.containedScope = aggScope; - classType.memberScope = memberScope; - var instanceType = classType.instanceType; - memberScope = context.typeFlow.checker.scopeOf(instanceType); - instanceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, instanceType, classType, null); - instanceType.containedScope = aggScope; - } else { - ast.type = context.typeFlow.anyType; - } - } - TypeScript.preAssignClassScopes = preAssignClassScopes; - function preAssignInterfaceScopes(ast, context) { - var interfaceDecl = ast; - var memberScope = null; - var aggScope = null; - if(interfaceDecl.name && interfaceDecl.type) { - interfaceDecl.name.sym = interfaceDecl.type.symbol; - } - var interfaceType = ast.type; - memberScope = context.typeFlow.checker.scopeOf(interfaceType); - interfaceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - interfaceType.containedScope = aggScope; - } - TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; - function preAssignWithScopes(ast, context) { - var withStmt = ast; - var withType = withStmt.type; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var withType = new TypeScript.Type(); - var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); - withType.members = members; - withType.ambientMembers = ambientMembers; - withType.symbol = withSymbol; - withType.setHasImplementation(); - withStmt.type = withType; - var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); - pushAssignScope(withScope, context, null, null, null); - withType.containedScope = withScope; - } - TypeScript.preAssignWithScopes = preAssignWithScopes; - function preAssignFuncDeclScopes(ast, context) { - var funcDecl = ast; - var container = null; - var localContainer = null; - if(funcDecl.type) { - localContainer = ast.type.symbol; - } - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isInnerStatic = isStatic && context.scopeChain.fnc != null; - var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; - if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { - var instType = context.scopeChain.thisType; - if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(!funcDecl.isMethod() || isStatic) { - parentScope = instType.constructorScope; - } else { - parentScope = instType.containedScope; - } - } else { - if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { - parentScope = instType.constructorScope; - } else { - if(isStatic && context.scopeChain.classType) { - parentScope = context.scopeChain.classType.containedScope; - } else { - parentScope = instType.containedScope; - } - } - } - container = instType.symbol; - } else { - if(funcDecl.isConstructor && context.scopeChain.thisType) { - container = context.scopeChain.thisType.symbol; - } - } - if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { - if(context.scopeChain.fnc && context.scopeChain.fnc.type) { - container = context.scopeChain.fnc.type.symbol; - } - var funcScope = null; - var outerFnc = context.scopeChain.fnc; - var nameText = funcDecl.name ? funcDecl.name.actualText : null; - var fgSym = null; - if(isStatic) { - if(outerFnc.type.members == null && container.getType().memberScope) { - outerFnc.type.members = ((container).type.memberScope).valueMembers; - } - funcScope = context.scopeChain.fnc.type.memberScope; - outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; - } else { - funcScope = context.scopeChain.scope; - } - if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { - if(isStatic) { - fgSym = funcScope.findLocal(nameText, false, false); - } else { - fgSym = funcScope.findLocal(nameText, false, false); - } - } - context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); - if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); - } - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; - } - if(funcDecl.name && funcDecl.type) { - funcDecl.name.sym = funcDecl.type.symbol; - } - funcDecl.scopeType = funcDecl.type; - if(funcDecl.isOverload) { - return; - } - var funcTable = new TypeScript.StringHashTable(); - var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); - var ambientFuncTable = new TypeScript.StringHashTable(); - var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); - var funcStaticTable = new TypeScript.StringHashTable(); - var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); - var ambientFuncStaticTable = new TypeScript.StringHashTable(); - var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); - funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; - var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); - var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); - if(funcDecl.isConstructor && context.scopeChain.thisType) { - context.scopeChain.thisType.constructorScope = locals; - } - funcDecl.symbols = funcTable; - if(!funcDecl.isSpecialFn()) { - var group = funcDecl.type; - var signature = funcDecl.signature; - if(!funcDecl.isConstructor) { - group.containedScope = locals; - locals.container = group.symbol; - group.memberScope = statics; - statics.container = group.symbol; - } - funcDecl.enclosingFnc = context.scopeChain.fnc; - group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; - var fgSym = ast.type.symbol; - if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { - context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); - context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); - } - if(signature.parameters) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); - } - } - context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); - } - if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; - pushAssignScope(locals, context, thisType, null, funcDecl); - } - if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { - if(funcDecl.name.sym) { - funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); - } - } - } - TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; - function preAssignCatchScopes(ast, context) { - var catchBlock = ast; - if(catchBlock.param) { - var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); - catchBlock.containedScope = catchLocals; - pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); - } - } - TypeScript.preAssignCatchScopes = preAssignCatchScopes; - function preAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - list.enclosingScope = context.scopeChain.scope; - } else { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - preAssignModuleScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - preAssignClassScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - preAssignInterfaceScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - preAssignWithScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - preAssignFuncDeclScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.Catch) { - preAssignCatchScopes(ast, context); - } else { - if(ast.nodeType == TypeScript.NodeType.TypeRef) { - go = false; - } - } - } - } - } - } - } - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preAssignScopes = preAssignScopes; - function postAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var prevModDecl = ast; - popAssignScope(context); - context.modDeclChain.pop(); - if(context.modDeclChain.length >= 1) { - context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; - } - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - popAssignScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - popAssignScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - popAssignScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { - popAssignScope(context); - } - } else { - if(ast.nodeType == TypeScript.NodeType.Catch) { - var catchBlock = ast; - if(catchBlock.param) { - popAssignScope(context); - } - } else { - go = false; - } - } - } - } - } - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.postAssignScopes = postAssignScopes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var TypeCollectionContext = (function () { - function TypeCollectionContext(scopeChain, checker) { - this.scopeChain = scopeChain; - this.checker = checker; - this.script = null; - } - return TypeCollectionContext; - })(); - TypeScript.TypeCollectionContext = TypeCollectionContext; - var MemberScopeContext = (function () { - function MemberScopeContext(flow, pos, matchFlag) { - this.flow = flow; - this.pos = pos; - this.matchFlag = matchFlag; - this.type = null; - this.ast = null; - this.options = new TypeScript.AstWalkOptions(); - } - return MemberScopeContext; - })(); - TypeScript.MemberScopeContext = MemberScopeContext; - var EnclosingScopeContext = (function () { - function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { - this.logger = logger; - this.script = script; - this.text = text; - this.pos = pos; - this.isMemberCompletion = isMemberCompletion; - this.scopeGetter = null; - this.objectLiteralScopeGetter = null; - this.scopeStartAST = null; - this.skipNextFuncDeclForClass = false; - this.deepestModuleDecl = null; - this.enclosingClassDecl = null; - this.enclosingObjectLit = null; - this.publicsOnly = true; - this.useFullAst = false; - } - EnclosingScopeContext.prototype.getScope = function () { - return this.scopeGetter(); - }; - EnclosingScopeContext.prototype.getObjectLiteralScope = function () { - return this.objectLiteralScopeGetter(); - }; - EnclosingScopeContext.prototype.getScopeAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScopePosition = function () { - return this.scopeStartAST.minChar; - }; - EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { - return this.getScriptFragmentStartAST().minChar; - }; - EnclosingScopeContext.prototype.getScriptFragment = function () { - if(this.scriptFragment == null) { - var ast = this.getScriptFragmentStartAST(); - var minChar = ast.minChar; - var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); - this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; - } - return this.scriptFragment; - }; - return EnclosingScopeContext; - })(); - TypeScript.EnclosingScopeContext = EnclosingScopeContext; - function preFindMemberScope(ast, parent, walker) { - var memScope = walker.state; - if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { - memScope.ast = ast; - if((ast.type == null) && (memScope.pos >= 0)) { - memScope.flow.inScopeTypeCheck(ast, memScope.scope); - } - memScope.type = ast.type; - memScope.options.stopWalk(); - } - return ast; - } - TypeScript.preFindMemberScope = preFindMemberScope; - function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { - var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); - var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); - chain.thisType = thisType; - chain.classType = classType; - chain.moduleDecl = moduleDecl; - context.scopeChain = chain; - } - TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; - function popTypeCollectionScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popTypeCollectionScope = popTypeCollectionScope; - function preFindEnclosingScope(ast, parent, walker) { - var context = walker.state; - var minChar = ast.minChar; - var limChar = ast.limChar; - if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { - limChar = context.pos; - } - if((minChar <= context.pos) && (limChar >= context.pos)) { - switch(ast.nodeType) { - case TypeScript.NodeType.Script: { - var script = ast; - context.scopeGetter = function () { - return script.bod === null ? null : script.bod.enclosingScope; - }; - context.scopeStartAST = script; - break; - - } - case TypeScript.NodeType.ClassDeclaration: { - context.scopeGetter = function () { - return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; - }; - context.scopeStartAST = ast; - context.enclosingClassDecl = ast; - break; - - } - case TypeScript.NodeType.ObjectLit: { - var objectLit = ast; - if(objectLit.targetType) { - context.scopeGetter = function () { - return objectLit.targetType.containedScope; - }; - context.objectLiteralScopeGetter = function () { - return objectLit.targetType.memberScope; - }; - context.enclosingObjectLit = objectLit; - } - break; - - } - case TypeScript.NodeType.ModuleDeclaration: { - context.deepestModuleDecl = ast; - context.scopeGetter = function () { - return ast.type === null ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - - } - case TypeScript.NodeType.InterfaceDeclaration: { - context.scopeGetter = function () { - return (ast.type === null) ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - - } - case TypeScript.NodeType.FuncDecl: { - { - var funcDecl = ast; - if(context.skipNextFuncDeclForClass) { - context.skipNextFuncDeclForClass = false; - } else { - context.scopeGetter = function () { - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(ast.type && ast.type.enclosingType) { - return ast.type.enclosingType.constructorScope; - } - } - if(funcDecl.scopeType) { - return funcDecl.scopeType.containedScope; - } - if(funcDecl.type) { - return funcDecl.type.containedScope; - } - return null; - }; - context.scopeStartAST = ast; - } - } - break; - - } - } - walker.options.goChildren = true; - } else { - walker.options.goChildren = false; - } - return ast; - } - TypeScript.preFindEnclosingScope = preFindEnclosingScope; - function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { - var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); - TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); - if(context.scopeStartAST === null) { - return null; - } - return context; - } - TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Signature = (function () { - function Signature() { - this.hasVariableArgList = false; - this.parameters = null; - this.declAST = null; - this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - this.nonOptionalParameterCount = 0; - } - Signature.prototype.specializeType = function (pattern, replacement, checker) { - var result = new Signature(); - if(this.hasVariableArgList) { - result.hasVariableArgList = true; - } - result.returnType = new TypeScript.TypeLink(); - if(this.returnType.type) { - result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); - } else { - result.returnType.type = checker.anyType; - } - if(this.parameters) { - result.parameters = []; - for(var i = 0, len = this.parameters.length; i < len; i++) { - var oldSym = this.parameters[i]; - var paramDef = new TypeScript.ValueLocation(); - var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); - paramSym.declAST = this.declAST; - paramDef.symbol = paramSym; - paramDef.typeLink = new TypeScript.TypeLink(); - result.parameters[i] = paramSym; - var oldType = oldSym.getType(); - if(oldType) { - paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); - paramSym.declAST.type = paramDef.typeLink.type; - } else { - paramDef.typeLink.type = checker.anyType; - } - } - } - result.nonOptionalParameterCount = this.nonOptionalParameterCount; - result.declAST = this.declAST; - return result; - }; - Signature.prototype.toString = function () { - return this.toStringHelper(false, false, null); - }; - Signature.prototype.toStringHelper = function (shortform, brackets, scope) { - return this.toStringHelperEx(shortform, brackets, scope).toString(); - }; - Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { - if (typeof prefix === "undefined") { prefix = ""; } - var builder = new TypeScript.MemberNameArray(); - if(brackets) { - builder.prefix = prefix + "["; - } else { - builder.prefix = prefix + "("; - } - var paramLen = this.parameters.length; - var len = this.hasVariableArgList ? paramLen - 1 : paramLen; - for(var i = 0; i < len; i++) { - builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - if(i < paramLen - 1) { - builder.add(TypeScript.MemberName.create(", ")); - } - } - if(this.hasVariableArgList) { - builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - } - if(shortform) { - if(brackets) { - builder.add(TypeScript.MemberName.create("] => ")); - } else { - builder.add(TypeScript.MemberName.create(") => ")); - } - } else { - if(brackets) { - builder.add(TypeScript.MemberName.create("]: ")); - } else { - builder.add(TypeScript.MemberName.create("): ")); - } - } - if(this.returnType.type) { - builder.add(this.returnType.type.getScopedTypeNameEx(scope)); - } else { - builder.add(TypeScript.MemberName.create("any")); - } - return builder; - }; - return Signature; - })(); - TypeScript.Signature = Signature; - var SignatureGroup = (function () { - function SignatureGroup() { - this.signatures = []; - this.hasImplementation = true; - this.definitionSignature = null; - this.hasBeenTypechecked = false; - this.flags = TypeScript.SignatureFlags.None; - } - SignatureGroup.prototype.addSignature = function (signature) { - if(this.signatures == null) { - this.signatures = new Array(); - } - this.signatures[this.signatures.length] = signature; - if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Definition)) { - this.definitionSignature = signature; - } - }; - SignatureGroup.prototype.toString = function () { - return this.signatures.toString(); - }; - SignatureGroup.prototype.toStrings = function (prefix, shortform, scope) { - var result = []; - var len = this.signatures.length; - if(len > 1) { - shortform = false; - } - for(var i = 0; i < len; i++) { - if(len > 1 && this.signatures[i] == this.definitionSignature) { - continue; - } - if(this.flags & TypeScript.SignatureFlags.IsIndexer) { - result.push(this.signatures[i].toStringHelperEx(shortform, true, scope)); - } else { - result.push(this.signatures[i].toStringHelperEx(shortform, false, scope, prefix)); - } - } - return result; - }; - SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { - var result = new SignatureGroup(); - if(this.signatures) { - for(var i = 0, len = this.signatures.length; i < len; i++) { - result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); - } - } - return result; - }; - SignatureGroup.prototype.verifySignatures = function (checker) { - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - for(var j = i + 1; j < len; j++) { - if(this.signatures[i].declAST && this.signatures[j].declAST && (!TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Definition) && !TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Definition)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); - } - } - if(this.definitionSignature) { - if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); - } - } - } - } - }; - SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { - if(this.hasBeenTypechecked) { - return; - } - this.hasBeenTypechecked = true; - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); - } - if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); - } - checker.typeFlow.typeCheck(this.signatures[i].declAST); - } - this.verifySignatures(checker); - } - }; - return SignatureGroup; - })(); - TypeScript.SignatureGroup = SignatureGroup; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeCheckStatus) { - TypeCheckStatus._map = []; - TypeCheckStatus._map[0] = "NotStarted"; - TypeCheckStatus.NotStarted = 0; - TypeCheckStatus._map[1] = "Started"; - TypeCheckStatus.Started = 1; - TypeCheckStatus._map[2] = "Finished"; - TypeCheckStatus.Finished = 2; - })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); - var TypeCheckStatus = TypeScript.TypeCheckStatus; - function aLexicallyEnclosesB(a, b) { - if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; - } else { - return false; - } - } - TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; - function aEnclosesB(a, b) { - while(a.container) { - if(a == b || aLexicallyEnclosesB(a.container, b)) { - return true; - } - a = a.container; - } - return false; - } - TypeScript.aEnclosesB = aEnclosesB; - var Symbol = (function () { - function Symbol(name, location, length, unitIndex) { - this.name = name; - this.location = location; - this.length = length; - this.unitIndex = unitIndex; - this.bound = false; - this.flags = TypeScript.SymbolFlags.None; - this.isObjectLitField = false; - this.declAST = null; - this.declModule = null; - this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; - } - Symbol.prototype.instanceScope = function () { - return null; - }; - Symbol.prototype.isVariable = function () { - return false; - }; - Symbol.prototype.isMember = function () { - return false; - }; - Symbol.prototype.isInferenceSymbol = function () { - return false; - }; - Symbol.prototype.isWith = function () { - return false; - }; - Symbol.prototype.writeable = function () { - return false; - }; - Symbol.prototype.isType = function () { - return false; - }; - Symbol.prototype.getType = function () { - return null; - }; - Symbol.prototype.isAccessor = function () { - return false; - }; - Symbol.prototype.isInstanceProperty = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); - }; - Symbol.prototype.getTypeName = function (scope) { - return this.getTypeNameEx(scope).toString(); - }; - Symbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.toString()); - }; - Symbol.prototype.getOptionalNameString = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; - }; - Symbol.prototype.pathToRoot = function () { - var path = new Array(); - var node = this; - while(node && (node.name != TypeScript.globalId)) { - path[path.length] = node; - node = node.container; - } - return path; - }; - Symbol.prototype.findCommonAncestorPath = function (b) { - if(this.container == null) { - return new Array(); - } - var aPath = this.container.pathToRoot(); - var bPath; - if(b) { - bPath = b.pathToRoot(); - } else { - bPath = new Array(); - } - var commonNodeIndex = -1; - for(var i = 0, aLen = aPath.length; i < aLen; i++) { - var aNode = aPath[i]; - for(var j = 0, bLen = bPath.length; j < bLen; j++) { - var bNode = bPath[j]; - if(aNode == bNode) { - commonNodeIndex = i; - break; - } - } - if(commonNodeIndex >= 0) { - break; - } - } - if(commonNodeIndex >= 0) { - return aPath.slice(0, commonNodeIndex); - } else { - return aPath; - } - }; - Symbol.prototype.getPrettyName = function (scopeSymbol) { - return this.name; - }; - Symbol.prototype.scopeRelativeName = function (scope) { - if(scope == null) { - return this.getPrettyName(null) + this.getOptionalNameString(); - } - var lca = this.findCommonAncestorPath(scope.container); - var builder = ""; - for(var i = 0, len = lca.length; i < len; i++) { - var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); - builder = prettyName + "." + builder; - } - builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); - return builder; - }; - Symbol.prototype.fullName = function () { - var builder = this.name; - var ancestor = this.container; - while(ancestor && (ancestor.name != TypeScript.globalId)) { - builder = ancestor.name + "." + builder; - ancestor = ancestor.container; - } - return builder; - }; - Symbol.prototype.isExternallyVisible = function (checker) { - if(this == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return false; - } - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - return this.container == checker.gloMod; - } - return this.container.isExternallyVisible(checker); - }; - Symbol.prototype.visible = function (scope, checker) { - if(checker == null || this.container == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return true; - } else { - return aEnclosesB(this, scope.container); - } - } else { - return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); - } - } else { - var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - var isMethod = isFunction && (this.declAST).isMethod(); - var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); - var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); - var isAlias = this.isType() && (this).aliasLink; - if(this.isMember() || isMethod || isStaticFunction || isAlias) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { - if(scope.container == null && this.container != scope.container) { - return false; - } else { - return this.container == null ? true : aEnclosesB(scope.container, this.container); - } - } else { - return true; - } - } else { - if(this.container) { - return aEnclosesB(this, scope.container); - } else { - return true; - } - } - } - }; - Symbol.prototype.addRef = function (identifier) { - if(!this.refs) { - this.refs = []; - } - this.refs[this.refs.length] = identifier; - }; - Symbol.prototype.toString = function () { - if(this.name) { - return this.name; - } else { - return "_anonymous"; - } - }; - Symbol.prototype.print = function (outfile) { - outfile.Write(this.toString()); - }; - Symbol.prototype.specializeType = function (pattern, replacement, checker) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.setType = function (type) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.kind = function () { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { - if(this.declAST != null) { - if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.declAST; - } else { - if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.container.declAST; - } - } - } - return null; - }; - Symbol.prototype.getVarDeclFromSymbol = function () { - if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { - return this.declAST; - } - return null; - }; - Symbol.prototype.getDocComments = function () { - if(this.declAST != null) { - return this.declAST.getDocComments(); - } - return []; - }; - Symbol.prototype.isStatic = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); - }; - return Symbol; - })(); - TypeScript.Symbol = Symbol; - var ValueLocation = (function () { - function ValueLocation() { } - return ValueLocation; - })(); - TypeScript.ValueLocation = ValueLocation; - var InferenceSymbol = (function (_super) { - __extends(InferenceSymbol, _super); - function InferenceSymbol(name, location, length, unitIndex) { - _super.call(this, name, location, length, unitIndex); - this.typeCheckStatus = TypeCheckStatus.NotStarted; - } - InferenceSymbol.prototype.isInferenceSymbol = function () { - return true; - }; - InferenceSymbol.prototype.transferVarFlags = function (varFlags) { - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { - this.flags |= TypeScript.SymbolFlags.Ambient; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { - this.flags |= TypeScript.SymbolFlags.Constant; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { - this.flags |= TypeScript.SymbolFlags.Static; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { - this.flags |= TypeScript.SymbolFlags.Property; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { - this.flags |= TypeScript.SymbolFlags.Private; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { - this.flags |= TypeScript.SymbolFlags.Public; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { - this.flags |= TypeScript.SymbolFlags.Readonly; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { - this.flags |= TypeScript.SymbolFlags.Exported; - } - }; - return InferenceSymbol; - })(Symbol); - TypeScript.InferenceSymbol = InferenceSymbol; - var TypeSymbol = (function (_super) { - __extends(TypeSymbol, _super); - function TypeSymbol(locName, location, length, unitIndex, type) { - _super.call(this, locName, location, length, unitIndex); - this.type = type; - this.expansions = []; - this.expansionsDeclAST = []; - this.isDynamic = false; - this.isMethod = false; - this.aliasLink = null; - this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; - this.prettyName = this.name; - } - TypeSymbol.prototype.addLocation = function (loc) { - if(this.additionalLocations == null) { - this.additionalLocations = []; - } - this.additionalLocations[this.additionalLocations.length] = loc; - }; - TypeSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Type; - }; - TypeSymbol.prototype.isType = function () { - return true; - }; - TypeSymbol.prototype.getType = function () { - return this.type; - }; - TypeSymbol.prototype.getTypeNameEx = function (scope) { - return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); - }; - TypeSymbol.prototype.instanceScope = function () { - if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { - return this.type.instanceType.constructorScope; - } else { - return this.type.containedScope; - } - }; - TypeSymbol.prototype.toString = function () { - var result = this.type.getTypeName(); - if(this.name) { - result = this.name + ":" + result; - } - return result; - }; - TypeSymbol.prototype.isClass = function () { - return this.instanceType != null; - }; - TypeSymbol.prototype.isFunction = function () { - return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - }; - TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { - if(this.type == pattern) { - return replacement.symbol; - } else { - var replType = this.type.specializeType(pattern, replacement, checker, false); - if(replType != this.type) { - var result = new TypeSymbol(this.name, -1, 0, -1, replType); - return result; - } else { - return this; - } - } - }; - TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { - if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { - var symbolPath = scopeSymbol.pathToRoot(); - var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); - if(prettyName != null) { - return prettyName.name; - } - } - return this.prettyName; - }; - TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { - var scopeSymbolPathLength = scopeSymbolPath.length; - var externalSymbol = null; - if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { - if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - if(externalSymbol == null) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - } - return externalSymbol; - }; - TypeSymbol.prototype.getDocComments = function () { - var comments = []; - if(this.declAST != null) { - comments = comments.concat(this.declAST.getDocComments()); - } - for(var i = 0; i < this.expansionsDeclAST.length; i++) { - comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); - } - return comments; - }; - return TypeSymbol; - })(InferenceSymbol); - TypeScript.TypeSymbol = TypeSymbol; - var WithSymbol = (function (_super) { - __extends(WithSymbol, _super); - function WithSymbol(location, unitIndex, withType) { - _super.call(this, "with", location, 4, unitIndex, withType); - } - WithSymbol.prototype.isWith = function () { - return true; - }; - return WithSymbol; - })(TypeSymbol); - TypeScript.WithSymbol = WithSymbol; - var FieldSymbol = (function (_super) { - __extends(FieldSymbol, _super); - function FieldSymbol(name, location, unitIndex, canWrite, field) { - _super.call(this, name, location, name.length, unitIndex); - this.canWrite = canWrite; - this.field = field; - this.getter = null; - this.setter = null; - this.hasBeenEmitted = false; - this.name = name; - this.location = location; - } - FieldSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Field; - }; - FieldSymbol.prototype.writeable = function () { - return this.isAccessor() ? this.setter != null : this.canWrite; - }; - FieldSymbol.prototype.getType = function () { - return this.field.typeLink.type; - }; - FieldSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.field.typeLink.type.getScopedTypeNameEx(scope), this.name + this.getOptionalNameString() + ": ", ""); - }; - FieldSymbol.prototype.isMember = function () { - return true; - }; - FieldSymbol.prototype.setType = function (type) { - this.field.typeLink.type = type; - }; - FieldSymbol.prototype.isAccessor = function () { - return this.getter != null || this.setter != null; - }; - FieldSymbol.prototype.isVariable = function () { - return true; - }; - FieldSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); - if(rType != this.field.typeLink.type) { - var fieldDef = new ValueLocation(); - var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); - result.flags = this.flags; - fieldDef.symbol = result; - fieldDef.typeLink = new TypeScript.TypeLink(); - result.setType(rType); - result.typeCheckStatus = TypeCheckStatus.Finished; - return result; - } else { - return this; - } - }; - FieldSymbol.prototype.getDocComments = function () { - if(this.getter != null || this.setter != null) { - var comments = []; - if(this.getter != null) { - comments = comments.concat(this.getter.getDocComments()); - } - if(this.setter != null) { - comments = comments.concat(this.setter.getDocComments()); - } - return comments; - } else { - if(this.declAST != null) { - return this.declAST.getDocComments(); - } - } - return []; - }; - return FieldSymbol; - })(InferenceSymbol); - TypeScript.FieldSymbol = FieldSymbol; - var ParameterSymbol = (function (_super) { - __extends(ParameterSymbol, _super); - function ParameterSymbol(name, location, unitIndex, parameter) { - _super.call(this, name, location, name.length, unitIndex); - this.parameter = parameter; - this.paramDocComment = null; - this.funcDecl = null; - this.argsOffset = (-1); - this.name = name; - this.location = location; - } - ParameterSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Parameter; - }; - ParameterSymbol.prototype.writeable = function () { - return true; - }; - ParameterSymbol.prototype.getType = function () { - return this.parameter.typeLink.type; - }; - ParameterSymbol.prototype.setType = function (type) { - this.parameter.typeLink.type = type; - }; - ParameterSymbol.prototype.isVariable = function () { - return true; - }; - ParameterSymbol.prototype.isOptional = function () { - if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { - return (this.parameter.symbol.declAST).isOptional; - } else { - return false; - } - }; - ParameterSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); - }; - ParameterSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); - if(this.parameter.typeLink.type != rType) { - var paramDef = new ValueLocation(); - var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); - paramDef.symbol = result; - result.setType(rType); - return result; - } else { - return this; - } - }; - ParameterSymbol.prototype.getParameterDocComments = function () { - if(!this.paramDocComment) { - var parameterComments = []; - if(this.funcDecl) { - var fncDocComments = this.funcDecl.getDocComments(); - var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); - if(paramComment != "") { - parameterComments.push(paramComment); - } - } - var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); - if(docComments != "") { - parameterComments.push(docComments); - } - this.paramDocComment = parameterComments.join("\n"); - } - return this.paramDocComment; - }; - return ParameterSymbol; - })(InferenceSymbol); - TypeScript.ParameterSymbol = ParameterSymbol; - var VariableSymbol = (function (_super) { - __extends(VariableSymbol, _super); - function VariableSymbol(name, location, unitIndex, variable) { - _super.call(this, name, location, name.length, unitIndex); - this.variable = variable; - } - VariableSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Variable; - }; - VariableSymbol.prototype.writeable = function () { - return true; - }; - VariableSymbol.prototype.getType = function () { - return this.variable.typeLink.type; - }; - VariableSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); - }; - VariableSymbol.prototype.setType = function (type) { - this.variable.typeLink.type = type; - }; - VariableSymbol.prototype.isVariable = function () { - return true; - }; - return VariableSymbol; - })(InferenceSymbol); - TypeScript.VariableSymbol = VariableSymbol; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopedMembers = (function () { - function ScopedMembers(dualMembers) { - this.dualMembers = dualMembers; - this.allMembers = this.dualMembers; - this.publicMembers = this.dualMembers.primaryTable; - this.privateMembers = this.dualMembers.secondaryTable; - } - ScopedMembers.prototype.addPublicMember = function (key, data) { - return this.dualMembers.primaryTable.add(key, data); - }; - ScopedMembers.prototype.addPrivateMember = function (key, data) { - return this.dualMembers.secondaryTable.add(key, data); - }; - return ScopedMembers; - })(); - TypeScript.ScopedMembers = ScopedMembers; - (function (SymbolKind) { - SymbolKind._map = []; - SymbolKind._map[0] = "None"; - SymbolKind.None = 0; - SymbolKind._map[1] = "Type"; - SymbolKind.Type = 1; - SymbolKind._map[2] = "Field"; - SymbolKind.Field = 2; - SymbolKind._map[3] = "Parameter"; - SymbolKind.Parameter = 3; - SymbolKind._map[4] = "Variable"; - SymbolKind.Variable = 4; - })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); - var SymbolKind = TypeScript.SymbolKind; - var SymbolScope = (function () { - function SymbolScope(container) { - this.container = container; - } - SymbolScope.prototype.printLabel = function () { - return "base"; - }; - SymbolScope.prototype.getAllSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllTypeSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllValueSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.find = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.print = function (outfile) { - if(this.container) { - outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); - } else { - outfile.WriteLine(this.printLabel() + " scope..."); - } - }; - SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { - throw new Error("please implement in derived class"); - }; - SymbolScope.prototype.getTable = function () { - throw new Error("please implement in derived class"); - }; - return SymbolScope; - })(); - TypeScript.SymbolScope = SymbolScope; - function symbolCanBeUsed(sym, publicOnly) { - return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; - } - var SymbolAggregateScope = (function (_super) { - __extends(SymbolAggregateScope, _super); - function SymbolAggregateScope(container) { - _super.call(this, container); - this.valueCache = null; - this.valueImplCache = null; - this.valueAmbientCache = null; - this.typeCache = null; - this.typeImplCache = null; - this.typeAmbientCache = null; - this.parents = null; - this.container = container; - } - SymbolAggregateScope.prototype.printLabel = function () { - return "agg"; - }; - SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var sym = this.parents[i].search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - } - return filter.result; - }; - SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - this.parents[i].print(outfile); - } - } - }; - SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var implCache = this.valueImplCache; - if(typespace) { - implCache = this.typeImplCache; - } - if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findImplementation(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(implCache) { - if(typespace) { - this.typeImplCache = new TypeScript.StringHashTable(); - implCache = this.typeImplCache; - } else { - this.valueImplCache = new TypeScript.StringHashTable(); - implCache = this.valueImplCache; - } - } - implCache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueCache; - if(typespace) { - cache = this.typeCache; - } - if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].find(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeCache = new TypeScript.StringHashTable(); - cache = this.typeCache; - } else { - this.valueCache = new TypeScript.StringHashTable(); - cache = this.valueCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueAmbientCache; - if(typespace) { - cache = this.typeAmbientCache; - } - if(cache && ((sym = cache.lookup(name)) != null)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findAmbient(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeAmbientCache = new TypeScript.StringHashTable(); - cache = this.typeAmbientCache; - } else { - this.valueAmbientCache = new TypeScript.StringHashTable(); - cache = this.valueAmbientCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.addParentScope = function (parent) { - if(this.parents == null) { - this.parents = new Array(); - } - this.parents[this.parents.length] = parent; - }; - return SymbolAggregateScope; - })(SymbolScope); - TypeScript.SymbolAggregateScope = SymbolAggregateScope; - var SymbolTableScope = (function (_super) { - __extends(SymbolTableScope, _super); - function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.container = container; - } - SymbolTableScope.prototype.printLabel = function () { - return "table"; - }; - SymbolTableScope.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - filter.update(sym); - return filter.result; - }; - SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { - var table = null; - var ambientTable = null; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } else { - table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - if(table) { - var s = table.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - }; - SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - if(sym) { - if(sym.kind() == SymbolKind.Type) { - var typeSym = sym; - if(!typeSym.type.hasImplementation()) { - sym = null; - } - } else { - if(sym.container) { - if(sym.container.kind() == SymbolKind.Type) { - var ctypeSym = sym.container; - if(!ctypeSym.type.hasImplementation()) { - sym = null; - } - } - } - } - } - return sym; - }; - SymbolTableScope.prototype.getTable = function () { - return this.valueMembers.publicMembers; - }; - return SymbolTableScope; - })(SymbolScope); - TypeScript.SymbolTableScope = SymbolTableScope; - var SymbolScopeBuilder = (function (_super) { - __extends(SymbolScopeBuilder, _super); - function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.parent = parent; - this.container = container; - } - SymbolScopeBuilder.prototype.printLabel = function () { - return "builder"; - }; - SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(this.parent) { - sym = this.parent.search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - return filter.result; - }; - SymbolScopeBuilder.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.parent) { - this.parent.print(outfile); - } - }; - SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(table && ((sym = table.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.find(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.findAmbient(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - return null; - }; - SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { - var table = null; - if(ambient) { - if(typespace) { - table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; - } else { - table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; - } - } else { - if(typespace) { - table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; - } else { - table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; - } - } - if(table) { - if(!table.add(symbol.name, symbol)) { - errorReporter.duplicateIdentifier(ast, symbol.name); - } - } else { - TypeScript.CompilerDiagnostics.Alert("YYYYY"); - } - symbol.container = container; - }; - SymbolScopeBuilder.prototype.getTable = function () { - return this.valueMembers.allMembers; - }; - return SymbolScopeBuilder; - })(SymbolScope); - TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; - var FilteredSymbolScope = (function (_super) { - __extends(FilteredSymbolScope, _super); - function FilteredSymbolScope(scope, container, filter) { - _super.call(this, container); - this.scope = scope; - this.filter = filter; - } - FilteredSymbolScope.prototype.print = function (outfile) { - this.scope.print(outfile); - }; - FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { - this.filter.reset(); - return this.scope.search(this.filter, name, publicOnly, typespace); - }; - FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return this.scope.findLocal(name, publicOnly, typespace); - }; - return FilteredSymbolScope; - })(SymbolScope); - TypeScript.FilteredSymbolScope = FilteredSymbolScope; - var FilteredSymbolScopeBuilder = (function (_super) { - __extends(FilteredSymbolScopeBuilder, _super); - function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { - _super.call(this, valueMembers, null, null, null, parent, container); - this.filter = filter; - } - FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return sym; - }; - FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - throw new Error("please implement"); - }; - FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return _super.prototype.find.call(this, name, publicOnly, typespace); - }; - return FilteredSymbolScopeBuilder; - })(SymbolScopeBuilder); - TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TokenID) { - TokenID._map = []; - TokenID._map[0] = "Any"; - TokenID.Any = 0; - TokenID._map[1] = "Bool"; - TokenID.Bool = 1; - TokenID._map[2] = "Break"; - TokenID.Break = 2; - TokenID._map[3] = "Case"; - TokenID.Case = 3; - TokenID._map[4] = "Catch"; - TokenID.Catch = 4; - TokenID._map[5] = "Class"; - TokenID.Class = 5; - TokenID._map[6] = "Const"; - TokenID.Const = 6; - TokenID._map[7] = "Continue"; - TokenID.Continue = 7; - TokenID._map[8] = "Debugger"; - TokenID.Debugger = 8; - TokenID._map[9] = "Default"; - TokenID.Default = 9; - TokenID._map[10] = "Delete"; - TokenID.Delete = 10; - TokenID._map[11] = "Do"; - TokenID.Do = 11; - TokenID._map[12] = "Else"; - TokenID.Else = 12; - TokenID._map[13] = "Enum"; - TokenID.Enum = 13; - TokenID._map[14] = "Export"; - TokenID.Export = 14; - TokenID._map[15] = "Extends"; - TokenID.Extends = 15; - TokenID._map[16] = "Declare"; - TokenID.Declare = 16; - TokenID._map[17] = "False"; - TokenID.False = 17; - TokenID._map[18] = "Finally"; - TokenID.Finally = 18; - TokenID._map[19] = "For"; - TokenID.For = 19; - TokenID._map[20] = "Function"; - TokenID.Function = 20; - TokenID._map[21] = "Constructor"; - TokenID.Constructor = 21; - TokenID._map[22] = "Get"; - TokenID.Get = 22; - TokenID._map[23] = "If"; - TokenID.If = 23; - TokenID._map[24] = "Implements"; - TokenID.Implements = 24; - TokenID._map[25] = "Import"; - TokenID.Import = 25; - TokenID._map[26] = "In"; - TokenID.In = 26; - TokenID._map[27] = "InstanceOf"; - TokenID.InstanceOf = 27; - TokenID._map[28] = "Interface"; - TokenID.Interface = 28; - TokenID._map[29] = "Let"; - TokenID.Let = 29; - TokenID._map[30] = "Module"; - TokenID.Module = 30; - TokenID._map[31] = "New"; - TokenID.New = 31; - TokenID._map[32] = "Number"; - TokenID.Number = 32; - TokenID._map[33] = "Null"; - TokenID.Null = 33; - TokenID._map[34] = "Package"; - TokenID.Package = 34; - TokenID._map[35] = "Private"; - TokenID.Private = 35; - TokenID._map[36] = "Protected"; - TokenID.Protected = 36; - TokenID._map[37] = "Public"; - TokenID.Public = 37; - TokenID._map[38] = "Return"; - TokenID.Return = 38; - TokenID._map[39] = "Set"; - TokenID.Set = 39; - TokenID._map[40] = "Static"; - TokenID.Static = 40; - TokenID._map[41] = "String"; - TokenID.String = 41; - TokenID._map[42] = "Super"; - TokenID.Super = 42; - TokenID._map[43] = "Switch"; - TokenID.Switch = 43; - TokenID._map[44] = "This"; - TokenID.This = 44; - TokenID._map[45] = "Throw"; - TokenID.Throw = 45; - TokenID._map[46] = "True"; - TokenID.True = 46; - TokenID._map[47] = "Try"; - TokenID.Try = 47; - TokenID._map[48] = "TypeOf"; - TokenID.TypeOf = 48; - TokenID._map[49] = "Var"; - TokenID.Var = 49; - TokenID._map[50] = "Void"; - TokenID.Void = 50; - TokenID._map[51] = "With"; - TokenID.With = 51; - TokenID._map[52] = "While"; - TokenID.While = 52; - TokenID._map[53] = "Yield"; - TokenID.Yield = 53; - TokenID._map[54] = "Semicolon"; - TokenID.Semicolon = 54; - TokenID._map[55] = "OpenParen"; - TokenID.OpenParen = 55; - TokenID._map[56] = "CloseParen"; - TokenID.CloseParen = 56; - TokenID._map[57] = "OpenBracket"; - TokenID.OpenBracket = 57; - TokenID._map[58] = "CloseBracket"; - TokenID.CloseBracket = 58; - TokenID._map[59] = "OpenBrace"; - TokenID.OpenBrace = 59; - TokenID._map[60] = "CloseBrace"; - TokenID.CloseBrace = 60; - TokenID._map[61] = "Comma"; - TokenID.Comma = 61; - TokenID._map[62] = "Equals"; - TokenID.Equals = 62; - TokenID._map[63] = "PlusEquals"; - TokenID.PlusEquals = 63; - TokenID._map[64] = "MinusEquals"; - TokenID.MinusEquals = 64; - TokenID._map[65] = "AsteriskEquals"; - TokenID.AsteriskEquals = 65; - TokenID._map[66] = "SlashEquals"; - TokenID.SlashEquals = 66; - TokenID._map[67] = "PercentEquals"; - TokenID.PercentEquals = 67; - TokenID._map[68] = "AmpersandEquals"; - TokenID.AmpersandEquals = 68; - TokenID._map[69] = "CaretEquals"; - TokenID.CaretEquals = 69; - TokenID._map[70] = "BarEquals"; - TokenID.BarEquals = 70; - TokenID._map[71] = "LessThanLessThanEquals"; - TokenID.LessThanLessThanEquals = 71; - TokenID._map[72] = "GreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanEquals = 72; - TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; - TokenID._map[74] = "Question"; - TokenID.Question = 74; - TokenID._map[75] = "Colon"; - TokenID.Colon = 75; - TokenID._map[76] = "BarBar"; - TokenID.BarBar = 76; - TokenID._map[77] = "AmpersandAmpersand"; - TokenID.AmpersandAmpersand = 77; - TokenID._map[78] = "Bar"; - TokenID.Bar = 78; - TokenID._map[79] = "Caret"; - TokenID.Caret = 79; - TokenID._map[80] = "And"; - TokenID.And = 80; - TokenID._map[81] = "EqualsEquals"; - TokenID.EqualsEquals = 81; - TokenID._map[82] = "ExclamationEquals"; - TokenID.ExclamationEquals = 82; - TokenID._map[83] = "EqualsEqualsEquals"; - TokenID.EqualsEqualsEquals = 83; - TokenID._map[84] = "ExclamationEqualsEquals"; - TokenID.ExclamationEqualsEquals = 84; - TokenID._map[85] = "LessThan"; - TokenID.LessThan = 85; - TokenID._map[86] = "LessThanEquals"; - TokenID.LessThanEquals = 86; - TokenID._map[87] = "GreaterThan"; - TokenID.GreaterThan = 87; - TokenID._map[88] = "GreaterThanEquals"; - TokenID.GreaterThanEquals = 88; - TokenID._map[89] = "LessThanLessThan"; - TokenID.LessThanLessThan = 89; - TokenID._map[90] = "GreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThan = 90; - TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThanGreaterThan = 91; - TokenID._map[92] = "Plus"; - TokenID.Plus = 92; - TokenID._map[93] = "Minus"; - TokenID.Minus = 93; - TokenID._map[94] = "Asterisk"; - TokenID.Asterisk = 94; - TokenID._map[95] = "Slash"; - TokenID.Slash = 95; - TokenID._map[96] = "Percent"; - TokenID.Percent = 96; - TokenID._map[97] = "Tilde"; - TokenID.Tilde = 97; - TokenID._map[98] = "Exclamation"; - TokenID.Exclamation = 98; - TokenID._map[99] = "PlusPlus"; - TokenID.PlusPlus = 99; - TokenID._map[100] = "MinusMinus"; - TokenID.MinusMinus = 100; - TokenID._map[101] = "Dot"; - TokenID.Dot = 101; - TokenID._map[102] = "DotDotDot"; - TokenID.DotDotDot = 102; - TokenID._map[103] = "Error"; - TokenID.Error = 103; - TokenID._map[104] = "EndOfFile"; - TokenID.EndOfFile = 104; - TokenID._map[105] = "EqualsGreaterThan"; - TokenID.EqualsGreaterThan = 105; - TokenID._map[106] = "Identifier"; - TokenID.Identifier = 106; - TokenID._map[107] = "StringLiteral"; - TokenID.StringLiteral = 107; - TokenID._map[108] = "RegularExpressionLiteral"; - TokenID.RegularExpressionLiteral = 108; - TokenID._map[109] = "NumberLiteral"; - TokenID.NumberLiteral = 109; - TokenID._map[110] = "Whitespace"; - TokenID.Whitespace = 110; - TokenID._map[111] = "Comment"; - TokenID.Comment = 111; - TokenID._map[112] = "Lim"; - TokenID.Lim = 112; - TokenID.LimFixed = TokenID.EqualsGreaterThan; - TokenID.LimKeyword = TokenID.Yield; - })(TypeScript.TokenID || (TypeScript.TokenID = {})); - var TokenID = TypeScript.TokenID; - TypeScript.tokenTable = new Array(); - TypeScript.nodeTypeTable = new Array(); - TypeScript.nodeTypeToTokTable = new Array(); - TypeScript.noRegexTable = new Array(); - TypeScript.noRegexTable[TokenID.Identifier] = true; - TypeScript.noRegexTable[TokenID.StringLiteral] = true; - TypeScript.noRegexTable[TokenID.NumberLiteral] = true; - TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; - TypeScript.noRegexTable[TokenID.This] = true; - TypeScript.noRegexTable[TokenID.PlusPlus] = true; - TypeScript.noRegexTable[TokenID.MinusMinus] = true; - TypeScript.noRegexTable[TokenID.CloseParen] = true; - TypeScript.noRegexTable[TokenID.CloseBracket] = true; - TypeScript.noRegexTable[TokenID.CloseBrace] = true; - TypeScript.noRegexTable[TokenID.True] = true; - TypeScript.noRegexTable[TokenID.False] = true; - (function (OperatorPrecedence) { - OperatorPrecedence._map = []; - OperatorPrecedence._map[0] = "None"; - OperatorPrecedence.None = 0; - OperatorPrecedence._map[1] = "Comma"; - OperatorPrecedence.Comma = 1; - OperatorPrecedence._map[2] = "Assignment"; - OperatorPrecedence.Assignment = 2; - OperatorPrecedence._map[3] = "Conditional"; - OperatorPrecedence.Conditional = 3; - OperatorPrecedence._map[4] = "LogicalOr"; - OperatorPrecedence.LogicalOr = 4; - OperatorPrecedence._map[5] = "LogicalAnd"; - OperatorPrecedence.LogicalAnd = 5; - OperatorPrecedence._map[6] = "BitwiseOr"; - OperatorPrecedence.BitwiseOr = 6; - OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; - OperatorPrecedence.BitwiseExclusiveOr = 7; - OperatorPrecedence._map[8] = "BitwiseAnd"; - OperatorPrecedence.BitwiseAnd = 8; - OperatorPrecedence._map[9] = "Equality"; - OperatorPrecedence.Equality = 9; - OperatorPrecedence._map[10] = "Relational"; - OperatorPrecedence.Relational = 10; - OperatorPrecedence._map[11] = "Shift"; - OperatorPrecedence.Shift = 11; - OperatorPrecedence._map[12] = "Additive"; - OperatorPrecedence.Additive = 12; - OperatorPrecedence._map[13] = "Multiplicative"; - OperatorPrecedence.Multiplicative = 13; - OperatorPrecedence._map[14] = "Unary"; - OperatorPrecedence.Unary = 14; - OperatorPrecedence._map[15] = "Lim"; - OperatorPrecedence.Lim = 15; - })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); - var OperatorPrecedence = TypeScript.OperatorPrecedence; - (function (Reservation) { - Reservation._map = []; - Reservation.None = 0; - Reservation.Javascript = 1; - Reservation.JavascriptFuture = 2; - Reservation.TypeScript = 4; - Reservation.JavascriptFutureStrict = 8; - Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; - Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; - Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; - })(TypeScript.Reservation || (TypeScript.Reservation = {})); - var Reservation = TypeScript.Reservation; - var TokenInfo = (function () { - function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - this.tokenId = tokenId; - this.reservation = reservation; - this.binopPrecedence = binopPrecedence; - this.binopNodeType = binopNodeType; - this.unopPrecedence = unopPrecedence; - this.unopNodeType = unopNodeType; - this.text = text; - this.ers = ers; - } - return TokenInfo; - })(); - TypeScript.TokenInfo = TokenInfo; - function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - if(tokenId !== undefined) { - TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); - if(binopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[binopNodeType] = text; - TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; - } - if(unopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[unopNodeType] = text; - } - } - } - setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); - setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); - setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); - setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); - setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); - setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); - setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); - setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); - setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); - setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); - setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); - setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); - setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); - setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); - setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); - setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); - setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); - function lookupToken(tokenId) { - return TypeScript.tokenTable[tokenId]; - } - TypeScript.lookupToken = lookupToken; - (function (TokenClass) { - TokenClass._map = []; - TokenClass._map[0] = "Punctuation"; - TokenClass.Punctuation = 0; - TokenClass._map[1] = "Keyword"; - TokenClass.Keyword = 1; - TokenClass._map[2] = "Operator"; - TokenClass.Operator = 2; - TokenClass._map[3] = "Comment"; - TokenClass.Comment = 3; - TokenClass._map[4] = "Whitespace"; - TokenClass.Whitespace = 4; - TokenClass._map[5] = "Identifier"; - TokenClass.Identifier = 5; - TokenClass._map[6] = "NumberLiteral"; - TokenClass.NumberLiteral = 6; - TokenClass._map[7] = "StringLiteral"; - TokenClass.StringLiteral = 7; - TokenClass._map[8] = "RegExpLiteral"; - TokenClass.RegExpLiteral = 8; - })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); - var TokenClass = TypeScript.TokenClass; - var SavedToken = (function () { - function SavedToken(tok, minChar, limChar) { - this.tok = tok; - this.minChar = minChar; - this.limChar = limChar; - } - return SavedToken; - })(); - TypeScript.SavedToken = SavedToken; - var Token = (function () { - function Token(tokenId) { - this.tokenId = tokenId; - } - Token.prototype.toString = function () { - return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; - }; - Token.prototype.print = function (line, outfile) { - outfile.WriteLine(this.toString() + ",on line" + line); - }; - Token.prototype.getText = function () { - return TypeScript.tokenTable[this.tokenId].text; - }; - Token.prototype.classification = function () { - if(this.tokenId <= TokenID.LimKeyword) { - return TokenClass.Keyword; - } else { - var tokenInfo = lookupToken(this.tokenId); - if(tokenInfo != undefined) { - if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { - return TokenClass.Operator; - } - } - } - return TokenClass.Punctuation; - }; - return Token; - })(); - TypeScript.Token = Token; - var NumberLiteralToken = (function (_super) { - __extends(NumberLiteralToken, _super); - function NumberLiteralToken(value, hasEmptyFraction) { - _super.call(this, TokenID.NumberLiteral); - this.value = value; - this.hasEmptyFraction = hasEmptyFraction; - } - NumberLiteralToken.prototype.getText = function () { - return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); - }; - NumberLiteralToken.prototype.classification = function () { - return TokenClass.NumberLiteral; - }; - return NumberLiteralToken; - })(Token); - TypeScript.NumberLiteralToken = NumberLiteralToken; - var StringLiteralToken = (function (_super) { - __extends(StringLiteralToken, _super); - function StringLiteralToken(value) { - _super.call(this, TokenID.StringLiteral); - this.value = value; - } - StringLiteralToken.prototype.getText = function () { - return this.value; - }; - StringLiteralToken.prototype.classification = function () { - return TokenClass.StringLiteral; - }; - return StringLiteralToken; - })(Token); - TypeScript.StringLiteralToken = StringLiteralToken; - var IdentifierToken = (function (_super) { - __extends(IdentifierToken, _super); - function IdentifierToken(value, hasEscapeSequence) { - _super.call(this, TokenID.Identifier); - this.value = value; - this.hasEscapeSequence = hasEscapeSequence; - } - IdentifierToken.prototype.getText = function () { - return this.value; - }; - IdentifierToken.prototype.classification = function () { - return TokenClass.Identifier; - }; - return IdentifierToken; - })(Token); - TypeScript.IdentifierToken = IdentifierToken; - var WhitespaceToken = (function (_super) { - __extends(WhitespaceToken, _super); - function WhitespaceToken(tokenId, value) { - _super.call(this, tokenId); - this.value = value; - } - WhitespaceToken.prototype.getText = function () { - return this.value; - }; - WhitespaceToken.prototype.classification = function () { - return TokenClass.Whitespace; - }; - return WhitespaceToken; - })(Token); - TypeScript.WhitespaceToken = WhitespaceToken; - var CommentToken = (function (_super) { - __extends(CommentToken, _super); - function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { - _super.call(this, tokenID); - this.value = value; - this.isBlock = isBlock; - this.startPos = startPos; - this.line = line; - this.endsLine = endsLine; - } - CommentToken.prototype.getText = function () { - return this.value; - }; - CommentToken.prototype.classification = function () { - return TokenClass.Comment; - }; - return CommentToken; - })(Token); - TypeScript.CommentToken = CommentToken; - var RegularExpressionLiteralToken = (function (_super) { - __extends(RegularExpressionLiteralToken, _super); - function RegularExpressionLiteralToken(regex) { - _super.call(this, TokenID.RegularExpressionLiteral); - this.regex = regex; - } - RegularExpressionLiteralToken.prototype.getText = function () { - return this.regex.toString(); - }; - RegularExpressionLiteralToken.prototype.classification = function () { - return TokenClass.RegExpLiteral; - }; - return RegularExpressionLiteralToken; - })(Token); - TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; - TypeScript.staticTokens = new Array(); - function initializeStaticTokens() { - for(var i = 0; i <= TokenID.LimFixed; i++) { - TypeScript.staticTokens[i] = new Token(i); - } - } - TypeScript.initializeStaticTokens = initializeStaticTokens; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ArrayCache = (function () { - function ArrayCache() { - this.arrayBase = null; - } - ArrayCache.prototype.specialize = function (arrInstType, checker) { - if(this.arrayBase == null) { - this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); - } - return this.arrayBase; - }; - return ArrayCache; - })(); - TypeScript.ArrayCache = ArrayCache; - var TypeComparisonInfo = (function () { - function TypeComparisonInfo() { - this.onlyCaptureFirstError = false; - this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; - this.message = ""; - } - TypeComparisonInfo.prototype.addMessageToFront = function (message) { - if(!this.onlyCaptureFirstError) { - this.message = this.message ? message + ":\n\t" + this.message : message; - } else { - this.setMessage(message); - } - }; - TypeComparisonInfo.prototype.setMessage = function (message) { - this.message = message; - }; - return TypeComparisonInfo; - })(); - TypeScript.TypeComparisonInfo = TypeComparisonInfo; - (function (TypeCheckCollectionMode) { - TypeCheckCollectionMode._map = []; - TypeCheckCollectionMode._map[0] = "Resident"; - TypeCheckCollectionMode.Resident = 0; - TypeCheckCollectionMode._map[1] = "Transient"; - TypeCheckCollectionMode.Transient = 1; - })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); - var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; - var PersistentGlobalTypeState = (function () { - function PersistentGlobalTypeState(errorReporter) { - this.errorReporter = errorReporter; - this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.globals = null; - this.globalTypes = null; - this.ambientGlobals = null; - this.ambientGlobalTypes = null; - this.residentGlobalValues = new TypeScript.StringHashTable(); - this.residentGlobalTypes = new TypeScript.StringHashTable(); - this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); - this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); - this.residentTypeCheck = true; - this.mod = null; - this.gloMod = null; - this.wildElm = null; - this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); - this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); - this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); - this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); - this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); - var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); - this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); - this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); - this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); - this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); - this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); - this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); - this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); - this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); - this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); - this.setCollectionMode(TypeCheckCollectionMode.Resident); - this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); - this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); - this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); - this.mod.members = dualGlobalScopedMembers; - this.mod.ambientMembers = dualGlobalScopedAmbientMembers; - this.mod.containedScope = this.globalScope; - this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); - this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); - this.defineGlobalValue("undefined", this.undefinedType); - } - PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { - var primitive = new TypeScript.Type(); - primitive.primitiveTypeClass = flags; - var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); - symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - primitive.symbol = symbol; - this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); - return primitive; - }; - PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { - this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; - }; - PersistentGlobalTypeState.prototype.refreshPersistentState = function () { - this.globals = new TypeScript.StringHashTable(); - this.globalTypes = new TypeScript.StringHashTable(); - this.ambientGlobals = new TypeScript.StringHashTable(); - this.ambientGlobalTypes = new TypeScript.StringHashTable(); - this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); - this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); - this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); - this.globalTypes.add("number", this.doubleType.symbol); - this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); - this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); - this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); - this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); - this.dualGlobalValues.secondaryTable = this.globals; - this.dualGlobalTypes.secondaryTable = this.globalTypes; - this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; - this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; - }; - PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { - var valueLocation = new TypeScript.ValueLocation(); - valueLocation.typeLink = new TypeScript.TypeLink(); - var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); - sym.setType(type); - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - sym.container = this.gloMod; - this.importedGlobalsTable.addPublicMember(name, sym); - }; - return PersistentGlobalTypeState; - })(); - TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; - var ContextualTypeContext = (function () { - function ContextualTypeContext(contextualType, provisional, contextID) { - this.contextualType = contextualType; - this.provisional = provisional; - this.contextID = contextID; - this.targetSig = null; - this.targetThis = null; - this.targetAccessorType = null; - } - return ContextualTypeContext; - })(); - TypeScript.ContextualTypeContext = ContextualTypeContext; - var ContextualTypingContextStack = (function () { - function ContextualTypingContextStack(checker) { - this.checker = checker; - this.contextStack = []; - this.hadProvisionalErrors = false; - } - ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; - ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { - this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); - this.checker.errorReporter.pushToErrorSink = provisional; - }; - ContextualTypingContextStack.prototype.popContextualType = function () { - var tc = this.contextStack.pop(); - this.checker.errorReporter.pushToErrorSink = this.isProvisional(); - this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); - this.checker.errorReporter.freeCapturedErrors(); - return tc; - }; - ContextualTypingContextStack.prototype.getContextualType = function () { - return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); - }; - ContextualTypingContextStack.prototype.getContextID = function () { - return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); - }; - ContextualTypingContextStack.prototype.isProvisional = function () { - return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); - }; - return ContextualTypingContextStack; - })(); - TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; - var TypeChecker = (function () { - function TypeChecker(persistentState) { - this.persistentState = persistentState; - this.errorReporter = null; - this.checkControlFlow = false; - this.printControlFlowGraph = false; - this.checkControlFlowUseDef = false; - this.styleSettings = null; - this.units = null; - this.anon = "_anonymous"; - this.locationInfo = null; - this.typeFlow = null; - this.currentCompareA = null; - this.currentCompareB = null; - this.currentModDecl = null; - this.inBind = false; - this.inWith = false; - this.errorsOnWith = true; - this.currentContextualTypeContext = null; - this.resolvingBases = false; - this.canCallDefinitionSignature = false; - this.assignableCache = { - }; - this.subtypeCache = { - }; - this.identicalCache = { - }; - this.provisionalStartedTypecheckObjects = []; - this.mustCaptureGlobalThis = false; - this.voidType = this.persistentState.voidType; - this.booleanType = this.persistentState.booleanType; - this.numberType = this.persistentState.doubleType; - this.stringType = this.persistentState.stringType; - this.anyType = this.persistentState.anyType; - this.nullType = this.persistentState.nullType; - this.undefinedType = this.persistentState.undefinedType; - this.globals = this.persistentState.dualGlobalValues; - this.globalTypes = this.persistentState.dualGlobalTypes; - this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; - this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; - this.gloModType = this.persistentState.mod; - this.gloMod = this.persistentState.gloMod; - this.wildElm = this.persistentState.wildElm; - this.globalScope = this.persistentState.globalScope; - this.typingContextStack = new ContextualTypingContextStack(this); - } - TypeChecker.prototype.setStyleOptions = function (style) { - this.styleSettings = style; - }; - TypeChecker.prototype.setContextualType = function (type, provisional) { - this.typingContextStack.pushContextualType(type, provisional); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.unsetContextualType = function () { - var lastTC = this.typingContextStack.popContextualType(); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - return lastTC; - }; - TypeChecker.prototype.hadProvisionalErrors = function () { - return this.typingContextStack.hadProvisionalErrors; - }; - TypeChecker.prototype.resetProvisionalErrors = function () { - if(!this.typingContextStack.getContextualType()) { - this.typingContextStack.hadProvisionalErrors = false; - } - }; - TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { - if(condition) { - this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); - } - this.typeFlow.typeCheck(ast); - if(condition) { - this.unsetContextualType(); - } - }; - TypeChecker.prototype.resetTargetType = function () { - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.killCurrentContextualType = function () { - this.currentContextualTypeContext = null; - this.errorReporter.pushToErrorSink = false; - }; - TypeChecker.prototype.hasTargetType = function () { - return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; - }; - TypeChecker.prototype.getTargetTypeContext = function () { - return this.currentContextualTypeContext; - }; - TypeChecker.prototype.inProvisionalTypecheckMode = function () { - return this.typingContextStack.isProvisional(); - }; - TypeChecker.prototype.getTypeCheckFinishedStatus = function () { - if(this.inProvisionalTypecheckMode()) { - return this.typingContextStack.getContextID(); - } - return TypeScript.TypeCheckStatus.Finished; - }; - TypeChecker.prototype.typeStatusIsFinished = function (status) { - return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); - }; - TypeChecker.prototype.addStartedPTO = function (pto) { - if(this.inProvisionalTypecheckMode()) { - this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; - } - }; - TypeChecker.prototype.cleanStartedPTO = function () { - for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { - if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { - this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - } - } - this.provisionalStartedTypecheckObjects = []; - }; - TypeChecker.prototype.collectTypes = function (ast) { - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - this.locationInfo = script.locationInfo; - } - var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); - var context = new TypeScript.TypeCollectionContext(globalChain, this); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); - }; - TypeChecker.prototype.makeArrayType = function (type) { - if(type.arrayCache == null) { - type.arrayCache = new ArrayCache(); - type.arrayCache.arrayType = new TypeScript.Type(); - type.arrayCache.arrayType.elementType = type; - type.arrayCache.arrayType.symbol = type.symbol; - } - return type.arrayCache.arrayType; - }; - TypeChecker.prototype.getParameterList = function (funcDecl, container) { - var args = funcDecl.arguments; - var parameterTable = null; - var parameterBuilder = null; - var len = args.members.length; - var nonOptionalParams = 0; - var result = []; - if(len > 0) { - parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); - for(var i = 0; i < len; i++) { - var parameter = args.members[i]; - var paramDef = new TypeScript.ValueLocation(); - var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); - parameterSymbol.declAST = parameter; - parameterSymbol.funcDecl = funcDecl; - parameter.id.sym = parameterSymbol; - parameter.sym = parameterSymbol; - paramDef.symbol = parameterSymbol; - paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); - parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); - result[result.length] = parameterSymbol; - if(!parameter.isOptionalArg()) { - nonOptionalParams++; - } - } - } - return { - parameters: result, - nonOptionalParameterCount: nonOptionalParams - }; - }; - TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isDefinition = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition); - var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var isGlobal = container == this.gloMod; - var signature = new TypeScript.Signature(); - var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; - if(funcDecl.returnTypeAnnotation || isDefinition) { - signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); - } else { - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = this.anyType; - } - signature.hasVariableArgList = funcDecl.variableArgList; - var sigData = this.getParameterList(funcDecl, container); - signature.parameters = sigData.parameters; - signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; - funcDecl.signature = signature; - signature.declAST = funcDecl; - var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); - if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); - } - var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); - if(isConstructor) { - if(groupType.construct == null) { - groupType.construct = new TypeScript.SignatureGroup(); - } - groupType.construct.addSignature(signature); - groupType.construct.hasImplementation = !(funcDecl.isSignature()); - if(groupType.construct.hasImplementation) { - groupType.setHasImplementation(); - } - } else { - if(funcDecl.isIndexerMember()) { - if(groupType.index == null) { - groupType.index = new TypeScript.SignatureGroup(); - groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; - } - groupType.index.addSignature(signature); - groupType.index.hasImplementation = !(funcDecl.isSignature()); - if(groupType.index.hasImplementation) { - groupType.setHasImplementation(); - } - } else { - if(groupType.call == null) { - groupType.call = new TypeScript.SignatureGroup(); - } - groupType.call.addSignature(signature); - groupType.call.hasImplementation = !(funcDecl.isSignature()); - if(groupType.call.hasImplementation) { - groupType.setHasImplementation(); - } - } - } - var instanceType = groupType.instanceType; - var funcName = null; - var usedHint = false; - if(funcDecl.name && !funcDecl.name.isMissing()) { - funcName = funcDecl.name.text; - } else { - if(funcDecl.hint) { - funcName = funcDecl.hint; - usedHint = true; - } - } - if(groupType.symbol == null) { - groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); - if(!useOverloadGroupSym) { - groupType.symbol.declAST = funcDecl; - } - } - if(isStatic) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Static; - } - if(isAmbient) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; - } - if(isPrivate) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Private; - } - groupType.symbol.isMethod = funcDecl.isMethod(); - if(groupType.symbol.isMethod) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Property; - } - funcDecl.type = groupType; - if(!isConstructor) { - if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { - if(addToScope) { - if(funcDecl.isMethod() && isStatic) { - if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { - this.errorReporter.duplicateIdentifier(funcDecl, funcName); - } - groupType.symbol.container = container; - } else { - if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { - scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); - } - } - } else { - if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } - } else { - if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } - } - if(useOverloadGroupSym) { - var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; - var classType = groupType; - if(classType != overloadGroupType) { - if(classType.construct == null) { - if(overloadGroupType && overloadGroupType.construct) { - classType.construct = overloadGroupType.construct; - } else { - classType.construct = new TypeScript.SignatureGroup(); - } - } else { - if(overloadGroupType) { - if(overloadGroupType.construct) { - classType.construct.signatures.concat(overloadGroupType.construct.signatures); - } - } - } - if(overloadGroupType) { - if(classType.call == null) { - classType.call = overloadGroupType.call; - } else { - if(overloadGroupType.call) { - classType.call.signatures.concat(overloadGroupType.call.signatures); - } - } - if(!isStatic) { - if(classType.instanceType == null) { - classType.instanceType = overloadGroupType.instanceType; - } - var instanceType = classType.instanceType; - if(instanceType) { - if(instanceType.call == null) { - instanceType.call = overloadGroupType.call; - } else { - if(overloadGroupType.call) { - instanceType.call.signatures.concat(overloadGroupType.call.signatures); - } - } - } - } - if(classType.index == null) { - classType.index = overloadGroupType.index; - } else { - if(overloadGroupType.index) { - classType.index.signatures.concat(overloadGroupType.index.signatures); - } - } - } - } - } - return signature; - }; - TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { - var accessorSym = null; - var sig = funcDecl.signature; - var nameText = funcDecl.name.text; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - if(fgSym == null) { - var field = new TypeScript.ValueLocation(); - accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); - field.symbol = accessorSym; - accessorSym.declAST = funcDecl; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = sig.declAST.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = sig.declAST.type.symbol; - } - field.typeLink = TypeScript.getTypeLink(null, this, false); - if(addToMembers) { - if(enclosingClass) { - if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { - this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); - } - accessorSym.container = enclosingClass.symbol; - } else { - this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); - } - } else { - scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); - } - if(isClassProperty) { - accessorSym.flags |= TypeScript.SymbolFlags.Property; - } - if(isStatic) { - accessorSym.flags |= TypeScript.SymbolFlags.Static; - } - if(isPrivate) { - accessorSym.flags |= TypeScript.SymbolFlags.Private; - } else { - accessorSym.flags |= TypeScript.SymbolFlags.Public; - } - } else { - accessorSym = (fgSym); - if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = funcDecl.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = funcDecl.type.symbol; - } - } - return accessorSym; - }; - TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { - resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); - var i = 0; - var parent; - if(type.extendsList) { - for(var len = type.extendsList.length; i < len; i++) { - parent = type.extendsList[i]; - if(baseContext.baseId == parent.typeID) { - this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); - parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - break; - } - this.addBases(resultScope, parent, baseContext); - } - } - }; - TypeChecker.prototype.scopeOf = function (type) { - var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); - var baseContext = { - base: type.symbol && type.symbol.name ? type.symbol.name : "{}", - baseId: type.typeID - }; - this.addBases(resultScope, type, baseContext); - return resultScope; - }; - TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { - var symbol = null; - if(containingType.containedScope) { - symbol = containingType.containedScope.find(name, false, true); - } else { - if(containingType.members) { - symbol = containingType.members.allMembers.lookup(name); - if(symbol == null && containingType.ambientMembers) { - symbol = containingType.ambientMembers.allMembers.lookup(name); - } - } - } - if(symbol == null) { - var typeMembers = containingType.getAllEnclosedTypes(); - var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); - if(typeMembers) { - symbol = typeMembers.allMembers.lookup(name); - if(symbol == null && ambientTypeMembers) { - symbol = ambientTypeMembers.allMembers.lookup(name); - } - } - } - if(symbol && symbol.isType()) { - return symbol; - } else { - return null; - } - }; - TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { - var originalIdText = idText; - var symbol = search(idText); - if(symbol == null) { - if(!symbol) { - idText = TypeScript.swapQuotes(originalIdText); - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".str"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; - symbol = search(idText); - } - if(!symbol && !TypeScript.isRelative(originalIdText)) { - idText = originalIdText; - var strippedIdText = TypeScript.stripQuotes(idText); - var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); - while(symbol == null && path != "") { - idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); - symbol = search(idText); - if(symbol == null) { - idText = TypeScript.changePathToSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDTS(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - if(path === '/') { - path = ''; - } else { - path = TypeScript.normalizePath(path + ".."); - path = path && path != '/' ? path + '/' : path; - } - } - } - } - } - return symbol; - }; - TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { - var lhs = dotNode.operand1; - var rhs = dotNode.operand2; - var resultType = this.anyType; - var lhsType = this.anyType; - if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { - if(lhs.nodeType == TypeScript.NodeType.Dot) { - lhsType = this.resolveTypeMember(scope, lhs); - } else { - if(lhs.nodeType == TypeScript.NodeType.Name) { - var identifier = lhs; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else { - if(symbol.isType()) { - var typeSymbol = symbol; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(TypeScript.optimizeModuleCodeGen && symbol) { - var symType = symbol.getType(); - if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; - } - } - } - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - lhsType = symbol.getType(); - identifier.sym = symbol; - } else { - this.errorReporter.simpleError(lhs, "Expected type"); - } - } - } - } - if(!lhsType) { - lhsType = this.anyType; - } - if(lhsType != this.anyType) { - var rhsIdentifier = rhs; - var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); - if(resultSymbol == null) { - resultType = this.anyType; - this.errorReporter.simpleError(dotNode, "Expected type"); - } else { - resultType = resultSymbol.getType(); - if(!resultSymbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); - } - } - rhsIdentifier.sym = resultType.symbol; - } - } - if(resultType.isClass()) { - resultType = resultType.instanceType; - } - return resultType; - }; - TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { - var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; - var signatures; - if(funcDecl.isConstructMember()) { - signatures = functionGroupSymbol.type.construct.signatures; - } else { - if(funcDecl.isIndexerMember()) { - signatures = functionGroupSymbol.type.getInstanceType().index.signatures; - } else { - signatures = functionGroupSymbol.type.call.signatures; - } - } - var signature = signatures[signatures.length - 1]; - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); - } - if(len && funcDecl.variableArgList) { - if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { - this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); - signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); - } - } - this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); - return functionGroupSymbol; - }; - TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = varDecl; - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); - this.resolveTypeLink(scope, field.typeLink, true); - varDecl.sym = fieldSymbol; - varDecl.type = field.typeLink.type; - return fieldSymbol; - }; - TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { - var arrayCount = 0; - if(typeLink.type == null) { - var ast = typeLink.ast; - if(ast) { - while(typeLink.type == null) { - switch(ast.nodeType) { - case TypeScript.NodeType.Name: { - var identifier = ast; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - typeLink.type = this.anyType; - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else { - if(symbol.isType()) { - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - identifier.sym = symbol; - typeLink.type = symbol.getType(); - if(typeLink.type) { - if(typeLink.type.isClass()) { - typeLink.type = typeLink.type.instanceType; - } - } else { - typeLink.type = this.anyType; - } - } else { - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - } - } - break; - - } - case TypeScript.NodeType.Dot: { - typeLink.type = this.resolveTypeMember(scope, ast); - break; - - } - case TypeScript.NodeType.TypeRef: { - var typeRef = ast; - arrayCount = typeRef.arrayCount; - ast = typeRef.term; - if(ast == null) { - typeLink.type = this.anyType; - } - break; - - } - case TypeScript.NodeType.InterfaceDeclaration: { - var interfaceDecl = ast; - var interfaceType = new TypeScript.Type(); - var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); - interfaceType.containedScope.container = interfaceSymbol; - interfaceType.memberScope = interfaceType.containedScope; - var memberList = interfaceDecl.members; - var props = memberList.members; - var propsLen = props.length; - for(var j = 0; j < propsLen; j++) { - var propDecl = props[j]; - var propSym = null; - var addMember = true; - var id = null; - if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = propDecl; - id = funcDecl.name; - propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); - addMember = (propSym == null); - if(funcDecl.isSpecialFn()) { - addMember = false; - propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); - } else { - propSym = this.resolveFuncDecl(funcDecl, scope, propSym); - } - funcDecl.type = (propSym).type; - } else { - id = (propDecl).id; - propSym = this.resolveVarDecl(propDecl, scope); - addMember = !id.isMissing(); - } - if(addMember) { - if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { - propSym.flags |= TypeScript.SymbolFlags.Optional; - } - if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { - this.errorReporter.duplicateIdentifier(ast, propSym.name); - } - } - } - ast.type = interfaceType; - typeLink.type = interfaceType; - break; - - } - case TypeScript.NodeType.FuncDecl: { - var tsym = this.resolveFuncDecl(ast, scope, null); - typeLink.type = tsym.type; - break; - - } - default: { - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - break; - - } - } - } - } - for(var count = arrayCount; count > 0; count--) { - typeLink.type = this.makeArrayType(typeLink.type); - } - if(supplyVar && (typeLink.type == null)) { - typeLink.type = this.anyType; - } - if(typeLink.ast) { - typeLink.ast.type = typeLink.type; - } - } - }; - TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { - this.resolvingBases = true; - this.resolveTypeLink(scope, typeLink, true); - this.resolvingBases = false; - var extendsType = null; - if(typeLink.type.isClass()) { - extendsType = typeLink.type.instanceType; - } else { - extendsType = typeLink.type; - } - return extendsType; - }; - TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { - if(signatures.length == 1) { - return { - sig: signatures[0].signature, - ambiguous: false - }; - } - var best = signatures[0]; - var Q = null; - var AType = null; - var PType = null; - var QType = null; - var ambiguous = false; - for(var qSig = 1; qSig < signatures.length; qSig++) { - Q = signatures[qSig]; - var i = 0; - for(i = 0; args && i < args.members.length; i++) { - AType = args.members[i].type; - PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; - QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; - if(this.typesAreIdentical(PType, QType)) { - continue; - } else { - if(this.typesAreIdentical(AType, PType)) { - break; - } else { - if(this.typesAreIdentical(AType, QType)) { - best = Q; - break; - } else { - if(this.sourceIsSubtypeOfTarget(PType, QType)) { - break; - } else { - if(this.sourceIsSubtypeOfTarget(QType, PType)) { - best = Q; - break; - } else { - if(Q.hadProvisionalErrors) { - break; - } else { - if(best.hadProvisionalErrors) { - best = Q; - break; - } - } - } - } - } - } - } - } - if(!args || i == args.members.length) { - var collection = { - getLength: function () { - return 2; - }, - setTypeAtIndex: function (index, type) { - }, - getTypeAtIndex: function (index) { - return index ? Q.signature.returnType.type : best.signature.returnType.type; - } - }; - var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); - ambiguous = !bct; - } else { - ambiguous = false; - } - } - return { - sig: best.signature, - ambiguous: ambiguous - }; - }; - TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { - var applicableSigs = []; - var memberType = null; - var miss = false; - var cxt = null; - var hadProvisionalErrors = false; - for(var i = 0; i < signatures.length; i++) { - miss = false; - for(var j = 0; j < args.members.length; j++) { - if(j >= signatures[i].parameters.length) { - continue; - } - memberType = signatures[i].parameters[j].getType(); - if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { - memberType = memberType.elementType; - } - if(memberType == this.anyType) { - continue; - } else { - if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { - if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { - continue; - } - if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { - if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { - this.typeFlow.typeCheck(args.members[j]); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - break; - } - } else { - break; - } - } else { - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } else { - if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { - if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } else { - if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { - if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - break; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } - } - } - } - if(j == args.members.length) { - applicableSigs[applicableSigs.length] = { - signature: signatures[i], - hadProvisionalErrors: hadProvisionalErrors - }; - } - hadProvisionalErrors = false; - } - return applicableSigs; - }; - TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { - if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { - return false; - } - beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); - if(!beStringent) { - return true; - } - if(!funcDecl.signature) { - this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); - this.typeFlow.typeCheck(funcDecl); - } - var signature = funcDecl.signature; - var paramLen = signature.parameters.length; - for(var i = 0; i < paramLen; i++) { - var param = signature.parameters[i]; - var symbol = param; - var argDecl = symbol.declAST; - if(beStringent && argDecl.typeExpr) { - return false; - } - } - if(candidateType.construct && candidateType.call) { - return false; - } - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - if(!candidateSigs || candidateSigs.signatures.length > 1) { - return false; - } - return true; - }; - TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { - if(targetType == this.typeFlow.objectInterfaceType) { - return true; - } - var memberDecls = objectLit.operand; - if(!(memberDecls && targetType.memberScope)) { - return false; - } - var id = null; - var targetMember = null; - var text = ""; - var foundSyms = { - }; - for(var i = 0; i < memberDecls.members.length; i++) { - id = (memberDecls.members[i]).operand1; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else { - if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - return false; - } - } - targetMember = targetType.memberScope.find(text, true, false); - if(!targetMember) { - return false; - } - foundSyms[text] = true; - } - var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); - for(var i = 0; i < targetMembers.length; i++) { - var memberName = targetMembers[i]; - var memberSym = targetType.memberScope.find(memberName, true, false); - if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.widenType = function (t) { - if(t == this.undefinedType || t == this.nullType) { - return this.anyType; - } - return t; - }; - TypeChecker.prototype.isNullOrUndefinedType = function (t) { - return t == this.undefinedType || t == this.nullType; - }; - TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { - var i = 0; - var len = collection.getLength(); - var nlastChecked = 0; - var bestCommonType = initialType; - if(targetType) { - bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; - } - var convergenceType = bestCommonType; - while(nlastChecked < len) { - for(i = 0; i < len; i++) { - if(i == nlastChecked) { - continue; - } - if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { - convergenceType = bestCommonType; - } - if(bestCommonType == this.anyType || bestCommonType == null) { - break; - } else { - if(targetType) { - collection.setTypeAtIndex(i, targetType); - } - } - } - if(convergenceType && bestCommonType) { - break; - } - nlastChecked++; - if(nlastChecked < len) { - convergenceType = collection.getTypeAtIndex(nlastChecked); - } - } - return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); - }; - TypeChecker.prototype.typesAreIdentical = function (t1, t2) { - if(t1 == t2) { - return true; - } - if(!t1 || !t2) { - return false; - } - if(t1.isClass() || t1.isClassInstance()) { - return false; - } - var comboId = (t2.typeID << 16) | t1.typeID; - if(this.identicalCache[comboId]) { - return true; - } - if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(t1.isArray() || t2.isArray()) { - if(!(t1.isArray() && t2.isArray())) { - return false; - } - this.identicalCache[comboId] = false; - var ret = this.typesAreIdentical(t1.elementType, t2.elementType); - if(ret) { - this.subtypeCache[comboId] = true; - } else { - this.subtypeCache[comboId] = undefined; - } - return ret; - } - if(t1.primitiveTypeClass != t2.primitiveTypeClass) { - return false; - } - this.identicalCache[comboId] = false; - if(t1.memberScope && t2.memberScope) { - var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); - var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); - if(t1MemberKeys.length != t2MemberKeys.length) { - this.identicalCache[comboId] = undefined; - return false; - } - var t1MemberSymbol = null; - var t2MemberSymbol = null; - var t1MemberType = null; - var t2MemberType = null; - for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { - if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); - t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); - if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberType = t1MemberSymbol.getType(); - t2MemberType = t2MemberSymbol.getType(); - if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { - continue; - } - if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { - this.identicalCache[comboId] = undefined; - return false; - } - } - } else { - if(t1.memberScope || t2.memberScope) { - this.identicalCache[comboId] = undefined; - return false; - } - } - if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { - this.identicalCache[comboId] = undefined; - return false; - } - this.identicalCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { - if(sg1 == sg2) { - return true; - } - if(!sg1 || !sg2) { - return false; - } - if(sg1.signatures.length != sg2.signatures.length) { - return false; - } - var sig1 = null; - var sig2 = null; - var sigsMatch = false; - for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { - sig1 = sg1.signatures[iSig1]; - for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { - sig2 = sg2.signatures[iSig2]; - if(this.signaturesAreIdentical(sig1, sig2)) { - sigsMatch = true; - break; - } - } - if(sigsMatch) { - sigsMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { - if(s1.hasVariableArgList != s2.hasVariableArgList) { - return false; - } - if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { - return false; - } - if(s1.parameters.length != s2.parameters.length) { - return false; - } - if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { - return false; - } - for(var iParam = 0; iParam < s1.parameters.length; iParam++) { - if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { - if(source == target) { - return true; - } - if(!(source && target)) { - return true; - } - var comboId = (source.typeID << 16) | target.typeID; - if(comparisonCache[comboId] != undefined) { - return true; - } - if(assignableTo) { - if(source == this.anyType || target == this.anyType) { - return true; - } - } else { - if(target == this.anyType) { - return true; - } - } - if(source == this.undefinedType) { - return true; - } - if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { - return true; - } - if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(source.isArray() || target.isArray()) { - if(!(source.isArray() && target.isArray())) { - return false; - } - comparisonCache[comboId] = false; - var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); - if(ret) { - comparisonCache[comboId] = true; - } else { - comparisonCache[comboId] = undefined; - } - return ret; - } - if(source.primitiveTypeClass != target.primitiveTypeClass) { - if(target.primitiveTypeClass == TypeScript.Primitive.None) { - if(source == this.numberType && this.typeFlow.numberInterfaceType) { - source = this.typeFlow.numberInterfaceType; - } else { - if(source == this.stringType && this.typeFlow.stringInterfaceType) { - source = this.typeFlow.stringInterfaceType; - } else { - if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { - source = this.typeFlow.booleanInterfaceType; - } else { - return false; - } - } - } - } else { - return false; - } - } - comparisonCache[comboId] = false; - if(source.hasBase(target)) { - comparisonCache[comboId] = true; - return true; - } - if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { - return true; - } - if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { - return true; - } - if(target.isClass() || target.isClassInstance()) { - comparisonCache[comboId] = undefined; - return false; - } - if(target.memberScope && source.memberScope) { - var mPropKeys = target.memberScope.getAllValueSymbolNames(true); - var mProp = null; - var nProp = null; - var mPropType = null; - var nPropType = null; - var inferenceSymbol = null; - for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { - mProp = target.memberScope.find(mPropKeys[iMProp], false, false); - nProp = source.memberScope.find(mPropKeys[iMProp], false, false); - if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { - continue; - } - if(mProp.isInferenceSymbol()) { - inferenceSymbol = mProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(mProp.declAST); - } - } - mPropType = mProp.getType(); - if(!nProp) { - if(this.typeFlow.objectInterfaceType) { - nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { - nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; - comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); - } - return false; - } else { - continue; - } - } - } - } - if(nProp.isInferenceSymbol()) { - inferenceSymbol = nProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(nProp.declAST); - } - } - nPropType = nProp.getType(); - if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { - continue; - } - if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; - comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } - return false; - } - } - } - if(source.call || target.call) { - if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.call && target.call) { - comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.call ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(source.construct || target.construct) { - if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.construct && target.construct) { - comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(target.index) { - var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; - var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; - if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - comparisonCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { - if(sourceSG == targetSG) { - return true; - } - if(!(sourceSG && targetSG)) { - return false; - } - var mSig = null; - var nSig = null; - var foundMatch = false; - for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { - mSig = targetSG.signatures[iMSig]; - for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { - nSig = sourceSG.signatures[iNSig]; - if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { - foundMatch = true; - break; - } - } - if(foundMatch) { - foundMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { - if(!sourceSig.parameters || !targetSig.parameters) { - return false; - } - var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; - var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; - if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; - comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); - } - return false; - } - var sourceReturnType = sourceSig.returnType.type; - var targetReturnType = targetSig.returnType.type; - if(targetReturnType != this.voidType) { - if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; - } - return false; - } - } - var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; - var sourceParamType = null; - var targetParamType = null; - var sourceParamName = ""; - var targetParamName = ""; - for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { - if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } else { - if(iSource == sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - if(sourceParamType.elementType) { - sourceParamType = sourceParamType.elementType; - } - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } - } - if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } else { - if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - if(targetParamType.elementType) { - targetParamType = targetParamType.elementType; - } - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } - } - if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; - } - return false; - } - } - return true; - }; - return TypeChecker; - })(); - TypeScript.TypeChecker = TypeChecker; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Continuation = (function () { - function Continuation(normalBlock) { - this.normalBlock = normalBlock; - this.exceptionBlock = -1; - } - return Continuation; - })(); - TypeScript.Continuation = Continuation; - function getBaseTypeLinks(bases, baseTypeLinks) { - if(bases) { - var len = bases.members.length; - if(baseTypeLinks == null) { - baseTypeLinks = new Array(); - } - for(var i = 0; i < len; i++) { - var baseExpr = bases.members[i]; - var name = baseExpr; - var typeLink = new TypeScript.TypeLink(); - typeLink.ast = name; - baseTypeLinks[baseTypeLinks.length] = typeLink; - } - } - return baseTypeLinks; - } - function getBases(type, typeDecl) { - type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); - type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); - } - function addPrototypeField(classType, ast, context) { - var field = new TypeScript.ValueLocation(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.ast = ast; - field.typeLink.type = classType.instanceType; - var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - classType.members.addPublicMember("prototype", fieldSymbol); - } - function createNewConstructGroupForType(type) { - var signature = new TypeScript.Signature(); - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = type.instanceType; - signature.parameters = []; - type.construct = new TypeScript.SignatureGroup(); - type.construct.addSignature(signature); - } - TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; - function cloneParentConstructGroupForChildType(child, parent) { - child.construct = new TypeScript.SignatureGroup(); - var sig = null; - if(!parent.construct) { - createNewConstructGroupForType(parent); - } - for(var i = 0; i < parent.construct.signatures.length; i++) { - sig = new TypeScript.Signature(); - sig.parameters = parent.construct.signatures[i].parameters; - sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; - sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; - sig.declAST = parent.construct.signatures[i].declAST; - sig.returnType = new TypeScript.TypeLink(); - sig.returnType.type = child.instanceType; - child.construct.addSignature(sig); - } - } - TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; - TypeScript.globalId = "__GLO"; - function findTypeSymbolInScopeChain(name, scopeChain) { - var symbol = scopeChain.scope.find(name, false, true); - if(symbol == null && scopeChain.previous) { - symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); - } - return symbol; - } - function findSymbolFromAlias(alias, context) { - var symbol = null; - switch(alias.nodeType) { - case TypeScript.NodeType.Name: { - var name = (alias).text; - var isDynamic = TypeScript.isQuoted(name); - var findSym = function (id) { - if(context.members) { - return context.members.lookup(name); - } else { - return findTypeSymbolInScopeChain(name, context.topLevelScope); - } - }; - if(isDynamic) { - symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); - } else { - symbol = findSym(name); - } - break; - - } - case TypeScript.NodeType.Dot: { - var dottedExpr = alias; - var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); - if(op1Sym && op1Sym.getType()) { - symbol = findSymbolFromAlias(dottedExpr.operand2, context); - } - break; - - } - default: { - break; - - } - } - if(symbol) { - var symType = symbol.getType(); - if(symType) { - var members = symType.members; - if(members) { - context.members = members.publicMembers; - } - } - } - return symbol; - } - function preCollectImportTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var typeSymbol = null; - var modType = null; - var importDecl = ast; - var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { - topLevelScope: scopeChain, - members: null, - tcContext: context - }); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - if(aliasedModSymbol) { - var aliasedModType = aliasedModSymbol.getType(); - if(aliasedModType) { - modType = aliasedModType; - } - } - typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); - typeSymbol.aliasLink = importDecl; - if(context.scopeChain.moduleDecl) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = importDecl; - importDecl.id.sym = typeSymbol; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); - return true; - } - TypeScript.preCollectImportTypes = preCollectImportTypes; - function preCollectModuleTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var moduleDecl = ast; - var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); - var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - var modName = (moduleDecl.name).text; - var isDynamic = TypeScript.isQuoted(modName); - var symbol = scopeChain.scope.findLocal(modName, false, false); - var typeSymbol = null; - var modType = null; - if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { - if(modType == null) { - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.setHasImplementation(); - } - typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); - typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); - if(context.scopeChain.moduleDecl) { - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = moduleDecl; - typeSymbol.prettyName = moduleDecl.prettyName; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - modType.symbol = typeSymbol; - } else { - if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { - context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); - } - typeSymbol = symbol; - var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; - var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; - var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicMembers = typeSymbol.type.members.publicMembers; - var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); - var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; - var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = members; - modType.ambientMembers = ambientMembers; - modType.setHasImplementation(); - modType.symbol = typeSymbol; - typeSymbol.addLocation(moduleDecl.minChar); - typeSymbol.expansions.push(modType); - typeSymbol.expansionsDeclAST.push(moduleDecl); - } - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - moduleDecl.mod = modType; - TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); - return true; - } - TypeScript.preCollectModuleTypes = preCollectModuleTypes; - function preCollectClassTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var classDecl = ast; - var classType; - var instanceType; - var typeSymbol = null; - var className = (classDecl.name).text; - var alreadyInScope = false; - var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var containerMod = scopeChain.container; - var foundValSymbol = false; - typeSymbol = scopeChain.scope.findLocal(className, false, true); - if(!typeSymbol) { - var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); - if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { - typeSymbol = valTypeSymbol; - foundValSymbol = true; - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - } - } - if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { - typeSymbol = null; - } - if(typeSymbol == null) { - var valueSymbol = scopeChain.scope.findLocal(className, false, false); - classType = new TypeScript.Type(); - classType.setHasImplementation(); - instanceType = new TypeScript.Type(); - instanceType.setHasImplementation(); - classType.instanceType = instanceType; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - addPrototypeField(classType, classDecl, context); - instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); - typeSymbol.declAST = classDecl; - typeSymbol.instanceType = instanceType; - classType.symbol = typeSymbol; - instanceType.symbol = typeSymbol; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - typeSymbol.declModule = context.scopeChain.moduleDecl; - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - ast.type = classType; - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - if(valueSymbol == null) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - } - } else { - classType = typeSymbol.type; - if(classType.instanceType == null) { - classType.instanceType = new TypeScript.Type(); - classType.instanceType.setHasImplementation(); - classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.instanceType.symbol = classType.symbol; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - } - instanceType = classType.instanceType; - ast.type = classType; - } - if(!classDecl.constructorDecl) { - if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { - context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); - } - createNewConstructGroupForType(classDecl.type); - } - classType.typeFlags |= TypeScript.TypeFlags.IsClass; - instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; - getBases(instanceType, classDecl); - TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); - return true; - } - TypeScript.preCollectClassTypes = preCollectClassTypes; - function preCollectInterfaceTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var interfaceDecl = ast; - var interfaceSymbol = null; - var interfaceType = null; - var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var alreadyInScope = true; - alreadyInScope = false; - var interfaceName = (interfaceDecl.name).text; - interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); - if(interfaceSymbol == null) { - interfaceType = new TypeScript.Type(); - interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceSymbol.declAST = interfaceDecl; - interfaceSymbol.declModule = context.scopeChain.moduleDecl; - } else { - alreadyInScope = true; - interfaceType = interfaceSymbol.type; - } - if(!interfaceType) { - interfaceType = context.checker.anyType; - } - ast.type = interfaceType; - getBases(interfaceType, interfaceDecl); - if(isExported) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(context.scopeChain.moduleDecl) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(!alreadyInScope) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); - } - TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); - return true; - } - TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; - function preCollectArgDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var argDecl = ast; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { - var field = new TypeScript.ValueLocation(); - var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); - var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); - fieldSymbol.transferVarFlags(argDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - argDecl.parameterPropertySym = fieldSymbol; - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); - field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); - argDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; - function preCollectVarDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var varDecl = ast; - var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); - var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); - var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); - var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { - if(isAmbient) { - var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); - if(existingSym) { - varDecl.sym = existingSym; - return false; - } - } - if(varDecl.id == null) { - context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); - return false; - } - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - if(isOptional) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; - } - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - fieldSymbol.declModule = context.scopeChain.moduleDecl; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { - if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { - context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); - } - fieldSymbol.container = context.scopeChain.classType.symbol; - } else { - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); - varDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; - function preCollectFuncDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - var funcDecl = ast; - var fgSym = null; - var nameText = funcDecl.getNameText(); - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); - var containerScope = context.scopeChain.scope; - var isGlobal = containerSym == context.checker.gloMod; - var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); - var go = false; - var foundSymbol = false; - if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - containerSym = containerSym.container; - containerScope = scopeChain.previous.scope; - } - funcDecl.unitIndex = context.checker.locationInfo.unitIndex; - if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { - return go; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { - var instType = context.scopeChain.thisType; - if(nameText && nameText != "__missing") { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - fgSym = containerScope.findLocal(nameText, false, false); - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, true); - } - } - if(fgSym) { - foundSymbol = true; - if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { - fgSym = null; - } - } - } - if(fgSym == null) { - if(!(funcDecl.isSpecialFn())) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; - } else { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; - } - if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { - fgSym.declAST = ast; - } - } else { - if((fgSym.kind() == TypeScript.SymbolKind.Type)) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; - } else { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - } - } - if(funcDecl.isSpecialFn() && !isStatic) { - funcDecl.type = instType ? instType : fgSym.type; - } else { - funcDecl.type = fgSym.type; - } - } else { - if(nameText) { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - if(funcDecl.isConstructor && context.scopeChain.previous) { - fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); - } - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, false); - } - } - if(fgSym) { - foundSymbol = true; - if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { - fgSym = null; - foundSymbol = false; - } - } - } - if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); - } - if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - fgSym.type = context.checker.anyType; - } - var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); - if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); - } - funcDecl.type.symbol.declAST = ast; - if(funcDecl.isConstructor) { - go = true; - } - ; ; - } - if(isExported) { - if(funcDecl.type.call) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { - fgSym.flags |= TypeScript.SymbolFlags.Exported; - } - } - if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; - funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; - } - if(fgSym && isOptional) { - fgSym.flags |= TypeScript.SymbolFlags.Optional; - } - return go; - } - TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; - function preCollectTypes(ast, parent, walker) { - var context = walker.state; - var go = false; - var scopeChain = context.scopeChain; - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - context.script = script; - go = true; - } else { - if(ast.nodeType == TypeScript.NodeType.List) { - go = true; - } else { - if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { - go = preCollectImportTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - go = false; - } else { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - go = preCollectModuleTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - go = preCollectClassTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.Block) { - go = true; - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - go = preCollectInterfaceTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - go = preCollectArgDeclTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.VarDecl) { - go = preCollectVarDeclTypes(ast, parent, context); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - go = preCollectFuncDeclTypes(ast, parent, context); - } else { - if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - } - } - } - } - } - } - } - } - } - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preCollectTypes = preCollectTypes; - function postCollectTypes(ast, parent, walker) { - var context = walker.state; - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else { - if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - TypeScript.popTypeCollectionScope(context); - } - } - } - return ast; - } - TypeScript.postCollectTypes = postCollectTypes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopeChain = (function () { - function ScopeChain(container, previous, scope) { - this.container = container; - this.previous = previous; - this.scope = scope; - } - return ScopeChain; - })(); - TypeScript.ScopeChain = ScopeChain; - var BBUseDefInfo = (function () { - function BBUseDefInfo(bb) { - this.bb = bb; - this.defsBySymbol = new Array(); - this.useIndexBySymbol = new Array(); - } - BBUseDefInfo.prototype.updateTop = function () { - var temp = new BitVector(this.top.bitCount); - for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { - var succ = this.bb.successors[i]; - if(succ.useDef) { - temp.union(succ.useDef.top); - } - } - temp.difference(this.kill); - temp.union(this.gen); - var changed = temp.notEq(this.top); - this.top = temp; - return changed; - }; - BBUseDefInfo.prototype.initialize = function (useDefContext) { - var _this = this; - var defSym = function (sym, context) { - if(context.isLocalSym(sym)) { - var index = context.getSymbolIndex(sym); - _this.useIndexBySymbol[index] = new Array(); - _this.defsBySymbol[index] = true; - } - }; - var useSym = function (sym, context, ast) { - if(context.isLocalSym(sym)) { - var symIndex = context.getSymbolIndex(sym); - if(_this.useIndexBySymbol[symIndex] == undefined) { - _this.useIndexBySymbol[symIndex] = new Array(); - } - var symUses = _this.useIndexBySymbol[symIndex]; - var astIndex = context.getUseIndex(ast); - context.addUse(symIndex, astIndex); - symUses.push(astIndex); - } - }; - function initUseDefPre(cur, parent, walker) { - var context = walker.state; - if(cur == null) { - cur = null; - } - if(cur.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = cur; - if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { - defSym(varDecl.sym, context); - } - } else { - if(cur.nodeType == TypeScript.NodeType.Name) { - if(parent) { - if(parent.nodeType == TypeScript.NodeType.Asg) { - var asg = parent; - if(asg.operand1 == cur) { - return cur; - } - } else { - if(parent.nodeType == TypeScript.NodeType.VarDecl) { - var parentDecl = parent; - if(parentDecl.id == cur) { - return cur; - } - } - } - } - var id = cur; - useSym(id.sym, context, cur); - } else { - if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { - var asg = cur; - if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { - var id = asg.operand1; - defSym(id.sym, context); - } - } else { - if(cur.nodeType == TypeScript.NodeType.FuncDecl) { - walker.options.goChildren = false; - } - } - } - } - return cur; - } - var options = new TypeScript.AstWalkOptions(); - options.reverseSiblings = true; - TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); - }; - BBUseDefInfo.prototype.initializeGen = function (useDefContext) { - var symbolLen = this.useIndexBySymbol.length; - var bitCount = useDefContext.uses.length; - this.gen = new BitVector(bitCount); - for(var s = 0; s < symbolLen; s++) { - var symUses = this.useIndexBySymbol[s]; - if((symUses != undefined) && (symUses.length > 0)) { - for(var u = 0, uLen = symUses.length; u < uLen; u++) { - this.gen.set(symUses[u], true); - } - } - } - this.top = this.gen; - }; - BBUseDefInfo.prototype.initializeKill = function (useDefContext) { - this.kill = new BitVector(this.gen.bitCount); - for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { - if(this.defsBySymbol[s]) { - var globalSymUses = useDefContext.useIndexBySymbol[s]; - if(globalSymUses) { - for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { - this.kill.set(globalSymUses[u], true); - } - } - } - } - }; - return BBUseDefInfo; - })(); - TypeScript.BBUseDefInfo = BBUseDefInfo; - var UseDefContext = (function () { - function UseDefContext() { - this.useIndexBySymbol = new Array(); - this.uses = new Array(); - this.symbols = new Array(); - this.symbolMap = new TypeScript.StringHashTable(); - this.symbolCount = 0; - } - UseDefContext.prototype.getSymbolIndex = function (sym) { - var name = sym.name; - var index = (this.symbolMap.lookup(name)); - if(index == null) { - index = this.symbolCount++; - this.symbols[index] = sym; - this.symbolMap.add(name, index); - } - return index; - }; - UseDefContext.prototype.addUse = function (symIndex, astIndex) { - var useBySym = this.useIndexBySymbol[symIndex]; - if(useBySym == undefined) { - useBySym = new Array(); - this.useIndexBySymbol[symIndex] = useBySym; - } - useBySym[useBySym.length] = astIndex; - }; - UseDefContext.prototype.getUseIndex = function (ast) { - this.uses[this.uses.length] = ast; - return this.uses.length - 1; - }; - UseDefContext.prototype.isLocalSym = function (sym) { - return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); - }; - UseDefContext.prototype.killSymbol = function (sym, bbUses) { - var index = this.symbolMap.lookup(sym.name); - var usesOfSym = this.useIndexBySymbol[index]; - for(var k = 0, len = usesOfSym.length; k < len; k++) { - bbUses.set(usesOfSym[k], true); - } - }; - return UseDefContext; - })(); - TypeScript.UseDefContext = UseDefContext; - var BitVector = (function () { - function BitVector(bitCount) { - this.bitCount = bitCount; - this.firstBits = 0; - this.restOfBits = null; - if(this.bitCount > BitVector.packBits) { - this.restOfBits = new Array(); - var len = Math.floor(this.bitCount / BitVector.packBits); - for(var i = 0; i < len; i++) { - this.restOfBits[i] = 0; - } - } - } - BitVector.packBits = 30; - BitVector.prototype.set = function (bitIndex, value) { - if(bitIndex < BitVector.packBits) { - if(value) { - this.firstBits |= (1 << bitIndex); - } else { - this.firstBits &= (~(1 << bitIndex)); - } - } else { - var offset = Math.floor(bitIndex / BitVector.packBits) - 1; - var localIndex = bitIndex % BitVector.packBits; - if(value) { - this.restOfBits[offset] |= (1 << localIndex); - } else { - this.restOfBits[offset] &= (~(1 << localIndex)); - } - } - }; - BitVector.prototype.map = function (fn) { - var k; - for(k = 0; k < BitVector.packBits; k++) { - if(k == this.bitCount) { - return; - } - if(((1 << k) & this.firstBits) != 0) { - fn(k); - } - } - if(this.restOfBits) { - var len; - var cumu = BitVector.packBits; - for(k = 0 , len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - for(var j = 0; j < BitVector.packBits; j++) { - if(((1 << j) & myBits) != 0) { - fn(cumu); - } - cumu++; - if(cumu == this.bitCount) { - return; - } - } - } - } - }; - BitVector.prototype.union = function (b) { - this.firstBits |= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits | bBits; - } - } - }; - BitVector.prototype.intersection = function (b) { - this.firstBits &= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits & bBits; - } - } - }; - BitVector.prototype.notEq = function (b) { - if(this.firstBits != b.firstBits) { - return true; - } - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - if(myBits != bBits) { - return true; - } - } - } - return false; - }; - BitVector.prototype.difference = function (b) { - var oldFirstBits = this.firstBits; - this.firstBits &= (~b.firstBits); - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] &= (~bBits); - } - } - }; - return BitVector; - })(); - TypeScript.BitVector = BitVector; - var BasicBlock = (function () { - function BasicBlock() { - this.predecessors = new Array(); - this.index = -1; - this.markValue = 0; - this.successors = new Array(); - this.useDef = null; - this.content = new TypeScript.ASTList(); - } - BasicBlock.prototype.marked = function (markBase) { - return this.markValue > markBase; - }; - BasicBlock.prototype.mark = function () { - this.markValue++; - }; - BasicBlock.prototype.addSuccessor = function (successor) { - this.successors[this.successors.length] = successor; - successor.predecessors[successor.predecessors.length] = this; - }; - return BasicBlock; - })(); - TypeScript.BasicBlock = BasicBlock; - var ControlFlowContext = (function () { - function ControlFlowContext(current, exit) { - this.current = current; - this.exit = exit; - this.entry = null; - this.unreachable = null; - this.noContinuation = false; - this.statementStack = new Array(); - this.currentSwitch = new Array(); - this.markBase = 0; - this.linearBBs = new Array(); - this.entry = this.current; - } - ControlFlowContext.prototype.walk = function (ast, parent) { - return this.walker.walk(ast, parent); - }; - ControlFlowContext.prototype.pushSwitch = function (bb) { - this.currentSwitch.push(bb); - }; - ControlFlowContext.prototype.popSwitch = function () { - return this.currentSwitch.pop(); - }; - ControlFlowContext.prototype.reportUnreachable = function (er) { - if(this.unreachable && (this.unreachable.length > 0)) { - var len = this.unreachable.length; - for(var i = 0; i < len; i++) { - var unreachableAST = this.unreachable[i]; - if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { - er.simpleError(unreachableAST, "unreachable code"); - } - } - } - }; - ControlFlowContext.prototype.printAST = function (ast, outfile) { - var printContext = new TypeScript.PrintContext(outfile, null); - printContext.increaseIndent(); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); - printContext.decreaseIndent(); - }; - ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { - var content = bb.content; - for(var i = 0, len = content.members.length; i < len; i++) { - var ast = content.members[i]; - this.printAST(ast, outfile); - } - }; - ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { - var markValue = this.markBase++; - var q = new Array(); - q[q.length] = this.entry; - while(q.length > 0) { - var bb = q.pop(); - if(!(bb.marked(markValue))) { - bb.mark(); - if(nodeFunc) { - nodeFunc(bb); - } - var succLen = bb.successors.length; - if(succLen > 0) { - if(preEdges) { - preEdges(); - } - for(var j = succLen - 1; j >= 0; j--) { - var successor = bb.successors[j]; - if(!(successor.marked(this.markBase))) { - if(edgeFunc) { - edgeFunc(bb, successor); - } - q[q.length] = successor; - } - } - if(postEdges) { - postEdges(); - } - } - } - } - }; - ControlFlowContext.prototype.useDef = function (er, funcSym) { - var _this = this; - var useDefContext = new UseDefContext(); - useDefContext.func = funcSym; - var useDefInit = function (bb) { - bb.useDef = new BBUseDefInfo(bb); - bb.useDef.initialize(useDefContext); - _this.linearBBs[_this.linearBBs.length] = bb; - }; - this.bfs(useDefInit, null, null, null); - var i, bbLen; - for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { - this.linearBBs[i].useDef.initializeGen(useDefContext); - this.linearBBs[i].useDef.initializeKill(useDefContext); - } - var changed = true; - while(changed) { - changed = false; - for(i = 0; i < bbLen; i++) { - changed = this.linearBBs[i].useDef.updateTop() || changed; - } - } - var top = this.entry.useDef.top; - top.map(function (index) { - var ast = useDefContext.uses[index]; - er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); - }); - }; - ControlFlowContext.prototype.print = function (outfile) { - var _this = this; - var index = 0; - var node = function (bb) { - if(bb.index < 0) { - bb.index = index++; - } - if(bb == _this.exit) { - outfile.WriteLine("Exit block with index " + bb.index); - } else { - outfile.WriteLine("Basic block with index " + bb.index); - _this.printBlockContent(bb, outfile); - } - }; - function preEdges() { - outfile.Write(" Branches to "); - } - function postEdges() { - outfile.WriteLine(""); - } - function edge(node1, node2) { - if(node2.index < 0) { - node2.index = index++; - } - outfile.Write(node2.index + " "); - } - this.bfs(node, edge, preEdges, postEdges); - if(this.unreachable != null) { - for(var i = 0, len = this.unreachable.length; i < len; i++) { - outfile.WriteLine("Unreachable basic block ..."); - this.printAST(this.unreachable[i], outfile); - } - } - }; - ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { - this.statementStack.push({ - stmt: stmt, - continueBB: continueBB, - breakBB: breakBB - }); - }; - ControlFlowContext.prototype.popStatement = function () { - return this.statementStack.pop(); - }; - ControlFlowContext.prototype.returnStmt = function () { - this.current.addSuccessor(this.exit); - this.setUnreachable(); - }; - ControlFlowContext.prototype.setUnreachable = function () { - this.current = null; - this.noContinuation = true; - }; - ControlFlowContext.prototype.addUnreachable = function (ast) { - if(this.unreachable === null) { - this.unreachable = new Array(); - } - this.unreachable[this.unreachable.length] = ast; - }; - ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { - var targetBB = null; - for(var i = 0, len = this.statementStack.length; i < len; i++) { - var targetInfo = this.statementStack[i]; - if(targetInfo.stmt == target) { - if(isContinue) { - targetBB = targetInfo.continueBB; - } else { - targetBB = targetInfo.breakBB; - } - break; - } - } - if(targetBB) { - this.current.addSuccessor(targetBB); - } - this.setUnreachable(); - }; - ControlFlowContext.prototype.addContent = function (ast) { - if(this.current) { - this.current.content.append(ast); - } - }; - return ControlFlowContext; - })(); - TypeScript.ControlFlowContext = ControlFlowContext; - var ResolutionDataCache = (function () { - function ResolutionDataCache() { - this.cacheSize = 16; - this.rdCache = []; - this.nextUp = 0; - for(var i = 0; i < this.cacheSize; i++) { - this.rdCache[i] = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: i - }; - } - } - ResolutionDataCache.prototype.getResolutionData = function () { - var rd = null; - if(this.nextUp < this.cacheSize) { - rd = this.rdCache[this.nextUp]; - } - if(rd == null) { - this.cacheSize++; - rd = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: this.cacheSize - }; - this.rdCache[this.cacheSize] = rd; - } - this.nextUp++; - return rd; - }; - ResolutionDataCache.prototype.returnResolutionData = function (rd) { - rd.actuals.length = 0; - rd.exactCandidates.length = 0; - rd.conversionCandidates.length = 0; - this.nextUp = rd.id; - }; - return ResolutionDataCache; - })(); - TypeScript.ResolutionDataCache = ResolutionDataCache; - var TypeFlow = (function () { - function TypeFlow(logger, initScope, parser, checker) { - this.logger = logger; - this.initScope = initScope; - this.parser = parser; - this.checker = checker; - this.thisFnc = null; - this.thisClassNode = null; - this.enclosingFncIsMethod = false; - this.arrayInterfaceType = null; - this.stringInterfaceType = null; - this.objectInterfaceType = null; - this.functionInterfaceType = null; - this.numberInterfaceType = null; - this.booleanInterfaceType = null; - this.iargumentsInterfaceType = null; - this.currentScript = null; - this.inImportTypeCheck = false; - this.inTypeRefTypeCheck = false; - this.inArrayElementTypeCheck = false; - this.resolutionDataCache = new ResolutionDataCache(); - this.nestingLevel = 0; - this.inSuperCall = false; - this.checker.typeFlow = this; - this.scope = this.initScope; - this.globalScope = this.initScope; - this.doubleType = this.checker.numberType; - this.booleanType = this.checker.booleanType; - this.stringType = this.checker.stringType; - this.anyType = this.checker.anyType; - this.regexType = this.anyType; - this.nullType = this.checker.nullType; - this.voidType = this.checker.voidType; - this.arrayAnyType = this.checker.makeArrayType(this.anyType); - } - TypeFlow.prototype.initLibs = function () { - var arraySym = this.globalScope.find("Array", false, true); - if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { - this.arrayInterfaceType = (arraySym).type; - } - var stringSym = this.globalScope.find("String", false, true); - if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { - this.stringInterfaceType = (stringSym).type; - } - var objectSym = this.globalScope.find("Object", false, true); - if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { - this.objectInterfaceType = (objectSym).type; - } - var fnSym = this.globalScope.find("Function", false, true); - if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { - this.functionInterfaceType = (fnSym).type; - } - var numberSym = this.globalScope.find("Number", false, true); - if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { - this.numberInterfaceType = (numberSym).type; - } - var booleanSym = this.globalScope.find("Boolean", false, true); - if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { - this.booleanInterfaceType = (booleanSym).type; - } - var regexSym = this.globalScope.find("RegExp", false, true); - if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { - this.regexType = (regexSym).type; - } - }; - TypeFlow.prototype.cast = function (ast, type) { - return this.castWithCoercion(ast, type, true, false); - }; - TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { - if(applyCoercion) { - if(type == null) { - ast.type = this.anyType; - } else { - if(type.isClass()) { - ast.type = type.instanceType; - } else { - ast.type = type; - } - } - } - return ast; - } else { - this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); - return ast; - } - }; - TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { - var prevScope = this.scope; - this.scope = enclosingScope; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var svThisClassNode = this.thisClassNode; - var svCurrentModDecl = this.checker.currentModDecl; - var prevMethodStatus = this.enclosingFncIsMethod; - var container = this.scope.container; - var fnc = null; - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - if(fnc == null) { - this.enclosingFncIsMethod = typeSym.isMethod; - fnc = container.declAST; - } - } - if(type.isClass()) { - this.thisType = type.instanceType; - if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { - this.thisClassNode = typeSym.declAST; - } - break; - } - if(type.isModuleType()) { - this.checker.currentModDecl = typeSym.declAST; - break; - } - } - container = container.container; - } - this.thisFnc = fnc; - var updated = this.typeCheck(ast); - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.thisClassNode = svThisClassNode; - this.checker.currentModDecl = svCurrentModDecl; - this.enclosingFncIsMethod = prevMethodStatus; - this.scope = prevScope; - return updated; - }; - TypeFlow.prototype.typeCheck = function (ast) { - if(ast) { - return ast.typeCheck(this); - } else { - return null; - } - }; - TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { - if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { - this.inScopeTypeCheckBoundDecl(ast); - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if(funcDecl.isAccessor()) { - this.typeCheckFunction(funcDecl); - } - } - } - }; - TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { - var sym = varDecl.sym; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevLocationInfo = this.checker.locationInfo; - if(sym && sym.container) { - var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - this.thisFnc = sym.container.declAST; - } - if(instanceScope) { - var prevScope = this.scope; - this.scope = instanceScope; - var container = sym.container; - if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[sym.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - this.enclosingFncIsMethod = typeSym.isMethod; - } - if(type.isClass()) { - this.thisType = type.instanceType; - break; - } - } - container = container.container; - } - this.typeCheckBoundDecl(varDecl); - this.scope = prevScope; - } - } - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.checker.locationInfo = prevLocationInfo; - this.enclosingFncIsMethod = prevMethodStatus; - }; - TypeFlow.prototype.resolveBoundDecl = function (varDecl) { - if(varDecl.typeExpr) { - if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { - this.typeCheck(varDecl.typeExpr); - } - varDecl.type = varDecl.typeExpr.type; - if(varDecl.sym) { - varDecl.sym.setType(varDecl.type); - } - } else { - if(varDecl.init == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - if(varDecl.sym) { - if(varDecl.sym.isType()) { - var tsym = varDecl.sym; - if(tsym.isMethod) { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); - return; - } else { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); - return; - } - } - varDecl.sym.setType(varDecl.type); - } - } - } - }; - TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { - var _this = this; - var infSym = varDecl.sym; - if(infSym == null) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = this.checker.widenType(varDecl.init.type); - } else { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - } - } else { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - infSym.setType(this.anyType); - } else { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(infSym); - var resolved = false; - if(varDecl.type == null) { - if(varDecl.typeExpr) { - this.resolveBoundDecl(varDecl); - resolved = true; - varDecl.type = varDecl.typeExpr.type; - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } - } - if(varDecl.init) { - var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); - var prevScope = this.scope; - var applyTargetType = !varDecl.init.isParenthesized; - if(isLocalStatic) { - this.scope = varDecl.sym.container.getType().memberScope; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { - TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { - if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; - } - walker.options.goChildren = false; - } - return ast; - }); - } - this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); - this.scope = prevScope; - if(varDecl.type) { - var preserveScope = false; - var preservedContainedScope = null; - if(varDecl.init.type) { - preservedContainedScope = varDecl.init.type.containedScope; - preserveScope = true; - if(varDecl.init.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - } - } - varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && varDecl.init.type.containedScope == null) { - varDecl.init.type.containedScope = preservedContainedScope; - } - } else { - varDecl.type = this.checker.widenType(varDecl.init.type); - if(varDecl.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - varDecl.type = this.anyType; - } - } - infSym.setType(varDecl.type); - } else { - if(!resolved) { - this.resolveBoundDecl(varDecl); - } - } - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else { - if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = infSym.getType(); - varDecl.init = this.cast(varDecl.init, varDecl.type); - } - } - } - } - } - if(varDecl.id && varDecl.sym) { - varDecl.id.sym = varDecl.sym; - } - if(varDecl.sym && varDecl.sym.container) { - this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { - return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); - }); - } - return varDecl; - }; - TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); - } else { - this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); - } - } else { - this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); - } - }; - TypeFlow.prototype.typeCheckSuper = function (ast) { - if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { - ast.type = this.thisType.baseClass(); - } else { - if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - var enclosingFnc = this.thisFnc.enclosingFnc; - while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - enclosingFnc = enclosingFnc.enclosingFnc; - } - if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { - ast.type = this.thisType.baseClass(); - enclosingFnc.setHasSuperReferenceInFatArrowFunction(); - return ast; - } - } - ast.type = this.anyType; - this.checker.errorReporter.invalidSuperReference(ast); - } - return ast; - }; - TypeFlow.prototype.typeCheckThis = function (ast) { - ast.type = this.anyType; - var illegalThisRef = false; - if(this.thisFnc == null) { - if(this.thisType) { - if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { - illegalThisRef = true; - } else { - ast.type = this.thisType; - } - } else { - if(this.checker.currentModDecl) { - this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); - } - } - } else { - if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { - illegalThisRef = true; - } - if(this.thisFnc.isMethod() || this.thisFnc.isConstructor || this.thisFnc.isTargetTypedAsMethod) { - if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - if(this.thisFnc.boundToProperty) { - var container = this.thisFnc.boundToProperty.sym.container; - if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - (container.declAST).setHasSelfReference(); - } - } else { - var encFnc = this.thisFnc.enclosingFnc; - var firstEncFnc = encFnc; - while(encFnc) { - if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { - illegalThisRef = true; - } - if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { - encFnc.setHasSelfReference(); - break; - } - encFnc = encFnc.enclosingFnc; - } - if(!encFnc && firstEncFnc) { - encFnc = firstEncFnc; - encFnc.setHasSelfReference(); - } else { - if(!encFnc) { - if(this.thisClassNode) { - (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; - } else { - if(this.checker.currentModDecl) { - this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; - } else { - this.checker.mustCaptureGlobalThis = true; - } - } - } - } - if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(illegalThisRef) { - this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); - } - return ast; - }; - TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - this.inScopeTypeCheckDecl(infSym.declAST); - } - if(!this.checker.styleSettings.innerScopeDeclEscape) { - if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { - if(this.nestingLevel < (infSym.declAST).nestingLevel) { - this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); - } - } - } - } - ast.type = symbol.getType(); - if(!symbol.writeable()) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } - } else { - if(symbol.isType()) { - ast.type = symbol.getType(); - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } else { - ast.type = this.anyType; - this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); - } - } - }; - TypeFlow.prototype.typeCheckName = function (ast) { - var _this = this; - var identifier = ast; - if(this.checker.inWith) { - identifier.type = this.anyType; - } else { - var typespace = this.inTypeRefTypeCheck; - var idText = identifier.text; - var originalIdText = idText; - var isDynamicModuleName = TypeScript.isQuoted(identifier.text); - var symbol = this.scope.find(idText, false, typespace); - if(symbol == null && isDynamicModuleName) { - symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { - return _this.scope.find(id, false, typespace); - }); - } - if(!symbol) { - if(!identifier.isMissing()) { - this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); - } - identifier.type = this.anyType; - } else { - if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { - var symType = symbol.getType(); - if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; - } - } - } - if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - (symbol.declAST).signature.returnType.type = this.anyType; - } - this.setTypeFromSymbol(ast, symbol); - identifier.sym = symbol; - if(this.thisFnc) { - if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { - this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; - } - } - } - } - return ast; - }; - TypeFlow.prototype.typeCheckScript = function (script) { - this.checker.locationInfo = script.locationInfo; - this.scope = this.checker.globalScope; - if(!script.topLevelMod) { - this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); - } - this.currentScript = script; - script.bod = this.typeCheck(script.bod); - this.currentScript = null; - return script; - }; - TypeFlow.prototype.typeCheckBitNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return unex; - }; - TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return ast; - }; - TypeFlow.prototype.typeCheckLogNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.booleanType; - return unex; - }; - TypeFlow.prototype.astIsWriteable = function (ast) { - return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); - }; - TypeFlow.prototype.typeCheckIncOrDec = function (ast) { - var unex = ast; - var lval = unex.operand; - if(!this.astIsWriteable(unex)) { - this.checker.errorReporter.valueCannotBeModified(unex); - unex.type = this.doubleType; - } else { - unex = this.typeCheckUnaryNumberOperator(ast); - if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { - this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); - } - } - return unex; - }; - TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { - var binex = ast; - var resultType = null; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { - resultType = this.doubleType; - } else { - if((leftType == this.booleanType) && (rightType == this.booleanType)) { - resultType = this.booleanType; - } else { - if(leftType == this.anyType) { - if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { - resultType = this.anyType; - } - } else { - if(rightType == this.anyType) { - if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { - resultType = this.anyType; - } - } - } - } - } - if(resultType == null) { - resultType = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = resultType; - return binex; - }; - TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - if(leftType == null || rightType == null) { - this.checker.errorReporter.simpleError(binex, "Could not typecheck arithmetic operation. Possible recursive typecheck error?"); - binex.type = this.anyType; - return binex; - } - var nodeType = binex.nodeType; - if(this.checker.isNullOrUndefinedType(leftType)) { - leftType = rightType; - } - if(this.checker.isNullOrUndefinedType(rightType)) { - rightType = leftType; - } - leftType = this.checker.widenType(leftType); - rightType = this.checker.widenType(rightType); - if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { - if(leftType == this.checker.stringType || rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else { - if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else { - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } - } - } - } else { - if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else { - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } - } - } - return binex; - }; - TypeFlow.prototype.typeCheckDotOperator = function (ast) { - var binex = ast; - var leftIsFnc = false; - binex.operand1 = this.typeCheck(binex.operand1); - var leftType = binex.operand1.type; - var leftScope = null; - if(leftType) { - if(leftType == this.anyType) { - binex.type = this.anyType; - return binex; - } else { - if(leftType == this.stringType) { - if(this.stringInterfaceType) { - leftScope = this.stringInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if(leftType == this.doubleType) { - if(this.numberInterfaceType) { - leftScope = this.numberInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if(leftType == this.booleanType) { - if(this.booleanInterfaceType) { - leftScope = this.booleanInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if((leftType.call || leftType.construct) && leftType.members == null) { - if(this.functionInterfaceType) { - leftScope = this.functionInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - if(leftType.elementType) { - if(this.arrayInterfaceType) { - var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); - leftScope = arrInstType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - leftScope = leftType.memberScope; - } - } - } - } - } - } - } - if(leftScope == null) { - this.checker.errorReporter.expectedClassOrInterface(binex); - binex.type = this.anyType; - } else { - var propertyName = binex.operand2; - var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; - var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); - if(!symbol) { - if(this.objectInterfaceType && leftType) { - if(leftType.isReferenceType()) { - symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - if(!symbol) { - if(this.functionInterfaceType && (leftType.call || leftType.construct)) { - symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - } - } - } - if(!symbol || (!symbol.visible(leftScope, this.checker))) { - binex.type = this.anyType; - if(symbol == null) { - this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); - } else { - if(!this.inTypeRefTypeCheck) { - this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); - } - } - } else { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - this.inScopeTypeCheckDecl(infSym.declAST); - } - } - } - propertyName.sym = symbol; - binex.type = symbol.getType(); - } - } - if(binex.type == null) { - binex.type = this.anyType; - } - return binex; - }; - TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckAsgOperator = function (ast) { - var binex = ast; - var applyTargetType = !binex.operand2.isParenthesized; - binex.operand1 = this.typeCheck(binex.operand1); - this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(!(this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(binex.operand1.nodeType == TypeScript.NodeType.Call) { - var callEx = binex.operand1; - } - var preserveScope = false; - var preservedContainedScope = null; - if(binex.operand2.type) { - preservedContainedScope = binex.operand2.type.containedScope; - preserveScope = true; - } - binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && binex.operand2.type.containedScope == null) { - binex.operand2.type.containedScope = preservedContainedScope; - } - binex.type = rightType; - return binex; - }; - TypeFlow.prototype.typeCheckIndex = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!this.checker.styleSettings.literalSubscript) { - if(binex.operand2.nodeType == TypeScript.NodeType.QString) { - this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); - } - } - var objExprType = binex.operand1.type; - var indexExprType = binex.operand2.type; - if(objExprType.elementType) { - if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { - binex.type = objExprType.elementType; - } else { - if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } - } else { - if(objExprType.index) { - if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - var sig = this.resolveOverload(ast, objExprType.index); - if(sig) { - binex.type = sig.returnType.type; - } else { - binex.type = this.checker.anyType; - } - } else { - if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } - } else { - if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } - } - return binex; - }; - TypeFlow.prototype.typeCheckInOperator = function (binex) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { - this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckShift = function (binex, assignment) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); - binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); - if(assignment && (!(this.astIsWriteable(binex.operand1)))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - binex.type = this.doubleType; - return binex; - }; - TypeFlow.prototype.typeCheckQMark = function (trinex) { - trinex.operand1 = this.typeCheck(trinex.operand1); - trinex.operand2 = this.typeCheck(trinex.operand2); - trinex.operand3 = this.typeCheck(trinex.operand3); - var leftType = trinex.operand2.type; - var rightType = trinex.operand3.type; - if(leftType == rightType) { - trinex.type = leftType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - trinex.type = rightType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - trinex.type = leftType; - } else { - trinex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); - } - } - } - return trinex; - }; - TypeFlow.prototype.addFormals = function (container, signature, table) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var symbol = signature.parameters[i]; - symbol.container = container; - table.add(symbol.name, symbol); - } - }; - TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { - var len = vars.members.length; - var hasArgsDef = false; - for(var i = 0; i < len; i++) { - var local = vars.members[i]; - if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = null; - if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { - local.varFlags |= TypeScript.VarFlags.LocalStatic; - varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); - } else { - varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - } - varSym.transferVarFlags(local.varFlags); - localVar.symbol = varSym; - varSym.declAST = local; - localVar.typeLink.ast = local.typeExpr; - this.checker.resolveTypeLink(scope, localVar.typeLink, false); - if((local.type == null) && (local.init == null)) { - local.type = this.anyType; - } - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - if(local.id.text == "arguments") { - hasArgsDef = true; - } - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - if(!isModContainer) { - if(!hasArgsDef) { - var argLoc = new TypeScript.ValueLocation(); - argLoc.typeLink = new TypeScript.TypeLink(); - var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); - if(!this.iargumentsInterfaceType) { - var argumentsSym = scope.find("IArguments", false, true); - if(argumentsSym) { - argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; - this.iargumentsInterfaceType = argumentsSym.getType(); - } else { - this.iargumentsInterfaceType = this.anyType; - } - } - argLoc.typeLink.type = this.iargumentsInterfaceType; - table.add("arguments", theArgSym); - } - } - }; - TypeFlow.prototype.addConstructorLocalArgs = function (container, args, table, isClass) { - if(args) { - var len = args.members.length; - for(var i = 0; i < len; i++) { - var local = args.members[i]; - if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - this.resolveBoundDecl(local); - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - varSym.declAST = local; - localVar.symbol = varSym; - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - } - }; - TypeFlow.prototype.checkInitSelf = function (funcDecl) { - if(!funcDecl.isMethod()) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if(sym.isInstanceProperty()) { - return true; - } - } - } - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - for(var j = 0; j < fnsLen; j++) { - var fn = fns.members[j]; - if(this.checkInitSelf(fn)) { - return true; - } - } - return false; - }; - TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { - TypeScript.instanceFilter.reset(); - if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); - } - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); - } - } - }; - TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { - var allReturnsAreVoid = true; - if(funcDecl.signature.returnType.type == null) { - var preFindReturnExpressionTypes = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: { - go = false; - break; - - } - case TypeScript.NodeType.Return: { - var returnStmt = ast; - if(returnStmt.returnExpression) { - allReturnsAreVoid = false; - go = false; - } - - } - default: { - break; - - } - } - walker.options.goChildren = go; - walker.options.goNextSibling = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); - } - return allReturnsAreVoid; - }; - TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { - var foundSuper = false; - var preFindSuperCall = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: { - go = false; - break; - - } - case TypeScript.NodeType.Call: { - var call = ast; - if(call.target.nodeType == TypeScript.NodeType.Super) { - go = false; - foundSuper = true; - break; - } - break; - - } - default: { - break; - - } - } - walker.options.goChildren = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); - return foundSuper; - }; - TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { - var baseSymbol = bases.members[i].type.symbol; - var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var baseListTypeString = extendsList ? "extends" : "implements"; - var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module "; - baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; - } else { - baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; - } - this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); - }; - TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { - var _this = this; - if(bases) { - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { - continue; - } - this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { - return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); - }); - } - } - }; - TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { - var externalModuleSymbol = null; - var declSymbolPath = null; - if(typeSymbol.isExternallyVisible(this.checker)) { - var typeSymbolPath = typeSymbol.pathToRoot(); - declSymbolPath = declSymbol.pathToRoot(); - var typeSymbolLength = typeSymbolPath.length; - var declSymbolPathLength = declSymbolPath.length; - if(typeSymbolLength > 0) { - if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; - } else { - if(typeSymbolLength > 1) { - if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; - } - } - } - } - if(externalModuleSymbol == null) { - return; - } - } - var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); - if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { - return; - } - var checkVisibilitySymbol = declSymbol; - var varDecl = declSymbol.getVarDeclFromSymbol(); - if(varDecl) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { - return; - } else { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - checkVisibilitySymbol = declSymbol.container; - } - } - } - if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { - var privateSymbolName = typeSymbol.name; - if(externalModuleSymbol != null) { - var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); - if(prettyName != null) { - this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); - return; - } else { - privateSymbolName = externalModuleSymbol.prettyName; - } - } - errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); - } - }; - TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { - var _this = this; - if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { - return; - } - if(type.isArray()) { - return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); - } - if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { - return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); - } - if(type.members) { - type.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); - } - }, null); - } - this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); - }; - TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { - if(sgroup) { - var len = sgroup.signatures.length; - for(var i = 0; i < sgroup.signatures.length; i++) { - var signature = sgroup.signatures[i]; - if(len > 1 && signature == sgroup.definitionSignature) { - continue; - } - if(signature.returnType) { - this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - var param = signature.parameters[j]; - this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); - } - } - } - }; - TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(funcDecl.isConstructor) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(isSetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(!isGetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); - } - } - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); - } else { - if(!funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); - } - } - } - } - }; - TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(isGetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); - } else { - if(!isSetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); - } - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); - } else { - if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); - } else { - if(funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); - } else { - this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); - } - } - } - } - }; - TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { - var reportOnFuncDecl = false; - if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); - } - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); - } else { - reportOnFuncDecl = true; - } - } - if(reportOnFuncDecl) { - this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); - } - }; - TypeFlow.prototype.typeCheckFunction = function (funcDecl) { - var _this = this; - this.nestingLevel = 0; - var fnType = funcDecl.type; - var fgSym = fnType.symbol; - var signature = funcDecl.signature; - if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { - return funcDecl; - } else { - if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { - signature.returnType.type = this.voidType; - return funcDecl; - } else { - if(funcDecl.returnTypeAnnotation == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - } - return funcDecl; - } - } - } - signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(signature); - var prevScope = this.scope; - var prevFnc = this.thisFnc; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevClassNode = this.thisClassNode; - this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; - this.thisFnc = funcDecl; - var container = funcDecl.type.symbol; - var prevThisType = this.thisType; - var prevLocationInfo = this.checker.locationInfo; - var funcTable = null; - var acceptedContextualType = false; - var targetParams = null; - var targetReturnType = null; - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; - var prevModDecl = this.checker.currentModDecl; - if(funcDecl.isConstructor && !funcDecl.isOverload) { - if(fnType.instanceType == null) { - this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); - return funcDecl; - } - this.scope = fnType.instanceType.constructorScope; - var ssb = this.scope; - funcTable = ssb.valueMembers.allMembers; - } else { - if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { - funcTable = funcDecl.symbols; - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { - this.scope = fnType.containedScope; - } - } else { - if(funcDecl.bod) { - this.scope = fnType.containedScope; - } - var ssb = this.scope; - if(ssb && ssb.valueMembers) { - funcTable = ssb.valueMembers.allMembers; - } - } - } - if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); - var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); - } else { - if(hasBaseType) { - if(superCallMustBeFirst) { - if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { - this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); - } - } else { - if(!this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); - } - } - } - } - } - if(funcDecl.isMethod() && funcDecl.type.enclosingType) { - var enclosingClassNode = null; - if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; - } else { - if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { - enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; - } - } - if(enclosingClassNode) { - this.thisClassNode = enclosingClassNode; - } - } - if(fnType.enclosingType) { - ; ; - var enclosingSym = fnType.symbol.container; - if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { - enclosingSym = enclosingSym.container; - } - if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { - this.checker.currentModDecl = enclosingSym.declAST; - } - } - if(funcDecl.unitIndex > 0) { - if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - } - if(fnType.enclosingType) { - this.thisType = fnType.enclosingType; - } else { - this.thisType = prevThisType; - } - var paramLen = signature.parameters.length; - if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { - var tmpParamScope = this.scope; - var ssb = this.scope; - if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { - if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { - var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); - if(considerSym && considerSym.declAST && considerSym.declAST.type) { - this.checker.setContextualType(considerSym.declAST.type, false); - } - } - if(this.checker.hasTargetType()) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var candidateType = candidateTypeContext.contextualType; - if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - candidateTypeContext.targetSig = candidateSigs.signatures[0]; - var candidateParams = candidateTypeContext.targetSig.parameters; - targetParams = candidateParams; - targetReturnType = candidateTypeContext.targetSig.returnType.type; - if(candidateTypeContext.targetSig.declAST) { - if(candidateTypeContext.targetSig.declAST.isConstructor) { - funcDecl.isTargetTypedAsMethod = true; - } else { - if(candidateTypeContext.targetSig.declAST.isMethod()) { - funcDecl.isTargetTypedAsMethod = true; - } - } - } - fgSym.type = candidateTypeContext.contextualType; - acceptedContextualType = true; - } else { - if(candidateType && funcDecl.isAccessor()) { - accessorType = candidateType; - candidateTypeContext.targetAccessorType = accessorType; - } else { - this.checker.killCurrentContextualType(); - } - } - } - } - var paramTable = ssb.valueMembers; - this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); - for(var p = 0; p < paramLen; p++) { - var symbol = signature.parameters[p]; - var ast = symbol.declAST; - if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; - ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); - ast.sym.setType(ast.type); - (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else { - this.typeCheck(ast); - } - if(isSetter && accessorType) { - ast = this.cast(ast, accessorType); - } - symbol.container = container; - this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); - }); - paramTable.publicMembers.add(symbol.name, symbol); - } - this.scope = tmpParamScope; - } else { - this.typeCheck(funcDecl.arguments); - for(var p = 0; p < paramLen; p++) { - signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; - this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); - }); - if((funcDecl.arguments.members[p]).parameterPropertySym) { - (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); - } - } - if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { - if(!paramLen || paramLen > 1) { - this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); - } else { - if(funcDecl.arguments.members[0].type == this.checker.numberType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; - } else { - if(funcDecl.arguments.members[0].type == this.checker.stringType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; - } else { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); - } - } - } - } - } - if(funcDecl.bod && (!funcDecl.isSignature())) { - if(!(funcDecl.isConstructor)) { - this.addFormals(container, signature, funcTable); - } else { - this.addConstructorLocalArgs(funcDecl.type.symbol, funcDecl.arguments, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); - if(this.thisClassNode && this.thisClassNode.extendsList) { - var tmpScope = this.scope; - var funcMembers = new TypeScript.ScopedMembers(funcTable); - this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { - return sym.kind() == TypeScript.SymbolKind.Parameter; - }); - this.typeCheckBaseCalls(this.thisClassNode.extendsList); - this.scope = tmpScope; - } - } - var prevMod = this.checker.currentModDecl; - if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { - this.checker.currentModDecl = funcDecl.type.symbol.declModule; - } - if(acceptedContextualType) { - this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); - } - this.typeCheck(funcDecl.bod); - if(acceptedContextualType) { - this.checker.unsetContextualType(); - } - this.checker.currentModDecl = prevMod; - if(this.checker.checkControlFlow) { - var cfg = funcDecl.buildControlFlow(); - if(this.checker.printControlFlowGraph) { - cfg.print(this.checker.errorReporter.outfile); - } - cfg.reportUnreachable(this.checker.errorReporter); - if(this.checker.checkControlFlowUseDef) { - cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); - } - } - if(funcDecl.isConstructor) { - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - var freeVars; - var sym; - var j = 0; - for(; j < fnsLen; j++) { - var fn = fns.members[j]; - if(!fn.isSignature()) { - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { - this.checkPromoteFreeVars(fn, funcDecl.type.symbol); - } - } - } - } - } - this.scope = prevScope; - this.thisFnc = prevFnc; - this.thisClassNode = prevClassNode; - this.enclosingFncIsMethod = prevMethodStatus; - this.thisType = prevThisType; - this.checker.locationInfo = prevLocationInfo; - this.checker.currentModDecl = prevModDecl; - signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - if(funcDecl.returnTypeAnnotation) { - this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); - if(signature.returnType.type == null) { - this.checker.resolveTypeLink(this.scope, signature.returnType, false); - } - } else { - if(targetReturnType) { - signature.returnType.type = targetReturnType; - } - } - if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { - var collection = { - getLength: function () { - return funcDecl.returnStatementsWithExpressions.length; - }, - setTypeAtIndex: function (index, type) { - funcDecl.returnStatementsWithExpressions[index].type = type; - }, - getTypeAtIndex: function (index) { - return funcDecl.returnStatementsWithExpressions[index].type; - } - }; - var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; - bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); - if(bestCommonReturnType) { - signature.returnType.type = this.checker.widenType(bestCommonReturnType); - } else { - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); - } - signature.returnType.type = this.anyType; - } - } - var onlyHasThrow = false; - if(signature.returnType.type == null) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - } else { - signature.returnType.type = this.voidType; - } - } else { - if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { - signature.returnType.type = this.anyType; - } else { - if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { - if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); - if(!onlyHasThrow) { - this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); - } - } - this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { - return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); - }); - } - } - } - if(funcDecl.accessorSymbol) { - var accessorType = funcDecl.accessorSymbol.getType(); - if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); - } - if(accessorType) { - if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { - this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); - } - } else { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - funcDecl.accessorSymbol.setType(signature.returnType.type); - } else { - if(funcDecl.arguments.members.length != 1) { - this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); - } else { - funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); - } - } - } - } - this.typeCheckOverloadSignatures(fnType, funcDecl); - return funcDecl; - }; - TypeFlow.prototype.typeCheckBases = function (type) { - var seenInterface = false; - var bases = type.extendsList; - var baseLinks = type.extendsTypeLinks; - if(bases) { - var len = bases.length; - if(len > 0) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseType; - } - for(var i = 0; i < len; i++) { - if(bases[i] == this.checker.anyType) { - baseLinks[i].type = null; - var oldErrors = this.checker.errorReporter.getCapturedErrors(); - TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); - this.checker.errorReporter.pushToErrorSink = true; - bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); - this.checker.errorReporter.pushToErrorSink = false; - this.checker.errorReporter.freeCapturedErrors(); - } - var base = bases[i]; - var baseRef = baseLinks[i].ast; - var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; - if(baseTypeOfObject) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; - } - if(base.isClassInstance()) { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - if(seenInterface) { - this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); - } - } - } else { - if(base.isModuleType()) { - this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); - } else { - if(base.members) { - if(!seenInterface) { - seenInterface = true; - } - } else { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); - } - break; - } - } - } - } - } - }; - TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { - var instanceType = implementingType.getInstanceType(); - if(instanceType.implementsList) { - var len = instanceType.implementsList.length; - for(var i = 0; i < len; i++) { - var interfaceType = instanceType.implementsList[i]; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { - var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); - } else { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); - } - } - } - } - }; - TypeFlow.prototype.typeCheckBaseCalls = function (bases) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.typeCheckNew(baseExpr); - } - } - }; - TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { - var _this = this; - if(type) { - if(type.members) { - type.members.publicMembers.map(function (key, s, c) { - var sym = s; - var dup = names.lookup(sym.name); - if(dup) { - if(checkUnique) { - _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); - } - } else { - names.add(sym.name, sym); - } - }, null); - } - if(type.extendsList) { - var len = type.extendsList.length; - for(var i = 0; i < len; i++) { - if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { - this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); - } - } - } - } - }; - TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { - var _this = this; - var instanceType = derivedType.getInstanceType(); - if(instanceType.extendsList == null) { - return; - } - var len = instanceType.extendsList.length; - if(len > 0) { - var names = new TypeScript.StringHashTable(); - if(instanceType.isClassInstance()) { - for(var i = 0; i < len; i++) { - this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); - } - } - if(instanceType.members) { - instanceType.members.publicMembers.map(function (key, s, c) { - var sym = s; - for(var j = 0; j < len; j++) { - var base = instanceType.extendsList[j]; - if(base.memberScope == null) { - _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); - } else { - var bSym = base.memberScope.find(sym.name, false, false); - if(bSym) { - var aType = sym.getType(); - var bType = bSym.getType(); - if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); - } else { - if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); - } - } - } - } - } - }, null); - } - } - }; - TypeFlow.prototype.typeCheckClass = function (classDecl) { - var typeSymbol = classDecl.type.symbol; - if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { - return classDecl; - } else { - if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - return classDecl; - } else { - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(typeSymbol); - } - } - var prevScope = this.scope; - var svClassNode = this.thisClassNode; - this.thisClassNode = classDecl; - var classType = classDecl.type; - this.typeCheckBases(classType.instanceType); - this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); - this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); - var prevThisType = this.thisType; - this.thisType = classType.instanceType; - this.scope = classType.instanceType.containedScope; - if(classDecl.constructorDecl) { - this.scope = classType.instanceType.constructorScope; - var ssb = this.scope; - var funcTable = ssb.valueMembers.allMembers; - this.addConstructorLocalArgs(classDecl.constructorDecl.type.symbol, classDecl.constructorDecl.arguments, funcTable, true); - } - this.typeCheck(classDecl.members); - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - this.checkBaseTypeMemberInheritance(classType, classDecl); - this.checkMembersImplementInterfaces(classType); - this.typeCheckOverloadSignatures(classType, classDecl); - this.typeCheckOverloadSignatures(classType.instanceType, classDecl); - if(!classDecl.constructorDecl) { - if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { - TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); - } - } - this.thisType = prevThisType; - this.thisClassNode = svClassNode; - this.scope = prevScope; - return classDecl; - }; - TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { - if(type.call) { - type.call.typeCheck(this.checker, ast, type.construct != null); - } - if(type.construct) { - type.construct.typeCheck(this.checker, ast, false); - } - if(type.index) { - type.index.typeCheck(this.checker, ast, false); - } - }; - TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { - this.typeCheckBases(interfaceDecl.type); - this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); - this.typeCheck(interfaceDecl.members); - this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); - if(interfaceDecl.extendsList) { - for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { - if(interfaceDecl.extendsList.members[i].type.call) { - if(interfaceDecl.type.call) { - interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); - } else { - interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; - } - } - if(interfaceDecl.extendsList.members[i].type.construct) { - if(interfaceDecl.type.construct) { - interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); - } else { - interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; - } - } - if(interfaceDecl.extendsList.members[i].type.index) { - if(interfaceDecl.type.index) { - interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); - } else { - interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; - } - } - } - } - return interfaceDecl; - }; - TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { - var mod = importDecl.alias.type; - var sym = null; - var prevInImportTC = this.inImportTypeCheck; - this.inImportTypeCheck = true; - this.typeCheck(importDecl.alias); - mod = importDecl.alias.type; - if(mod == null) { - this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); - mod = this.checker.anyType; - (importDecl.id.sym).type = mod; - } - importDecl.id.type = mod; - sym = mod.symbol; - if(!mod.isModuleType()) { - this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); - } else { - sym.type = mod; - if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { - this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); - } - (importDecl.id.sym).type = mod; - if(mod.symbol && mod.symbol.declAST) { - (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - } - } - this.inImportTypeCheck = prevInImportTC; - return importDecl; - }; - TypeFlow.prototype.typeCheckModule = function (moduleDecl) { - if(!moduleDecl.mod) { - return moduleDecl; - } - if(this.currentScript) { - this.currentScript.requiresGlobal = true; - } - var mod = moduleDecl.mod; - var sym = null; - var prevScope = this.scope; - var prevThisType = this.thisType; - var prevCurrentModDecl = this.checker.currentModDecl; - this.checker.currentModDecl = moduleDecl; - this.thisType = null; - this.scope = mod.containedScope; - this.typeCheck(moduleDecl.members); - sym = mod.symbol; - this.checker.currentModDecl = prevCurrentModDecl; - this.thisType = prevThisType; - this.scope = prevScope; - moduleDecl.type = mod; - if(sym) { - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - } - return moduleDecl; - }; - TypeFlow.prototype.typeCheckFor = function (forStmt) { - forStmt.init = this.typeCheck(forStmt.init); - this.nestingLevel++; - forStmt.cond = this.typeCheck(forStmt.cond); - this.typeCheckCondExpr(forStmt.cond); - forStmt.incr = this.typeCheck(forStmt.incr); - this.nestingLevel--; - forStmt.body = this.typeCheck(forStmt.body); - this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); - forStmt.type = this.voidType; - return forStmt; - }; - TypeFlow.prototype.typeCheckWith = function (withStmt) { - if(this.checker.errorsOnWith) { - this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); - } - withStmt.expr = this.typeCheck(withStmt.expr); - this.checker.inWith = true; - withStmt.body = this.typeCheck(withStmt.body); - this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); - this.checker.inWith = false; - return withStmt; - }; - TypeFlow.prototype.typeCheckForIn = function (forInStmt) { - forInStmt.obj = this.typeCheck(forInStmt.obj); - forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); - if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = forInStmt.lval; - if(varDecl.typeExpr) { - this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); - } - if(varDecl.sym) { - varDecl.sym.setType(this.checker.stringType); - } - } - forInStmt.body = this.typeCheck(forInStmt.body); - this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); - return forInStmt; - }; - TypeFlow.prototype.typeCheckWhile = function (whileStmt) { - whileStmt.cond = this.typeCheck(whileStmt.cond); - this.typeCheckCondExpr(whileStmt.cond); - whileStmt.body = this.typeCheck(whileStmt.body); - this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); - whileStmt.type = this.voidType; - return whileStmt; - }; - TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { - doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); - this.typeCheckCondExpr(doWhileStmt.cond); - doWhileStmt.body = this.typeCheck(doWhileStmt.body); - this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); - doWhileStmt.type = this.voidType; - return doWhileStmt; - }; - TypeFlow.prototype.typeCheckCondExpr = function (cond) { - if(this.checker.styleSettings.assignmentInCond) { - if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { - this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); - } - } - }; - TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { - if(this.checker.styleSettings.blockInCompoundStmt && stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); - } - } - }; - TypeFlow.prototype.typeCheckIf = function (ifStmt) { - ifStmt.cond = this.typeCheck(ifStmt.cond); - this.typeCheckCondExpr(ifStmt.cond); - ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); - ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); - this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); - this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); - ifStmt.type = this.voidType; - return ifStmt; - }; - TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { - if(!funcDecl.isAccessor()) { - return null; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - return funcDecl.type.call.signatures[0].returnType.type; - } else { - return funcDecl.type.call.signatures[0].parameters[0].getType(); - } - }; - TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { - var resultType = new TypeScript.Type(); - resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); - resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); - var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); - aggScope.addParentScope(resultType.memberScope); - aggScope.addParentScope(this.scope); - resultType.containedScope = aggScope; - var memberDecls = objectLit.operand; - var prevThisType = this.thisType; - var acceptTargetType = false; - var targetType = null; - if(this.checker.hasTargetType()) { - targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { - if(targetType.symbol.declAST) { - this.typeCheck(targetType.symbol.declAST); - } - } - acceptTargetType = true; - } - if(memberDecls) { - for(var i = 0, len = memberDecls.members.length; i < len; i++) { - var binex = memberDecls.members[i]; - var id = binex.operand1; - var text; - var targetMember = null; - var fieldSymbol = null; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else { - if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); - resultType = this.anyType; - break; - } - } - if(acceptTargetType && targetType.memberScope) { - targetMember = targetType.memberScope.find(text, false, false); - } - if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { - var funcDecl = binex.operand2; - var accessorSym = resultType.members.publicMembers.lookup(text); - accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); - funcDecl.accessorSymbol = accessorSym; - fieldSymbol = accessorSym; - if(id.nodeType == TypeScript.NodeType.Name) { - (id).sym = accessorSym; - } - } - this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); - if(acceptTargetType && targetMember) { - if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { - binex.operand1.type = targetMember.getType(); - } - } else { - binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; - } - if(fieldSymbol == null) { - var memberType = binex.operand2.type; - var field = new TypeScript.ValueLocation(); - fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= TypeScript.SymbolFlags.Property; - field.symbol = fieldSymbol; - fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.type = memberType; - resultType.members.publicMembers.add(text, fieldSymbol); - } - fieldSymbol.isObjectLitField = true; - } - } - this.thisType = prevThisType; - objectLit.type = resultType; - if(targetType) { - objectLit.targetType = targetType; - } - }; - TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { - var elements = arrayLit.operand; - var elementType = this.anyType; - var targetElementType = null; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - comparisonInfo.onlyCaptureFirstError = true; - if(this.checker.hasTargetType()) { - var targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType.elementType) { - targetElementType = targetType.elementType; - } - } - if(elements) { - var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; - this.inArrayElementTypeCheck = true; - this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); - this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; - elementType = elements.members[0].type; - var collection = { - getLength: function () { - return elements.members.length; - }, - setTypeAtIndex: function (index, type) { - elements.members[index].type = type; - }, - getTypeAtIndex: function (index) { - return elements.members[index].type; - } - }; - elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); - if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { - elementType = this.anyType; - } - } - if(!elementType) { - var emsg = "Incompatible types in array literal expression"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleError(arrayLit, emsg); - } else { - this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); - } - elementType = this.anyType; - } else { - if(targetElementType) { - if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { - elementType = targetElementType; - } - } - } - arrayLit.type = this.checker.makeArrayType(elementType); - }; - TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { - if(type && type.construct && type.construct.signatures.length > 0) { - for(var i = 0; i < type.construct.signatures.length; i++) { - if(type.construct.signatures[i].returnType.type == this.checker.voidType) { - this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); - break; - } - } - } - }; - TypeFlow.prototype.typeCheckReturn = function (returnStmt) { - if(this.thisFnc) { - var targetType = null; - if(this.checker.hasTargetType()) { - var tcContext = this.checker.getTargetTypeContext(); - var accessorType = tcContext.targetAccessorType; - if(accessorType) { - targetType = accessorType; - } else { - var targetSig = this.checker.getTargetTypeContext().targetSig; - if(targetSig && targetSig.returnType.type != this.voidType) { - targetType = targetSig.returnType.type; - } - } - } - if(returnStmt.returnExpression) { - this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; - if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { - targetType = this.thisFnc.returnTypeAnnotation.type; - } - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); - var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; - if(expectedReturnType) { - if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { - this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); - returnStmt.type = returnStmt.returnExpression.type; - } else { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); - returnStmt.type = expectedReturnType; - } - } else { - if(targetType) { - if(returnStmt.returnExpression.type != this.voidType) { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); - } else { - returnStmt.returnExpression.type = targetType; - } - } - returnStmt.type = returnStmt.returnExpression.type; - } - this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; - } else { - returnStmt.type = targetType == null ? this.checker.voidType : targetType; - } - } - return returnStmt; - }; - TypeFlow.prototype.typeCheckInstOf = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { - this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckCommaOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.typeCheckLogOr = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else { - if(leftType == this.checker.booleanType) { - if(rightType == this.checker.booleanType) { - binex.type = this.checker.booleanType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(leftType == this.checker.numberType) { - if(rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(leftType == this.checker.stringType) { - if(rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - binex.type = rightType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - binex.type = leftType; - } else { - binex.type = this.checker.anyType; - } - } - } - } - } - } - return binex; - }; - TypeFlow.prototype.typeCheckLogAnd = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { - var lowerBound = signature.nonOptionalParameterCount; - var upperBound = signature.parameters.length; - var formalLen = lowerBound; - var acceptable = false; - if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { - formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); - acceptable = true; - } - var repeatType = null; - if(acceptable || signature.hasVariableArgList) { - if(signature.hasVariableArgList) { - formalLen -= 1; - repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; - repeatType = repeatType.elementType; - acceptable = actuals.length >= formalLen; - } - var len = actuals.length; - var exact = acceptable; - var convert = acceptable; - for(var i = 0; i < len; i++) { - var typeA; - if(i < formalLen) { - typeA = (signature.parameters[i]).parameter.typeLink.type; - } else { - typeA = repeatType; - } - var typeB = actuals[i]; - if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { - exact = false; - } - if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { - convert = false; - } - if(!(exact || convert)) { - break; - } - } - if(exact) { - exactCandidates[exactCandidates.length] = signature; - } else { - if(convert && (exactCandidates.length == 0)) { - conversionCandidates[conversionCandidates.length] = signature; - } - } - } - }; - TypeFlow.prototype.resolveOverload = function (application, group) { - var rd = this.resolutionDataCache.getResolutionData(); - var actuals = rd.actuals; - var exactCandidates = rd.exactCandidates; - var conversionCandidates = rd.conversionCandidates; - var candidate = null; - var hasOverloads = group.signatures.length > 1; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - var args = null; - var target = null; - if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { - var callEx = application; - args = callEx.arguments; - target = callEx.target; - if(callEx.arguments) { - var len = callEx.arguments.members.length; - for(var i = 0; i < len; i++) { - actuals[i] = callEx.arguments.members[i].type; - } - } - } else { - if(application.nodeType == TypeScript.NodeType.Index) { - var binExp = application; - target = binExp.operand1; - args = new TypeScript.ASTList(); - args.members[0] = binExp.operand2; - actuals[0] = binExp.operand2.type; - } - } - for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { - var signature = group.signatures[j]; - if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { - continue; - } - if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { - this.typeCheckFunction(signature.declAST); - } - this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); - } - if(exactCandidates.length == 0) { - var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); - if(applicableCandidates.length > 0) { - var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - var emsg = "Supplied parameters do not match any signature of call target"; - if(comparisonInfo.message) { - this.checker.errorReporter.simpleError(target, emsg + ":\n\t" + comparisonInfo.message); - } else { - this.checker.errorReporter.simpleError(target, emsg); - } - } - } else { - if(exactCandidates.length > 1) { - var applicableSigs = []; - for(var i = 0; i < exactCandidates.length; i++) { - applicableSigs[i] = { - signature: exactCandidates[i], - hadProvisionalErrors: false - }; - } - var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - candidate = exactCandidates[0]; - } - } - this.resolutionDataCache.returnResolutionData(rd); - return candidate; - }; - TypeFlow.prototype.typeCheckNew = function (ast) { - var callEx = ast; - callEx.target = this.typeCheck(callEx.target); - var target = callEx.target; - if(target.type.construct || target.type.call) { - this.preTypeCheckCallArgs(callEx.arguments); - } else { - callEx.arguments = this.typeCheck(callEx.arguments); - } - if(target.type == this.anyType) { - callEx.type = this.anyType; - callEx.arguments = this.typeCheck(callEx.arguments); - } else { - if(target.type.construct) { - var signature = this.resolveOverload(callEx, target.type.construct); - if(signature == null) { - callEx.type = this.anyType; - } else { - if(signature.returnType.type == this.voidType) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } - } else { - if(target.type.call) { - var signature = this.resolveOverload(callEx, target.type.call); - if(signature == null) { - callEx.type = this.anyType; - } else { - if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); - } - } - } else { - if(target.type.elementType) { - callEx.type = target.type; - } else { - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - callEx.type = this.anyType; - } - } - } - } - this.postTypeCheckCallArgs(callEx); - return callEx; - }; - TypeFlow.prototype.preTypeCheckCallArgs = function (args) { - if(!args) { - return; - } - for(var i = 0; i < args.members.length; i++) { - switch(args.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - continue; - - } - default: { - this.typeCheck(args.members[i]); - break; - - } - } - } - }; - TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { - var acceptedTargetType = false; - var i = 0; - if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { - var sig = callEx.signature; - if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { - acceptedTargetType = true; - var targetType = null; - var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; - var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; - for(i = 0; i < nonVarArgActualParamLength; i++) { - targetType = sig.parameters[i].getType(); - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); - break; - - } - } - } - if(sig.hasVariableArgList) { - var varArgParamIndex = sig.nonOptionalParameterCount - 1; - targetType = sig.parameters[varArgParamIndex].getType(); - if(targetType) { - targetType = targetType.elementType; - } - var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; - for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); - break; - - } - } - } - } - } - } - if(!acceptedTargetType && callEx.arguments) { - this.checker.killCurrentContextualType(); - for(i = 0; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: { - this.typeCheck(callEx.arguments.members[i]); - break; - - } - default: { - continue; - - } - } - } - } - }; - TypeFlow.prototype.typeCheckCall = function (ast) { - var callEx = ast; - if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { - this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); - } - } else { - if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { - if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { - this.checker.errorReporter.styleError(callEx, "eval not permitted"); - } - } - } - if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { - (callEx.target).isInlineCallLiteral = true; - } - var prevInSuperCall = this.inSuperCall; - if(callEx.target.nodeType == TypeScript.NodeType.Super) { - this.inSuperCall = true; - } - callEx.target = this.typeCheck(callEx.target); - this.preTypeCheckCallArgs(callEx.arguments); - var target = callEx.target; - if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { - callEx.type = this.anyType; - } else { - var fnType = target.type; - if(fnType.call) { - var signature = this.resolveOverload(callEx, fnType.call); - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - callEx.type = this.anyType; - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - } - } - } - this.postTypeCheckCallArgs(callEx); - this.inSuperCall = prevInSuperCall; - return callEx; - }; - TypeFlow.prototype.assignScopes = function (ast) { - var script = ast; - this.checker.locationInfo = script.locationInfo; - var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); - var context = new TypeScript.AssignScopeContext(globalChain, this, [ - this.checker.currentModDecl - ]); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); - }; - TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { - var enclosingScope = enclosingScopeContext.getScope(); - var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); - var scriptFragment = enclosingScopeContext.getScriptFragment(); - var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); - memContext.scope = enclosingScope; - if(scriptFragment.nodeType == TypeScript.NodeType.Name) { - return scriptFragment.type.getMemberScope(this); - } else { - TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); - if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(memContext.type) { - return memContext.type.getMemberScope(this); - } else { - return null; - } - } - }; - TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { - return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); - }; - TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { - var matchFlag = TypeScript.ASTFlags.DotLHS; - var pos = enclosingScopeContext.pos; - var astResult = null; - var preFindMemberScopeFullAst = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { - astResult = ast; - walker.options.stopWalk(); - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { - astResult = ast; - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); - if(astResult == null) { - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); - } - if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(astResult && astResult.type) { - return astResult.type.getMemberScope(this); - } else { - return null; - } - }; - return TypeFlow; - })(); - TypeScript.TypeFlow = TypeFlow; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (Primitive) { - Primitive._map = []; - Primitive.None = 0; - Primitive.Void = 1; - Primitive.Double = 2; - Primitive.String = 4; - Primitive.Boolean = 8; - Primitive.Any = 16; - Primitive.Null = 32; - Primitive.Undefined = 64; - })(TypeScript.Primitive || (TypeScript.Primitive = {})); - var Primitive = TypeScript.Primitive; - var MemberName = (function () { - function MemberName() { - this.prefix = ""; - this.suffix = ""; - } - MemberName.prototype.isString = function () { - return false; - }; - MemberName.prototype.isArray = function () { - return false; - }; - MemberName.prototype.toString = function () { - return MemberName.memberNameToString(this); - }; - MemberName.memberNameToString = function memberNameToString(memberName) { - var result = memberName.prefix; - if(memberName.isString()) { - result += (memberName).text; - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - result += MemberName.memberNameToString(ar.entries[index]); - result += ar.delim; - } - } - result += memberName.suffix; - return result; - } - MemberName.create = function create(arg1, arg2, arg3) { - if(typeof arg1 == "string") { - return new MemberNameString(arg1); - } else { - var result = new MemberNameArray(); - if(arg2) { - result.prefix = arg2; - } - if(arg3) { - result.suffix = arg3; - } - result.entries.push(arg1); - return result; - } - } - return MemberName; - })(); - TypeScript.MemberName = MemberName; - var MemberNameString = (function (_super) { - __extends(MemberNameString, _super); - function MemberNameString(text) { - _super.call(this); - this.text = text; - } - MemberNameString.prototype.isString = function () { - return true; - }; - return MemberNameString; - })(MemberName); - TypeScript.MemberNameString = MemberNameString; - var MemberNameArray = (function (_super) { - __extends(MemberNameArray, _super); - function MemberNameArray() { - _super.apply(this, arguments); - - this.delim = ""; - this.entries = []; - } - MemberNameArray.prototype.isArray = function () { - return true; - }; - MemberNameArray.prototype.add = function (entry) { - this.entries.push(entry); - }; - MemberNameArray.prototype.addAll = function (entries) { - for(var i = 0; i < entries.length; i++) { - this.entries.push(entries[i]); - } - }; - return MemberNameArray; - })(MemberName); - TypeScript.MemberNameArray = MemberNameArray; - var currentTypeID = -1; - var Type = (function () { - function Type() { - this.typeID = currentTypeID++; - this.construct = null; - this.call = null; - this.index = null; - this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.primitiveTypeClass = Primitive.None; - this.typeFlags = TypeScript.TypeFlags.None; - } - Type.prototype.baseClass = function () { - if(this.extendsList && (this.extendsList.length > 0)) { - return this.extendsList[0]; - } else { - return null; - } - }; - Type.prototype.getArrayBase = function (arrInstType, checker) { - return this.arrayCache.specialize(arrInstType, checker); - }; - Type.prototype.isClass = function () { - return this.instanceType != null; - }; - Type.prototype.isArray = function () { - return this.elementType != null; - }; - Type.prototype.isClassInstance = function () { - return this.symbol && !this.elementType && (this.symbol).type.isClass(); - }; - Type.prototype.getInstanceType = function () { - if(this.isClass()) { - return this.instanceType; - } else { - return this; - } - }; - Type.prototype.hasImplementation = function () { - return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); - }; - Type.prototype.setHasImplementation = function () { - this.typeFlags |= TypeScript.TypeFlags.HasImplementation; - }; - Type.prototype.isDouble = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); - }; - Type.prototype.isString = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); - }; - Type.prototype.isBoolean = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); - }; - Type.prototype.isNull = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); - }; - Type.prototype.getTypeName = function () { - return this.getMemberTypeName("", true, false, null); - }; - Type.prototype.getScopedTypeName = function (scope) { - return this.getMemberTypeName("", true, false, scope); - }; - Type.prototype.getScopedTypeNameEx = function (scope) { - return this.getMemberTypeNameEx("", true, false, scope); - }; - Type.prototype.callCount = function () { - var total = 0; - if(this.call) { - total += this.call.signatures.length; - } - if(this.construct) { - total += this.construct.signatures.length; - } - if(this.index) { - total += this.index.signatures.length; - } - return total; - }; - Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope) { - var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope); - return memberName.toString(); - }; - Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope) { - if(this.elementType) { - return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); - } else { - if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { - var tn = this.symbol.scopeRelativeName(scope); - return MemberName.create(tn == "null" ? "any" : tn); - } else { - if(this.members || this.call || this.construct) { - if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { - return MemberName.create("this"); - } - this.typeFlags |= TypeScript.TypeFlags.BuildingName; - var builder = ""; - var allMemberNames = new MemberNameArray(); - var curlies = isElementType || this.index != null; - var memCount = 0; - var delim = "; "; - if(this.members) { - this.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - var typeNameMember = sym.getTypeNameEx(scope); - if(typeNameMember.isArray() && (typeNameMember).delim == delim) { - allMemberNames.addAll((typeNameMember).entries); - } else { - allMemberNames.add(typeNameMember); - } - memCount++; - curlies = true; - } - }, null); - } - var signatureCount = this.callCount(); - var j; - var len = 0; - var shortform = !curlies && signatureCount == 1 && topLevel; - if(this.call) { - allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope)); - } - if(this.construct) { - allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); - } - if(this.index) { - allMemberNames.addAll(this.index.toStrings("", shortform, scope)); - } - if((curlies) || ((signatureCount > 1) && topLevel)) { - allMemberNames.prefix = "{ "; - allMemberNames.suffix = "}"; - allMemberNames.delim = delim; - } else { - if(allMemberNames.entries.length > 1) { - allMemberNames.delim = delim; - } - } - this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); - if((signatureCount == 0) && (memCount == 0)) { - return MemberName.create("{}"); - } else { - return allMemberNames; - } - } else { - return MemberName.create("{}"); - } - } - } - }; - Type.prototype.checkDecl = function (checker) { - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST) { - checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); - } - } - }; - Type.prototype.getMemberScope = function (flow) { - if(this == flow.anyType) { - return null; - } else { - if(this.isDouble()) { - if(flow.numberInterfaceType) { - return flow.numberInterfaceType.memberScope; - } else { - return null; - } - } else { - if(this.isBoolean()) { - if(flow.booleanInterfaceType) { - return flow.booleanInterfaceType.memberScope; - } else { - return null; - } - } else { - if(this == flow.stringType) { - if(flow.stringInterfaceType) { - return flow.stringInterfaceType.memberScope; - } else { - return null; - } - } else { - if(this.elementType) { - if(flow.arrayInterfaceType) { - var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); - return arrInstType.memberScope; - } else { - return null; - } - } else { - return this.memberScope; - } - } - } - } - } - }; - Type.prototype.isReferenceType = function () { - return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; - }; - Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { - if(pattern == this) { - return replacement; - } - var result = this; - if(membersOnly) { - if(this.isReferenceType()) { - result = new Type(); - if(this.members) { - result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.members.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPublicMember(bSym.name, bSym); - }, null); - this.members.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPrivateMember(bSym.name, bSym); - }, null); - } - if(this.ambientMembers) { - result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.ambientMembers.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPublicMember(bSym.name, bSym); - }, null); - this.ambientMembers.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPrivateMember(bSym.name, bSym); - }, null); - } - result.containedScope = checker.scopeOf(result); - result.memberScope = result.containedScope; - } - } else { - if(this.elementType) { - if(this.elementType == pattern) { - result = checker.makeArrayType(replacement); - } else { - if(this.elementType.elementType == pattern) { - result = checker.makeArrayType(checker.makeArrayType(replacement)); - } - } - } else { - if(this.call) { - result = new Type(); - result.call = this.call.specializeType(pattern, replacement, checker); - } - } - } - return result; - }; - Type.prototype.hasBase = function (baseType) { - if(baseType == this) { - return true; - } else { - if(this.extendsList) { - for(var i = 0, len = this.extendsList.length; i < len; i++) { - if(this.extendsList[i].hasBase(baseType)) { - return true; - } - } - } - } - return false; - }; - Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { - if((this == checker.anyType) || (b == checker.anyType)) { - return checker.anyType; - } else { - if(this == b) { - return this; - } else { - if((b == checker.nullType) && this != checker.nullType) { - return this; - } else { - if((this == checker.nullType) && (b != checker.nullType)) { - return b; - } else { - if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { - return this; - } else { - if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { - return b; - } else { - if((b == checker.undefinedType) && this != checker.undefinedType) { - return this; - } else { - if((this == checker.undefinedType) && (b != checker.undefinedType)) { - return b; - } else { - if(this.elementType && b.elementType) { - if(this.elementType == b.elementType) { - return this; - } else { - var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); - if(mergedET == null) { - return checker.makeArrayType(checker.anyType); - } else { - return checker.makeArrayType(mergedET); - } - } - } else { - if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { - return b; - } else { - if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { - return this; - } else { - return null; - } - } - } - } - } - } - } - } - } - } - } - }; - Type.prototype.isModuleType = function () { - return false; - }; - Type.prototype.hasMembers = function () { - return this.members != null; - }; - Type.prototype.getAllEnclosedTypes = function () { - return null; - }; - Type.prototype.getAllAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getPublicEnclosedTypes = function () { - return null; - }; - Type.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getDocComments = function () { - if(this.elementType || !this.symbol) { - return []; - } - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return (this.symbol.declAST).classDecl.getDocComments(); - } else { - return this.symbol.getDocComments(); - } - } - if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { - return this.symbol.getDocComments(); - } - return []; - }; - return Type; - })(); - TypeScript.Type = Type; - var ModuleType = (function (_super) { - __extends(ModuleType, _super); - function ModuleType(enclosedTypes, ambientEnclosedTypes) { - _super.call(this); - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.importedModules = []; - } - ModuleType.prototype.isModuleType = function () { - return true; - }; - ModuleType.prototype.hasMembers = function () { - return this.members != null || this.enclosedTypes != null; - }; - ModuleType.prototype.getAllEnclosedTypes = function () { - return this.enclosedTypes; - }; - ModuleType.prototype.getAllAmbientEnclosedTypes = function () { - return this.ambientEnclosedTypes; - }; - ModuleType.prototype.getPublicEnclosedTypes = function () { - return null; - }; - ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { - var moduleName = null; - members.map(function (key, s, c) { - if(moduleName == null && !TypeScript.isQuoted(key)) { - var symbol = s; - var type = symbol.getType(); - if(type == moduleType) { - moduleName = { - name: key, - symbol: symbol - }; - } - } - }, null); - return moduleName; - } - ModuleType.prototype.findDynamicModuleName = function (moduleType) { - var moduleName = null; - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); - if(moduleName == null) { - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); - } - return moduleName; - }; - return ModuleType; - })(Type); - TypeScript.ModuleType = ModuleType; - var TypeLink = (function () { - function TypeLink() { - this.type = null; - this.ast = null; - } - return TypeLink; - })(); - TypeScript.TypeLink = TypeLink; - function getTypeLink(ast, checker, autoVar) { - var result = new TypeLink(); - result.ast = ast; - if((ast == null) && (autoVar)) { - result.type = checker.anyType; - } else { - result.type = null; - } - return result; - } - TypeScript.getTypeLink = getTypeLink; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function stripQuotes(str) { - return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); - } - TypeScript.stripQuotes = stripQuotes; - function isQuoted(str) { - return str.indexOf("\"") != -1 || str.indexOf("'") != -1 || str.indexOf("'") != -1 || str.indexOf("\"") != -1; - } - TypeScript.isQuoted = isQuoted; - function quoteStr(str) { - return "\"" + str + "\""; - } - TypeScript.quoteStr = quoteStr; - function swapQuotes(str) { - if(str.indexOf("\"") != -1) { - str = str.replace("\"", "'"); - str = str.replace("\"", "'"); - } else { - str = str.replace("'", "\""); - str = str.replace("'", "\""); - } - return str; - } - TypeScript.swapQuotes = swapQuotes; - function switchToForwardSlashes(path) { - return path.replace(/\\/g, "/"); - } - TypeScript.switchToForwardSlashes = switchToForwardSlashes; - function trimModName(modName) { - if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { - return modName.substring(0, modName.length - 6); - } - if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { - return modName.substring(0, modName.length - 4); - } - if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { - return modName.substring(0, modName.length - 5); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { - return modName.substring(0, modName.length - 3); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { - return modName.substring(0, modName.length - 3); - } - return modName; - } - TypeScript.trimModName = trimModName; - function getDeclareFilePath(fname) { - return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); - } - TypeScript.getDeclareFilePath = getDeclareFilePath; - function isFileOfExtension(fname, ext) { - var invariantFname = fname.toLocaleUpperCase(); - var invariantExt = ext.toLocaleUpperCase(); - var extLength = invariantExt.length; - return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; - } - function isJSFile(fname) { - return isFileOfExtension(fname, ".js"); - } - TypeScript.isJSFile = isJSFile; - function isSTRFile(fname) { - return isFileOfExtension(fname, ".str"); - } - TypeScript.isSTRFile = isSTRFile; - function isTSFile(fname) { - return isFileOfExtension(fname, ".ts"); - } - TypeScript.isTSFile = isTSFile; - function isDSTRFile(fname) { - return isFileOfExtension(fname, ".d.str"); - } - TypeScript.isDSTRFile = isDSTRFile; - function isDTSFile(fname) { - return isFileOfExtension(fname, ".d.ts"); - } - TypeScript.isDTSFile = isDTSFile; - function getPrettyName(modPath, quote, treatAsFileName) { - if (typeof quote === "undefined") { quote = true; } - if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } - var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); - var components = this.getPathComponents(modName); - return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; - } - TypeScript.getPrettyName = getPrettyName; - function getPathComponents(path) { - return path.split("/"); - } - TypeScript.getPathComponents = getPathComponents; - function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { - absoluteModPath = switchToForwardSlashes(absoluteModPath); - var modComponents = this.getPathComponents(absoluteModPath); - var fixedModComponents = this.getPathComponents(fixedModFilePath); - var joinStartIndex = 0; - for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { - break; - } - } - if(joinStartIndex != 0) { - var relativePath = ""; - var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); - for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != "") { - relativePath = relativePath + "../"; - } - } - return relativePath + relativePathComponents.join("/"); - } - return absoluteModPath; - } - TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; - function quoteBaseName(modPath) { - var modName = trimModName(stripQuotes(modPath)); - var path = getRootFilePath(modName); - if(path == "") { - return modPath; - } else { - var components = modName.split(path); - var fileIndex = components.length > 1 ? 1 : 0; - return quoteStr(components[fileIndex]); - } - } - TypeScript.quoteBaseName = quoteBaseName; - function changePathToSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".str"; - } - TypeScript.changePathToSTR = changePathToSTR; - function changePathToDSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.str"; - } - TypeScript.changePathToDSTR = changePathToDSTR; - function changePathToTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".ts"; - } - TypeScript.changePathToTS = changePathToTS; - function changePathToDTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.ts"; - } - TypeScript.changePathToDTS = changePathToDTS; - function isRelative(path) { - return path.charAt(0) == "."; - } - TypeScript.isRelative = isRelative; - function isRooted(path) { - return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); - } - TypeScript.isRooted = isRooted; - function getRootFilePath(outFname) { - if(outFname == "") { - return outFname; - } else { - var isPath = outFname.indexOf("/") != -1; - return isPath ? filePath(outFname) : ""; - } - } - TypeScript.getRootFilePath = getRootFilePath; - function filePathComponents(fullPath) { - fullPath = switchToForwardSlashes(fullPath); - var components = getPathComponents(fullPath); - return components.slice(0, components.length - 1); - } - TypeScript.filePathComponents = filePathComponents; - function filePath(fullPath) { - var path = filePathComponents(fullPath); - return path.join("/") + "/"; - } - TypeScript.filePath = filePath; - function normalizeURL(url) { - var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; - var matches = hostDomainAndPortRegex.exec(url); - if(matches) { - var hostDomainAndPort = matches[1]; - var actualPath = matches[3]; - return hostDomainAndPort + normalizePath(actualPath); - } - return normalizePath(url); - } - TypeScript.normalizeURL = normalizeURL; - TypeScript.pathNormalizeRegExp = /\//g; - function normalizePath(path) { - path = switchToForwardSlashes(path); - var startedWithSep = path.charAt(0) === "/"; - var parts = this.getPathComponents(path); - for(var i = 0; i < parts.length; i++) { - if(parts[i] === "." || parts[i] === "") { - parts.splice(i, 1); - i--; - } - if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { - parts.splice(i - 1, 2); - i -= 2; - } - } - return (startedWithSep ? "/" : "") + parts.join("/"); - } - TypeScript.normalizePath = normalizePath; - function normalizeImportPath(path) { - return normalizePath(path); - } - TypeScript.normalizeImportPath = normalizeImportPath; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var SourceUnit = (function () { - function SourceUnit(path, content) { - this.path = path; - this.content = content; - this.referencedFiles = null; - } - SourceUnit.prototype.getText = function (start, end) { - return this.content.substring(start, end); - }; - SourceUnit.prototype.getLength = function () { - return this.content.length; - }; - return SourceUnit; - })(); - TypeScript.SourceUnit = SourceUnit; - var CompilationEnvironment = (function () { - function CompilationEnvironment(compilationSettings, ioHost) { - this.compilationSettings = compilationSettings; - this.ioHost = ioHost; - this.residentCode = []; - this.code = []; - } - return CompilationEnvironment; - })(); - TypeScript.CompilationEnvironment = CompilationEnvironment; - var CodeResolver = (function () { - function CodeResolver(environment) { - this.environment = environment; - this.visited = { - }; - } - CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { - var resolvedFile = { - content: "", - path: referencePath - }; - var ioHost = this.environment.ioHost; - var isRelativePath = TypeScript.isRelative(referencePath); - var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); - var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); - if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { - normalizedPath += ".ts"; - } - normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); - var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); - if(!this.visited[absoluteModuleID]) { - if(isRelativePath || isRootedPath || !performSearch) { - try { - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - try { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else { - if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - } - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } - } - } - TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); - resolvedFile.path = normalizedPath; - this.visited[absoluteModuleID] = true; - } catch (err) { - TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); - } - } else { - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else { - if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - } - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - } - if(resolvedFile) { - resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); - TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); - resolvedFile.content = resolvedFile.content; - this.visited[absoluteModuleID] = true; - } else { - TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); - } - } - if(resolvedFile && resolvedFile.content) { - var rootDir = ioHost.dirName(resolvedFile.path); - var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); - var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); - sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; - for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { - var referencedFile = preProcessedFileInfo.referencedFiles[i]; - var normalizedPath = TypeScript.isRooted(referencedFile.path) ? referencedFile.path : rootDir + "/" + referencedFile.path; - normalizedPath = ioHost.resolvePath(normalizedPath); - if(referencePath == normalizedPath) { - resolutionDispatcher.postResolutionError(normalizedPath, "File contains reference to itself", null); - continue; - } - this.resolveCode(referencedFile.path, rootDir, false, resolutionDispatcher); - } - for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { - this.resolveCode(preProcessedFileInfo.importedFiles[i].path, rootDir, true, resolutionDispatcher); - } - resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); - } - } - }; - return CodeResolver; - })(); - TypeScript.CodeResolver = CodeResolver; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var StyleSettings = (function () { - function StyleSettings() { - this.bitwise = false; - this.blockInCompoundStmt = false; - this.eqeqeq = false; - this.forin = false; - this.emptyBlocks = true; - this.newMustBeUsed = false; - this.requireSemi = false; - this.assignmentInCond = false; - this.eqnull = false; - this.evalOK = true; - this.innerScopeDeclEscape = true; - this.funcInLoop = true; - this.reDeclareLocal = true; - this.literalSubscript = true; - this.implicitAny = false; - } - StyleSettings.prototype.setOption = function (opt, val) { - var optExists = this[opt]; - if(optExists !== undefined) { - this[opt] = val; - return true; - } else { - return false; - } - }; - StyleSettings.prototype.parseOptions = function (str) { - var opts = str.split(";"); - for(var i = 0, len = opts.length; i < len; i++) { - var opt = opts[i]; - var val = true; - var colonIndex = opt.lastIndexOf(":"); - if(colonIndex >= 0) { - var valStr = opt.substring(colonIndex + 1); - opt = opt.substring(0, colonIndex); - if(valStr == "off") { - val = false; - } - } - if(!this.setOption(opt, val)) { - return false; - } - } - return true; - }; - return StyleSettings; - })(); - TypeScript.StyleSettings = StyleSettings; - var CompilationSettings = (function () { - function CompilationSettings() { - this.styleSettings = new StyleSettings(); - this.propagateConstants = false; - this.minWhitespace = false; - this.parseOnly = false; - this.errorRecovery = false; - this.emitComments = false; - this.watch = false; - this.exec = false; - this.resolve = true; - this.controlFlow = false; - this.printControlFlow = false; - this.controlFlowUseDef = false; - this.errorOnWith = true; - this.preprocess = true; - this.canCallDefinitionSignature = false; - this.inferPropertiesFromThisAssignment = false; - this.useDefaultLib = true; - this.codeGenTarget = TypeScript.CodeGenTarget.ES3; - this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; - this.outputOption = ""; - this.mapSourceFiles = false; - this.generateDeclarationFiles = false; - this.useCaseSensitiveFileResolution = false; - } - CompilationSettings.prototype.setStyleOptions = function (str) { - this.styleSettings.parseOptions(str); - }; - return CompilationSettings; - })(); - TypeScript.CompilationSettings = CompilationSettings; - function getFileReferenceFromReferencePath(comment) { - var referencesRegEx = /^(\/\/\/\s*/igm; - var match = referencesRegEx.exec(comment); - if(match) { - var path = TypeScript.normalizePath(match[3]); - var adjustedPath = TypeScript.normalizePath(path); - var isResident = match.length >= 7 && match[6] == "true"; - if(isResident) { - TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); - } - return { - minChar: 0, - limChar: 0, - path: TypeScript.switchToForwardSlashes(adjustedPath), - isResident: isResident - }; - } else { - return null; - } - } - function getAdditionalDependencyPath(comment) { - var amdDependencyRegEx = /^(\/\/\/\s*/igm; - var match = amdDependencyRegEx.exec(comment); - if(match) { - var path = match[3]; - return path; - } else { - return null; - } - } - TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; - function getImplicitImport(comment) { - var implicitImportRegEx = /^(\/\/\/\s*/igm; - var match = implicitImportRegEx.exec(comment); - if(match) { - return true; - } - return false; - } - TypeScript.getImplicitImport = getImplicitImport; - function getStyleSettings(comment, styleSettings) { - var styleRegEx = /^(\/\/\/\s*/igm; - var settings = styleRegEx.exec(comment); - if(settings) { - var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/igm; - settings = settingsRegEx.exec(settings[2]); - if(settings) { - for(var i = 0; i < settings.length; i++) { - var setting = (settings[i]).split("="); - var on = "\"on\""; - switch(setting[0]) { - case "blockInCompoundStmt": { - styleSettings.blockInCompoundStmt = setting[1] == on; - break; - - } - case "eqeqeq": { - styleSettings.eqeqeq = setting[1] == on; - break; - - } - case "forin": { - styleSettings.forin = setting[1] == on; - break; - - } - case "emptyBlocks": { - styleSettings.emptyBlocks = setting[1] == on; - break; - - } - case "newMustBeUsed": { - styleSettings.newMustBeUsed = setting[1] == on; - break; - - } - case "requireSemi": { - styleSettings.requireSemi = setting[1] == on; - break; - - } - case "assignmentInCond": { - styleSettings.assignmentInCond = setting[1] == on; - break; - - } - case "eqnull": { - styleSettings.eqnull = setting[1] == on; - break; - - } - case "evalOK": { - styleSettings.evalOK = setting[1] == on; - break; - - } - case "innerScopeDeclEscape": { - styleSettings.innerScopeDeclEscape = setting[1] == on; - break; - - } - case "funcInLoop": { - styleSettings.funcInLoop = setting[1] == on; - break; - - } - case "reDeclareLocal": { - styleSettings.reDeclareLocal = setting[1] == on; - break; - - } - case "literalSubscript": { - styleSettings.literalSubscript = setting[1] == on; - break; - - } - case "implicitAny": { - styleSettings.implicitAny = setting[1] == on; - break; - - } - } - } - } - } - } - TypeScript.getStyleSettings = getStyleSettings; - function getReferencedFiles(sourceText) { - var preProcessInfo = preProcessFile(sourceText, null, false); - return preProcessInfo.referencedFiles; - } - TypeScript.getReferencedFiles = getReferencedFiles; - function preProcessFile(sourceText, options, readImportFiles) { - if (typeof options === "undefined") { options = new CompilationSettings(); } - if (typeof readImportFiles === "undefined") { readImportFiles = true; } - var scanner = new TypeScript.Scanner(); - scanner.resetComments(); - scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var tok = scanner.scan(); - var comments = []; - var comment = null; - var leftCurlies = []; - var settings = options; - var referencedFiles = []; - var importedFiles = []; - var isLibFile = false; - while(tok.tokenId != TypeScript.TokenID.EndOfFile) { - if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Equals) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Module) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.OpenParen) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.StringLiteral) { - var ref = { - minChar: scanner.startPos, - limChar: scanner.pos, - path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), - isResident: false - }; - importedFiles.push(ref); - } - } - } - } - } - } - if(tok.tokenId == TypeScript.TokenID.OpenBrace) { - leftCurlies.push(tok); - } - if(tok.tokenId == TypeScript.TokenID.CloseBrace) { - leftCurlies.pop(); - } - tok = scanner.scan(); - } - comments = scanner.getComments(); - for(var iComment = 0; iComment < comments.length; iComment++) { - comment = comments[iComment]; - if(!comment.isBlock) { - var referencedCode = getFileReferenceFromReferencePath(comment.getText()); - if(referencedCode) { - referencedCode.minChar = comment.startPos; - referencedCode.limChar = referencedCode.minChar + comment.value.length; - referencedFiles.push(referencedCode); - } - if(settings) { - getStyleSettings(comment.getText(), settings.styleSettings); - var isNoLibRegex = /^(\/\/\/\s*/igm; - var isNoLibMatch = isNoLibRegex.exec(comment.getText()); - if(isNoLibMatch) { - isLibFile = (isNoLibMatch[3] == "true"); - } - } - } - } - return { - settings: settings, - referencedFiles: referencedFiles, - importedFiles: importedFiles, - isLibFile: isLibFile - }; - } - TypeScript.preProcessFile = preProcessFile; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var IncrementalParser = (function () { - function IncrementalParser(logger) { - this.logger = logger; - this.astLogger = new TypeScript.AstLogger(this.logger); - } - IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - if(editRange.isUnknown()) { - this.logger.log(" Bailing out because edit range is unknown"); - return null; - } - var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); - var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); - if(scope1 == null || scope2 == null) { - this.logger.log(" Bailing out because containing scopes cannot be determined"); - return null; - } - if(scope1.scopeStartAST !== scope2.scopeStartAST) { - this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength <= 0) { - this.logger.log(" Bailing out because scope has been entirely removed from new source text"); - return null; - } - return scope1; - }; - IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); - if(scope1 === null) { - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength >= newSourceText.getLength() / 2) { - this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); - return null; - } - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); - if(quickParseResult.endLexState != TypeScript.LexState.Start) { - this.logger.log(" Bailing out because scope contains unterminated comment"); - return null; - } - var scriptFragment = quickParseResult.Script; - if(scriptFragment.vars.members.length !== 0) { - this.logger.log(" Bailing out because new source text defines variables"); - return null; - } - if(scriptFragment.bod.members.length !== 1) { - this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); - return null; - } - var oldScope = scope1.scopeStartAST; - var newScope = scriptFragment.bod.members[0]; - if(oldScope.nodeType != newScope.nodeType) { - this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); - return null; - } - if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { - this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); - return null; - } - if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); - return null; - } - if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); - return null; - } - if(newScope.minChar !== 0) { - this.logger.log(" Bailing out because new function declaration does not start at position 0"); - return null; - } - if(newScope.limChar !== newScopeLength) { - this.logger.log(" Bailing out because new function declaration does not end at the new end position"); - return null; - } - return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); - }; - IncrementalParser.prototype.mergeTrees = function (updateResult) { - var _this = this; - TypeScript.timeFunction(this.logger, "mergeTrees()", function () { - var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); - _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); - _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); - _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); - _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); - }); - }; - IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { - var _this = this; - var pre = function (cur, parent, walker) { - if(cur === oldAst) { - newAst.preComments = cur.preComments; - newAst.postComments = cur.postComments; - _this.logger.log("replaced old AST node with new one in script AST"); - walker.options.stopWalk(); - return newAst; - } - if(TypeScript.isValidAstNode(cur)) { - if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - }; - IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { - var lineMap1 = script.locationInfo.lineMap; - var lineMap2 = partial.locationInfo.lineMap; - if(this.logger.information()) { - this.logger.log("lineMap1 (before):"); - this.astLogger.logLinemap(lineMap1); - this.logger.log("lineMap2 (quick parse):"); - this.astLogger.logLinemap(lineMap2); - this.logger.log("EditRange=" + editRange); - } - var i1 = 2; - var i2 = 2; - var len1 = lineMap1.length; - var len2 = lineMap2.length; - while(i1 < len1) { - if(lineMap1[i1] <= editRange.minChar) { - i1++; - } else { - if(lineMap1[i1] >= editRange.limChar) { - lineMap1[i1] += editRange.delta; - i1++; - } else { - if(i2 < len2) { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } else { - lineMap1.splice(i1, 1); - len1--; - } - } - } - } - if(i2 < len2) { - if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { - i1 = 2; - while(i1 < len1 && i2 < len2) { - if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { - i1++; - } else { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } - } - } - for(; i2 < len2; i2++) { - lineMap1.push(lineMap2[i2] + editRange.minChar); - } - } - if(this.logger.information()) { - this.logger.log("lineMap1 (after merge):"); - this.astLogger.logLinemap(lineMap1); - } - }; - IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { - var applyDelta = function (ast) { - if(ast.minChar !== -1 && ast.minChar >= start) { - ast.minChar += delta; - } - if(ast.limChar !== -1 && ast.limChar >= start) { - ast.limChar += delta; - } - }; - var applyDeltaToComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - applyDelta(comments[i]); - } - } - }; - var pre = function (cur, parent, walker) { - if(cur.limChar !== -1 && cur.limChar < start) { - walker.options.goChildren = false; - } - applyDelta(cur); - applyDeltaToComments(cur.preComments); - applyDeltaToComments(cur.postComments); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(ast, pre); - }; - return IncrementalParser; - })(); - TypeScript.IncrementalParser = IncrementalParser; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var DeclFileWriter = (function () { - function DeclFileWriter(declFile) { - this.declFile = declFile; - this.onNewLine = true; - } - DeclFileWriter.prototype.Write = function (s) { - this.declFile.Write(s); - this.onNewLine = false; - }; - DeclFileWriter.prototype.WriteLine = function (s) { - this.declFile.WriteLine(s); - this.onNewLine = true; - }; - DeclFileWriter.prototype.Close = function () { - this.declFile.Close(); - }; - return DeclFileWriter; - })(); - TypeScript.DeclFileWriter = DeclFileWriter; - var DeclarationEmitter = (function () { - function DeclarationEmitter(checker, emitOptions, errorReporter) { - this.checker = checker; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.declFile = null; - this.indenter = new TypeScript.Indenter(); - this.declarationContainerStack = []; - this.isDottedModuleName = []; - this.ignoreCallbackAst = null; - this.singleDeclFile = null; - this.varListCount = 0; - } - DeclarationEmitter.prototype.getAstDeclarationContainer = function () { - return this.declarationContainerStack[this.declarationContainerStack.length - 1]; - }; - DeclarationEmitter.prototype.emitDottedModuleName = function () { - return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; - }; - DeclarationEmitter.prototype.setDeclarationFile = function (file) { - this.declFile = new DeclFileWriter(file); - }; - DeclarationEmitter.prototype.Close = function () { - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - DeclarationEmitter.prototype.emitDeclarations = function (script) { - TypeScript.AstWalkerWithDetailCallback.walk(script, this); - }; - DeclarationEmitter.prototype.getIndentString = function (declIndent) { - if (typeof declIndent === "undefined") { declIndent = false; } - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - DeclarationEmitter.prototype.emitIndent = function () { - this.declFile.Write(this.getIndentString()); - }; - DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { - if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } - if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } - var container; - if(useDeclarationContainerTop) { - container = this.getAstDeclarationContainer(); - } else { - container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; - } - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - return false; - } - if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { - return false; - } - return true; - }; - DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { - if(this.ignoreCallbackAst) { - TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); - this.ignoreCallbackAst = null; - return false; - } else { - if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { - this.ignoreCallbackAst = astWithPrePostCallback; - return false; - } - } - return true; - }; - DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { - var result = this.getIndentString(); - var accessorString = ""; - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { - accessorString = "get "; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { - accessorString = "set "; - } - } - var container = this.getAstDeclarationContainer(); - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - result += "export "; - } - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { - result += "static " + accessorString; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { - result += "private " + accessorString; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { - result += "public " + accessorString; - } else { - if(accessorString == "") { - result += typeString + " "; - } else { - result += accessorString; - } - } - } - } - return result; - }; - DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { - this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); - }; - DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { - if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } - return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); - }; - DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { - this.declarationContainerStack.push(ast); - }; - DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { - TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); - this.declarationContainerStack.pop(); - }; - DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { - if (typeof emitIndent === "undefined") { emitIndent = false; } - if(memberName.prefix == "{ ") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.WriteLine("{"); - this.indenter.increaseIndent(); - emitIndent = true; - } else { - if(memberName.prefix != "") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write(memberName.prefix); - emitIndent = false; - } - } - if(memberName.isString()) { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write((memberName).text); - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - this.emitTypeNamesMember(ar.entries[index], emitIndent); - if(ar.delim == "; ") { - this.declFile.WriteLine(";"); - } - } - } - if(memberName.suffix == "}") { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.Write(memberName.suffix); - } else { - this.declFile.Write(memberName.suffix); - } - }; - DeclarationEmitter.prototype.emitTypeSignature = function (type) { - var containingScope = null; - var declarationContainerAst = this.getAstDeclarationContainer(); - switch(declarationContainerAst.nodeType) { - case TypeScript.NodeType.ModuleDeclaration: - case TypeScript.NodeType.InterfaceDeclaration: - case TypeScript.NodeType.FuncDecl: { - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.containedScope; - } - break; - - } - case TypeScript.NodeType.Script: { - var script = declarationContainerAst; - if(script.bod) { - containingScope = script.bod.enclosingScope; - } - break; - - } - case TypeScript.NodeType.ClassDeclaration: { - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.instanceType.containedScope; - } - break; - - } - default: { - TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); - - } - } - var typeNameMembers = type.getScopedTypeNameEx(containingScope); - this.emitTypeNamesMember(typeNameMembers); - }; - DeclarationEmitter.prototype.emitComment = function (comment) { - var text = comment.getText(); - if(this.declFile.onNewLine) { - this.emitIndent(); - } else { - if(!comment.isBlockComment) { - this.declFile.WriteLine(""); - this.emitIndent(); - } - } - this.declFile.Write(text[0]); - for(var i = 1; i < text.length; i++) { - this.declFile.WriteLine(""); - this.emitIndent(); - this.declFile.Write(text[i]); - } - if(comment.endsLine || !comment.isBlockComment) { - this.declFile.WriteLine(""); - } else { - this.declFile.Write(" "); - } - }; - DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { - if (typeof endLine === "undefined") { endLine = true; } - if(!this.emitOptions.emitComments) { - return; - } - var declComments = astOrSymbol.getDocComments(); - if(declComments.length > 0) { - for(var i = 0; i < declComments.length; i++) { - this.emitComment(declComments[i]); - } - if(endLine) { - if(!this.declFile.onNewLine) { - this.declFile.WriteLine(""); - } - } else { - if(this.declFile.onNewLine) { - this.emitIndent(); - } - } - } - }; - DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { - if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { - var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - this.emitDeclarationComments(varDecl); - if(!interfaceMember) { - if(this.varListCount >= 0) { - this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); - this.varListCount = -this.varListCount; - } - this.declFile.Write(varDecl.id.text); - } else { - this.emitIndent(); - this.declFile.Write(varDecl.id.text); - if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("?"); - } - } - var type = null; - if(varDecl.typeExpr && varDecl.typeExpr.type) { - type = varDecl.typeExpr.type; - } else { - if(varDecl.sym) { - type = (varDecl.sym).getType(); - if(type == this.checker.anyType) { - type = null; - } - } - } - if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(type); - } - if(this.varListCount > 0) { - this.varListCount--; - } else { - if(this.varListCount < 0) { - this.varListCount++; - } - } - if(this.varListCount < 0) { - this.declFile.Write(", "); - } else { - this.declFile.WriteLine(";"); - } - } - return false; - }; - DeclarationEmitter.prototype.BlockCallback = function (pre, block) { - if(!block.isStatementBlock) { - if(pre) { - this.varListCount = block.statements.members.length; - } else { - this.varListCount = 0; - } - return true; - } - return false; - }; - DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { - this.emitDeclarationComments(argDecl, false); - this.declFile.Write(argDecl.id.text); - if(argDecl.isOptionalArg()) { - this.declFile.Write("?"); - } - if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - }; - DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { - if(!pre) { - return false; - } - if(funcDecl.isAccessor()) { - return this.emitPropertyAccessorSignature(funcDecl); - } - var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - if(funcDecl.bod) { - if(funcDecl.isConstructor) { - if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { - return false; - } - } else { - if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - return false; - } - } - } else { - if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - var signatures = funcDecl.type.call.signatures; - var firstSignature = signatures[0].declAST; - if(firstSignature.bod) { - firstSignature = signatures[1].declAST; - } - if(firstSignature != funcDecl) { - return false; - } - } - } - if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { - return false; - } - this.emitDeclarationComments(funcDecl); - if(funcDecl.isConstructor) { - this.emitIndent(); - this.declFile.Write("constructor"); - } else { - var id = funcDecl.getNameText(); - if(!isInterfaceMember) { - this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); - this.declFile.Write(id); - } else { - this.emitIndent(); - if(funcDecl.isConstructMember()) { - this.declFile.Write("new"); - } else { - if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { - this.declFile.Write(id); - if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("? "); - } - } - } - } - } - if(!funcDecl.isIndexerMember()) { - this.declFile.Write("("); - } else { - this.declFile.Write("["); - } - this.indenter.increaseIndent(); - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - this.emitArgDecl(argDecl, funcDecl); - if(i < (argsLen - 1)) { - this.declFile.Write(", "); - } - } - } - if(funcDecl.variableArgList) { - var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; - if(funcDecl.arguments.members.length > 1) { - this.declFile.Write(", ..."); - } else { - this.declFile.Write("..."); - } - this.emitArgDecl(lastArg, funcDecl); - } - this.indenter.decreaseIndent(); - if(!funcDecl.isIndexerMember()) { - this.declFile.Write(")"); - } else { - this.declFile.Write("]"); - } - if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(funcDecl.signature.returnType.type); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { - if(bases && (bases.members.length > 0)) { - this.declFile.Write(" " + qual + " "); - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = baseExpr.type.symbol; - var baseType = baseExpr.type; - if(i > 0) { - this.declFile.Write(", "); - } - this.emitTypeSignature(baseType); - } - } - }; - DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { - var accessorSymbol = funcDecl.accessorSymbol; - if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { - return false; - } - this.emitDeclarationComments(accessorSymbol); - this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); - this.declFile.Write(funcDecl.name.text); - var propertyType = accessorSymbol.getType(); - if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { - this.declFile.Write(" : "); - this.emitTypeSignature(propertyType); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { - this.emitDeclarationComments(argDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); - this.declFile.Write(argDecl.id.text); - if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - this.declFile.WriteLine(";"); - } - } - } - }; - DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { - return false; - } - if(pre) { - var className = classDecl.name.text; - this.emitDeclarationComments(classDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); - this.declFile.Write(className); - this.emitBaseList(classDecl.extendsList, "extends"); - this.emitBaseList(classDecl.implementsList, "implements"); - this.declFile.WriteLine(" {"); - this.pushDeclarationContainer(classDecl); - this.indenter.increaseIndent(); - if(classDecl.constructorDecl) { - this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); - } - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(classDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { - return false; - } - if(pre) { - var interfaceName = interfaceDecl.name.text; - this.emitDeclarationComments(interfaceDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); - this.declFile.Write(interfaceName); - this.emitBaseList(interfaceDecl.extendsList, "extends"); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - this.pushDeclarationContainer(interfaceDecl); - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(interfaceDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { - if(pre) { - if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { - this.emitDeclarationComments(importDecl); - this.emitIndent(); - this.declFile.Write("import "); - this.declFile.Write(importDecl.id.text + " = "); - if(importDecl.isDynamicImport) { - this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); - } else { - this.declFile.WriteLine(importDecl.getAliasName() + ";"); - } - } - } - return false; - }; - DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { - if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { - return false; - } - this.emitDeclarationComments(moduleDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); - this.declFile.WriteLine(moduleDecl.name.text + " {"); - this.indenter.increaseIndent(); - var membersLen = moduleDecl.members.members.length; - for(var j = 1; j < membersLen; j++) { - var memberDecl = moduleDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.emitDeclarationComments(memberDecl); - this.emitIndent(); - this.declFile.WriteLine((memberDecl).id.text + ","); - } else { - TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); - } - } - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - return false; - }; - DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - if(pre) { - if(!this.emitOptions.outputMany) { - this.singleDeclFile = this.declFile; - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - try { - this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - } - this.pushDeclarationContainer(moduleDecl); - } else { - if(!this.emitOptions.outputMany) { - TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - this.declFile = this.singleDeclFile; - } - this.popDeclarationContainer(moduleDecl); - } - } - return true; - } - if(moduleDecl.isEnum()) { - if(pre) { - this.emitEnumSignature(moduleDecl); - } - return false; - } - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { - return false; - } - if(pre) { - if(this.emitDottedModuleName()) { - this.dottedModuleEmit += "."; - } else { - this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); - } - this.dottedModuleEmit += moduleDecl.name.text; - var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); - var moduleDeclComments = moduleDecl.getDocComments(); - isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); - this.isDottedModuleName.push(isCurrentModuleDotted); - this.pushDeclarationContainer(moduleDecl); - if(!isCurrentModuleDotted) { - this.emitDeclarationComments(moduleDecl); - this.declFile.Write(this.dottedModuleEmit); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - } - } else { - if(!this.emitDottedModuleName()) { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - this.popDeclarationContainer(moduleDecl); - this.isDottedModuleName.pop(); - } - return true; - }; - DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { - if(pre) { - if(this.emitOptions.outputMany) { - for(var i = 0; i < script.referencedFiles.length; i++) { - var referencePath = script.referencedFiles[i].path; - var declareFileName; - if(TypeScript.isRooted(referencePath)) { - declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); - } else { - declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); - } - this.declFile.WriteLine('/// '); - } - } - this.pushDeclarationContainer(script); - } else { - this.popDeclarationContainer(script); - } - return true; - }; - DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { - return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); - }; - return DeclarationEmitter; - })(); - TypeScript.DeclarationEmitter = DeclarationEmitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (UpdateUnitKind) { - UpdateUnitKind._map = []; - UpdateUnitKind._map[0] = "Unknown"; - UpdateUnitKind.Unknown = 0; - UpdateUnitKind._map[1] = "NoEdits"; - UpdateUnitKind.NoEdits = 1; - UpdateUnitKind._map[2] = "EditsInsideSingleScope"; - UpdateUnitKind.EditsInsideSingleScope = 2; - })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); - var UpdateUnitKind = TypeScript.UpdateUnitKind; - var ScriptEditRange = (function () { - function ScriptEditRange(minChar, limChar, delta) { - this.minChar = minChar; - this.limChar = limChar; - this.delta = delta; - } - ScriptEditRange.unknown = function unknown() { - return new ScriptEditRange(-1, -1, -1); - } - ScriptEditRange.prototype.isUnknown = function () { - return this.minChar === -1 && this.limChar === -1 && this.delta === -1; - }; - ScriptEditRange.prototype.containsPosition = function (pos) { - return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); - }; - ScriptEditRange.prototype.toString = function () { - return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; - }; - return ScriptEditRange; - })(); - TypeScript.ScriptEditRange = ScriptEditRange; - var UpdateUnitResult = (function () { - function UpdateUnitResult(kind, unitIndex, script1, script2) { - this.kind = kind; - this.unitIndex = unitIndex; - this.script1 = script1; - this.script2 = script2; - this.scope1 = null; - this.scope2 = null; - this.editRange = null; - this.parseErrors = []; - } - UpdateUnitResult.noEdits = function noEdits(unitIndex) { - return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); - } - UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); - result.parseErrors = parseErrors; - return result; - } - UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); - result.scope1 = scope1; - result.scope2 = scope2; - result.editRange = editRange; - result.parseErrors = parseErrors; - return result; - } - return UpdateUnitResult; - })(); - TypeScript.UpdateUnitResult = UpdateUnitResult; - var ErrorEntry = (function () { - function ErrorEntry(unitIndex, minChar, limChar, message) { - this.unitIndex = unitIndex; - this.minChar = minChar; - this.limChar = limChar; - this.message = message; - } - return ErrorEntry; - })(); - TypeScript.ErrorEntry = ErrorEntry; - TypeScript.defaultSettings = new TypeScript.CompilationSettings(); - var TypeScriptCompiler = (function () { - function TypeScriptCompiler(errorOutput, logger, settings) { - if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } - if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } - this.errorOutput = errorOutput; - this.logger = logger; - this.settings = settings; - this.parser = new TypeScript.Parser(); - this.typeFlow = null; - this.scripts = new TypeScript.ASTList(); - this.units = new Array(); - this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); - this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); - this.errorReporter.parser = this.parser; - this.initTypeChecker(this.errorOutput); - this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; - this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; - this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; - this.emitSettings = new TypeScript.EmitOptions(this.settings); - TypeScript.codeGenTarget = settings.codeGenTarget; - } - TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { - return TypeScript.timeFunction(this.logger, funcDescription, func); - }; - TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { - this.persistentTypeState.refreshPersistentState(); - this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); - this.typeChecker.errorReporter = this.errorReporter; - this.typeChecker.checkControlFlow = this.settings.controlFlow; - this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; - this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; - this.typeChecker.errorsOnWith = this.settings.errorOnWith; - this.typeChecker.styleSettings = this.settings.styleSettings; - this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; - this.errorReporter.checker = this.typeChecker; - this.setErrorOutput(this.errorOutput); - }; - TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { - this.errorOutput = outerr; - this.errorReporter.setErrOut(outerr); - this.parser.outfile = outerr; - }; - TypeScriptCompiler.prototype.emitCommentsToOutput = function () { - this.emitSettings = new TypeScript.EmitOptions(this.settings); - }; - TypeScriptCompiler.prototype.setErrorCallback = function (fn) { - this.parser.errorCallback = fn; - }; - TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { - return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); - }; - TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("updateSourceUnit(" + filename + ")", function () { - var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); - return _this.applyUpdateResult(updateResult); - }); - }; - TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { - switch(updateResult.kind) { - case UpdateUnitKind.NoEdits: { - return false; - - } - case UpdateUnitKind.Unknown: { - this.scripts.members[updateResult.unitIndex] = updateResult.script2; - this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; - for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { - var e = updateResult.parseErrors[i]; - if(this.parser.errorCallback) { - this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); - } - } - return true; - - } - case UpdateUnitKind.EditsInsideSingleScope: { - new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); - return true; - - } - } - }; - TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { - for(var i = 0, len = _this.units.length; i < len; i++) { - if(_this.units[i].filename == filename) { - if((_this.scripts.members[i]).isResident) { - return UpdateUnitResult.noEdits(i); - } - if(setRecovery) { - _this.parser.setErrorRecovery(null); - } - var updateResult; - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var svErrorCallback = _this.parser.errorCallback; - if(svErrorCallback) { - _this.parser.errorCallback = errorCapture; - } - var oldScript = _this.scripts.members[i]; - var newScript = _this.parser.parse(sourceText, filename, i); - if(svErrorCallback) { - _this.parser.errorCallback = svErrorCallback; - } - updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); - return updateResult; - } - } - throw new Error("Unknown file \"" + filename + "\""); - }); - }; - TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { - if (typeof keepResident === "undefined") { keepResident = false; } - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); - }; - TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - var _this = this; - return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { - var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); - script.referencedFiles = referencedFiles; - script.isResident = keepResident; - _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); - var index = _this.units.length; - _this.units[index] = script.locationInfo; - _this.typeChecker.collectTypes(script); - _this.scripts.append(script); - return script; - }); - }; - TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { - return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); - }; - TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { - this.parser.setErrorRecovery(this.errorOutput); - var script = this.parser.parse(sourceText, filename, 0); - var index = this.units.length; - this.units[index] = script.locationInfo; - this.typeChecker.collectTypes(script); - this.scripts.append(script); - }; - TypeScriptCompiler.prototype.typeCheck = function () { - var _this = this; - return this.timeFunction("typeCheck()", function () { - var binder = new TypeScript.Binder(_this.typeChecker); - _this.typeChecker.units = _this.units; - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); - _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); - var i = 0; - var script = null; - var len = _this.scripts.members.length; - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.typeCheck(script); - script.hasBeenTypeChecked = true; - } - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - len = _this.scripts.members.length; - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.typeCheck(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { - function cleanASTType(ast, parent) { - ast.type = null; - if(ast.nodeType == TypeScript.NodeType.VarDecl) { - var vardecl = ast; - vardecl.sym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - var argdecl = ast; - argdecl.sym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.Name) { - var name = ast; - name.sym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcdecl = ast; - funcdecl.signature = null; - funcdecl.freeVariables = new Array(); - funcdecl.symbols = null; - funcdecl.accessorSymbol = null; - funcdecl.scopeType = null; - } else { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var modDecl = ast; - modDecl.mod = null; - } else { - if(ast.nodeType == TypeScript.NodeType.With) { - (ast).withSym = null; - } else { - if(ast.nodeType == TypeScript.NodeType.Catch) { - (ast).containedScope = null; - } - } - } - } - } - } - } - return ast; - } - TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); - }; - TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { - var _this = this; - return this.timeFunction("cleanTypesForReTypeCheck()", function () { - for(var i = 0, len = _this.scripts.members.length; i < len; i++) { - var script = _this.scripts.members[i]; - if((script).isResident) { - continue; - } - _this.cleanASTTypesForReTypeCheck(script); - _this.typeChecker.collectTypes(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { - return this.timeFunction("attemptIncrementalTypeCheck()", function () { - return false; - }); - }; - TypeScriptCompiler.prototype.reTypeCheck = function () { - var _this = this; - return this.timeFunction("reTypeCheck()", function () { - TypeScript.CompilerDiagnostics.analysisPass++; - _this.initTypeChecker(_this.errorOutput); - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - _this.cleanTypesForReTypeCheck(); - return _this.typeCheck(); - }); - }; - TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(!script.isDeclareFile && script.topLevelMod != null) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { - var commonComponents = []; - var commonComponentsLength = -1; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(script.emitRequired(this.emitSettings)) { - var fileName = script.locationInfo.filename; - var fileComponents = TypeScript.filePathComponents(fileName); - if(commonComponentsLength == -1) { - commonComponents = fileComponents; - commonComponentsLength = commonComponents.length; - } else { - var updatedPath = false; - for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { - if(commonComponents[j] != fileComponents[j]) { - commonComponentsLength = j; - updatedPath = true; - if(j == 0) { - this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); - return; - } - break; - } - } - if(!updatedPath && fileComponents.length < commonComponentsLength) { - commonComponentsLength = fileComponents.length; - } - } - } - } - this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; - if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { - this.emitSettings.outputOption += "/"; - } - }; - TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { - this.emitSettings.ioHost = ioHost; - if(this.emitSettings.outputOption == "") { - this.emitSettings.outputMany = true; - this.emitSettings.commonDirectoryPath = ""; - return; - } - this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); - if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = true; - } else { - if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = false; - } else { - this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); - } - } - if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { - this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); - } - if(this.emitSettings.outputMany) { - this.updateCommonDirectoryPath(); - } - }; - TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { - if(this.emitSettings.outputMany) { - return this.outputScriptToUTF8(script); - } else { - return this.outputScriptsToUTF8((this.scripts.members)); - } - }; - TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { - return TypeScript.getDeclareFilePath(fileName); - } - TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { - if(!this.settings.generateDeclarationFiles) { - return false; - } - if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { - return false; - } - return true; - }; - TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { - if(!this.canEmitDeclarations(script)) { - return null; - } - if(!declarationEmitter) { - var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); - var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); - declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); - declarationEmitter.setDeclarationFile(declareFile); - } - declarationEmitter.emitDeclarations(script); - if(!reuseEmitter) { - declarationEmitter.Close(); - return null; - } else { - return declarationEmitter; - } - }; - TypeScriptCompiler.prototype.emitDeclarations = function () { - if(!this.canEmitDeclarations()) { - return; - } - if(this.errorReporter.hasErrors) { - return; - } - if(this.scripts.members.length == 0) { - return; - } - var declarationEmitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || declarationEmitter == null) { - declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); - } else { - this.emitDeclarationsUnit(script, true, declarationEmitter); - } - } - if(declarationEmitter) { - declarationEmitter.Close(); - } - }; - TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { - if(wholeFileNameReplaced) { - return fileName; - } else { - var splitFname = fileName.split("."); - splitFname.pop(); - return splitFname.join(".") + extension; - } - } - TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); - } - TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter) { - if(!script.emitRequired(this.emitSettings)) { - return null; - } - var fname = script.locationInfo.filename; - if(!emitter) { - var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); - var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); - if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter)); - } - } else { - if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter)); - } - } - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - if(!reuseEmitter) { - emitter.Close(); - return null; - } else { - return emitter; - } - }; - TypeScriptCompiler.prototype.emit = function (ioHost) { - this.parseEmitOption(ioHost); - var emitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || emitter == null) { - emitter = this.emitUnit(script, !this.emitSettings.outputMany); - } else { - this.emitUnit(script, true, emitter); - } - } - if(emitter) { - emitter.Close(); - } - }; - TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { - if(this.settings.mapSourceFiles) { - throw Error("Cannot generate source map"); - } - if(this.settings.generateDeclarationFiles) { - throw Error("Cannot generate declaration files"); - } - if(this.settings.outputOption != "") { - throw Error("Cannot parse output option"); - } - var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); - ; ; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - } - }; - TypeScriptCompiler.prototype.emitAST = function (ioHost) { - this.parseEmitOption(ioHost); - var outFile = null; - var context = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || context == null) { - var fname = this.units[i].filename; - var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); - }; - var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); - outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - context = new TypeScript.PrintContext(outFile, this.parser); - } - TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); - if(this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - } - if(!this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - }; - TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { - return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); - }; - TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { - for(var i = 0, len = scripts.length; i < len; i++) { - var script = scripts[i]; - if(this.outputScriptToUTF8(script)) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitSettings.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return TypeScriptCompiler; - })(); - TypeScript.TypeScriptCompiler = TypeScriptCompiler; - var ScopeEntry = (function () { - function ScopeEntry(name, type, sym) { - this.name = name; - this.type = type; - this.sym = sym; - } - return ScopeEntry; - })(); - TypeScript.ScopeEntry = ScopeEntry; - var ScopeTraversal = (function () { - function ScopeTraversal(compiler) { - this.compiler = compiler; - } - ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { - if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { - return enclosingScopeContext.getObjectLiteralScope(); - } else { - if(enclosingScopeContext.isMemberCompletion) { - if(enclosingScopeContext.useFullAst) { - return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); - } else { - return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); - } - } else { - return enclosingScopeContext.getScope(); - } - } - }; - ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext) { - var scope = this.getScope(enclosingScopeContext); - if(scope == null) { - return []; - } - var inScopeNames = new TypeScript.StringHashTable(); - var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); - for(var i = 0; i < allSymbolNames.length; i++) { - var name = allSymbolNames[i]; - if(name == TypeScript.globalId || name == "_Core" || name == "_element") { - continue; - } - inScopeNames.add(name, ""); - } - var svModuleDecl = this.compiler.typeChecker.currentModDecl; - this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; - var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope); - this.compiler.typeChecker.currentModDecl = svModuleDecl; - return result; - }; - ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope) { - var result = []; - var enclosingScope = enclosingScopeContext.getScope(); - for(var i = 0; i < allNames.length; i++) { - var name = allNames[i]; - var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; - var symbol = scope.find(name, publicsOnly, false); - if(symbol == null) { - symbol = scope.find(name, publicsOnly, true); - } - var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; - if(symbol) { - if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { - var typeName = symbol.getType().getScopedTypeName(enclosingScope); - result.push(new ScopeEntry(name, typeName, symbol)); - } - } else { - if(name == "true" || name == "false") { - result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); - } - } - } - return result; - }; - return ScopeTraversal; - })(); - TypeScript.ScopeTraversal = ScopeTraversal; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (CompilerDiagnostics) { - CompilerDiagnostics.debug = false; - CompilerDiagnostics.diagnosticWriter = null; - CompilerDiagnostics.analysisPass = 0; - function Alert(output) { - if(CompilerDiagnostics.diagnosticWriter) { - CompilerDiagnostics.diagnosticWriter.Alert(output); - } - } - CompilerDiagnostics.Alert = Alert; - function debugPrint(s) { - if(CompilerDiagnostics.debug) { - Alert(s); - } - } - CompilerDiagnostics.debugPrint = debugPrint; - function assert(condition, s) { - if(CompilerDiagnostics.debug) { - if(!condition) { - Alert(s); - } - } - } - CompilerDiagnostics.assert = assert; - })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); - var CompilerDiagnostics = TypeScript.CompilerDiagnostics; - var NullLogger = (function () { - function NullLogger() { } - NullLogger.prototype.information = function () { - return false; - }; - NullLogger.prototype.debug = function () { - return false; - }; - NullLogger.prototype.warning = function () { - return false; - }; - NullLogger.prototype.error = function () { - return false; - }; - NullLogger.prototype.fatal = function () { - return false; - }; - NullLogger.prototype.log = function (s) { - }; - return NullLogger; - })(); - TypeScript.NullLogger = NullLogger; - var LoggerAdapter = (function () { - function LoggerAdapter(logger) { - this.logger = logger; - this._information = this.logger.information(); - this._debug = this.logger.debug(); - this._warning = this.logger.warning(); - this._error = this.logger.error(); - this._fatal = this.logger.fatal(); - } - LoggerAdapter.prototype.information = function () { - return this._information; - }; - LoggerAdapter.prototype.debug = function () { - return this._debug; - }; - LoggerAdapter.prototype.warning = function () { - return this._warning; - }; - LoggerAdapter.prototype.error = function () { - return this._error; - }; - LoggerAdapter.prototype.fatal = function () { - return this._fatal; - }; - LoggerAdapter.prototype.log = function (s) { - this.logger.log(s); - }; - return LoggerAdapter; - })(); - TypeScript.LoggerAdapter = LoggerAdapter; - var BufferedLogger = (function () { - function BufferedLogger() { - this.logContents = []; - } - BufferedLogger.prototype.information = function () { - return false; - }; - BufferedLogger.prototype.debug = function () { - return false; - }; - BufferedLogger.prototype.warning = function () { - return false; - }; - BufferedLogger.prototype.error = function () { - return false; - }; - BufferedLogger.prototype.fatal = function () { - return false; - }; - BufferedLogger.prototype.log = function (s) { - this.logContents.push(s); - }; - return BufferedLogger; - })(); - TypeScript.BufferedLogger = BufferedLogger; - function timeFunction(logger, funcDescription, func) { - var start = +new Date(); - var result = func(); - var end = +new Date(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); - return result; - } - TypeScript.timeFunction = timeFunction; - function stringToLiteral(value, length) { - var result = ""; - var addChar = function (index) { - var ch = value.charCodeAt(index); - switch(ch) { - case 9: { - result += "\\t"; - break; - - } - case 10: { - result += "\\n"; - break; - - } - case 11: { - result += "\\v"; - break; - - } - case 12: { - result += "\\f"; - break; - - } - case 13: { - result += "\\r"; - break; - - } - case 34: { - result += "\\\""; - break; - - } - case 39: { - result += "\\\'"; - break; - - } - case 92: { - result += "\\"; - break; - - } - default: { - result += value.charAt(index); - - } - } - }; - var tooLong = (value.length > length); - if(tooLong) { - var mid = length >> 1; - for(var i = 0; i < mid; i++) { - addChar(i); - } - result += "(...)"; - for(var i = value.length - mid; i < value.length; i++) { - addChar(i); - } - } else { - length = value.length; - for(var i = 0; i < length; i++) { - addChar(i); - } - } - return result; - } - TypeScript.stringToLiteral = stringToLiteral; -})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typescript_0.8.3/tsc b/_infrastructure/tests/typescript_0.8.3/tsc deleted file mode 100644 index 3c0dab574..000000000 --- a/_infrastructure/tests/typescript_0.8.3/tsc +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('./tsc.js') diff --git a/_infrastructure/tests/typescript_0.8.3/tsc.js b/_infrastructure/tests/typescript_0.8.3/tsc.js deleted file mode 100644 index 58a3b5e25..000000000 --- a/_infrastructure/tests/typescript_0.8.3/tsc.js +++ /dev/null @@ -1,24836 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -var TypeScript; -(function (TypeScript) { - function hasFlag(val, flag) { - return (val & flag) != 0; - } - TypeScript.hasFlag = hasFlag; - (function (ErrorRecoverySet) { - ErrorRecoverySet._map = []; - ErrorRecoverySet.None = 0; - ErrorRecoverySet.Comma = 1; - ErrorRecoverySet.SColon = 1 << 1; - ErrorRecoverySet.Asg = 1 << 2; - ErrorRecoverySet.BinOp = 1 << 3; - ErrorRecoverySet.RBrack = 1 << 4; - ErrorRecoverySet.RCurly = 1 << 5; - ErrorRecoverySet.RParen = 1 << 6; - ErrorRecoverySet.Dot = 1 << 7; - ErrorRecoverySet.Colon = 1 << 8; - ErrorRecoverySet.PrimType = 1 << 9; - ErrorRecoverySet.AddOp = 1 << 10; - ErrorRecoverySet.LCurly = 1 << 11; - ErrorRecoverySet.PreOp = 1 << 12; - ErrorRecoverySet.RegExp = 1 << 13; - ErrorRecoverySet.LParen = 1 << 14; - ErrorRecoverySet.LBrack = 1 << 15; - ErrorRecoverySet.Scope = 1 << 16; - ErrorRecoverySet.In = 1 << 17; - ErrorRecoverySet.SCase = 1 << 18; - ErrorRecoverySet.Else = 1 << 19; - ErrorRecoverySet.Catch = 1 << 20; - ErrorRecoverySet.Var = 1 << 21; - ErrorRecoverySet.Stmt = 1 << 22; - ErrorRecoverySet.While = 1 << 23; - ErrorRecoverySet.ID = 1 << 24; - ErrorRecoverySet.Prefix = 1 << 25; - ErrorRecoverySet.Literal = 1 << 26; - ErrorRecoverySet.RLit = 1 << 27; - ErrorRecoverySet.Func = 1 << 28; - ErrorRecoverySet.EOF = 1 << 29; - ErrorRecoverySet.TypeScriptS = 1 << 30; - ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; - ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; - ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; - })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); - var ErrorRecoverySet = TypeScript.ErrorRecoverySet; - (function (AllowedElements) { - AllowedElements._map = []; - AllowedElements.None = 0; - AllowedElements.ModuleDeclarations = 1 << 2; - AllowedElements.ClassDeclarations = 1 << 3; - AllowedElements.InterfaceDeclarations = 1 << 4; - AllowedElements.AmbientDeclarations = 1 << 10; - AllowedElements.Properties = 1 << 11; - AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; - AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; - })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); - var AllowedElements = TypeScript.AllowedElements; - (function (Modifiers) { - Modifiers._map = []; - Modifiers.None = 0; - Modifiers.Private = 1; - Modifiers.Public = 1 << 1; - Modifiers.Readonly = 1 << 2; - Modifiers.Ambient = 1 << 3; - Modifiers.Exported = 1 << 4; - Modifiers.Getter = 1 << 5; - Modifiers.Setter = 1 << 6; - Modifiers.Static = 1 << 7; - })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); - var Modifiers = TypeScript.Modifiers; - (function (ASTFlags) { - ASTFlags._map = []; - ASTFlags.None = 0; - ASTFlags.ExplicitSemicolon = 1; - ASTFlags.AutomaticSemicolon = 1 << 1; - ASTFlags.Writeable = 1 << 2; - ASTFlags.Error = 1 << 3; - ASTFlags.DotLHSPartial = 1 << 4; - ASTFlags.DotLHS = 1 << 5; - ASTFlags.IsStatement = 1 << 6; - ASTFlags.StrictMode = 1 << 7; - ASTFlags.PossibleOptionalParameter = 1 << 8; - ASTFlags.ClassBaseConstructorCall = 1 << 9; - ASTFlags.OptionalName = 1 << 10; - ASTFlags.SkipNextRParen = 1 << 11; - })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); - var ASTFlags = TypeScript.ASTFlags; - (function (DeclFlags) { - DeclFlags._map = []; - DeclFlags.None = 0; - DeclFlags.Exported = 1; - DeclFlags.Private = 1 << 1; - DeclFlags.Public = 1 << 2; - DeclFlags.Ambient = 1 << 3; - DeclFlags.Static = 1 << 4; - DeclFlags.LocalStatic = 1 << 5; - DeclFlags.GetAccessor = 1 << 6; - DeclFlags.SetAccessor = 1 << 7; - })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); - var DeclFlags = TypeScript.DeclFlags; - (function (ModuleFlags) { - ModuleFlags._map = []; - ModuleFlags.None = 0; - ModuleFlags.Exported = 1; - ModuleFlags.Private = 1 << 1; - ModuleFlags.Public = 1 << 2; - ModuleFlags.Ambient = 1 << 3; - ModuleFlags.Static = 1 << 4; - ModuleFlags.LocalStatic = 1 << 5; - ModuleFlags.GetAccessor = 1 << 6; - ModuleFlags.SetAccessor = 1 << 7; - ModuleFlags.IsEnum = 1 << 8; - ModuleFlags.ShouldEmitModuleDecl = 1 << 9; - ModuleFlags.IsWholeFile = 1 << 10; - ModuleFlags.IsDynamic = 1 << 11; - ModuleFlags.MustCaptureThis = 1 << 12; - })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); - var ModuleFlags = TypeScript.ModuleFlags; - (function (SymbolFlags) { - SymbolFlags._map = []; - SymbolFlags.None = 0; - SymbolFlags.Exported = 1; - SymbolFlags.Private = 1 << 1; - SymbolFlags.Public = 1 << 2; - SymbolFlags.Ambient = 1 << 3; - SymbolFlags.Static = 1 << 4; - SymbolFlags.LocalStatic = 1 << 5; - SymbolFlags.GetAccessor = 1 << 6; - SymbolFlags.SetAccessor = 1 << 7; - SymbolFlags.Property = 1 << 8; - SymbolFlags.Readonly = 1 << 9; - SymbolFlags.ModuleMember = 1 << 10; - SymbolFlags.InterfaceMember = 1 << 11; - SymbolFlags.ClassMember = 1 << 12; - SymbolFlags.BuiltIn = 1 << 13; - SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; - SymbolFlags.Constant = 1 << 15; - SymbolFlags.Optional = 1 << 16; - SymbolFlags.RecursivelyReferenced = 1 << 17; - SymbolFlags.Bound = 1 << 18; - SymbolFlags.CompilerGenerated = 1 << 19; - })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); - var SymbolFlags = TypeScript.SymbolFlags; - (function (VarFlags) { - VarFlags._map = []; - VarFlags.None = 0; - VarFlags.Exported = 1; - VarFlags.Private = 1 << 1; - VarFlags.Public = 1 << 2; - VarFlags.Ambient = 1 << 3; - VarFlags.Static = 1 << 4; - VarFlags.LocalStatic = 1 << 5; - VarFlags.GetAccessor = 1 << 6; - VarFlags.SetAccessor = 1 << 7; - VarFlags.AutoInit = 1 << 8; - VarFlags.Property = 1 << 9; - VarFlags.Readonly = 1 << 10; - VarFlags.Class = 1 << 11; - VarFlags.ClassProperty = 1 << 12; - VarFlags.ClassBodyProperty = 1 << 13; - VarFlags.ClassConstructorProperty = 1 << 14; - VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; - VarFlags.Constant = 1 << 16; - VarFlags.MustCaptureThis = 1 << 17; - })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); - var VarFlags = TypeScript.VarFlags; - (function (FncFlags) { - FncFlags._map = []; - FncFlags.None = 0; - FncFlags.Exported = 1; - FncFlags.Private = 1 << 1; - FncFlags.Public = 1 << 2; - FncFlags.Ambient = 1 << 3; - FncFlags.Static = 1 << 4; - FncFlags.LocalStatic = 1 << 5; - FncFlags.GetAccessor = 1 << 6; - FncFlags.SetAccessor = 1 << 7; - FncFlags.Signature = 1 << 9; - FncFlags.Method = 1 << 10; - FncFlags.HasReturnExpression = 1 << 11; - FncFlags.CallMember = 1 << 12; - FncFlags.ConstructMember = 1 << 13; - FncFlags.HasSelfReference = 1 << 14; - FncFlags.IsFatArrowFunction = 1 << 15; - FncFlags.IndexerMember = 1 << 16; - FncFlags.IsFunctionExpression = 1 << 17; - FncFlags.ClassMethod = 1 << 18; - FncFlags.ClassPropertyMethodExported = 1 << 19; - FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; - FncFlags.IsPropertyBound = 1 << 21; - })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); - var FncFlags = TypeScript.FncFlags; - (function (SignatureFlags) { - SignatureFlags._map = []; - SignatureFlags.None = 0; - SignatureFlags.IsIndexer = 1; - SignatureFlags.IsStringIndexer = 1 << 1; - SignatureFlags.IsNumberIndexer = 1 << 2; - })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); - var SignatureFlags = TypeScript.SignatureFlags; - function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { - return fncOrVarOrSymbolOrModuleFlags; - } - TypeScript.ToDeclFlags = ToDeclFlags; - (function (TypeFlags) { - TypeFlags._map = []; - TypeFlags.None = 0; - TypeFlags.HasImplementation = 1; - TypeFlags.HasSelfReference = 1 << 1; - TypeFlags.MergeResult = 1 << 2; - TypeFlags.IsEnum = 1 << 3; - TypeFlags.BuildingName = 1 << 4; - TypeFlags.HasBaseType = 1 << 5; - TypeFlags.HasBaseTypeOfObject = 1 << 6; - TypeFlags.IsClass = 1 << 7; - })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); - var TypeFlags = TypeScript.TypeFlags; - (function (TypeRelationshipFlags) { - TypeRelationshipFlags._map = []; - TypeRelationshipFlags.SuccessfulComparison = 0; - TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; - TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; - TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; - TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; - TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; - TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; - TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; - })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); - var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; - (function (CodeGenTarget) { - CodeGenTarget._map = []; - CodeGenTarget.ES3 = 0; - CodeGenTarget.ES5 = 1; - })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); - var CodeGenTarget = TypeScript.CodeGenTarget; - (function (ModuleGenTarget) { - ModuleGenTarget._map = []; - ModuleGenTarget.Synchronous = 0; - ModuleGenTarget.Asynchronous = 1; - ModuleGenTarget.Local = 1 << 1; - })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); - var ModuleGenTarget = TypeScript.ModuleGenTarget; - TypeScript.codeGenTarget = CodeGenTarget.ES3; - TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; - TypeScript.optimizeModuleCodeGen = true; - function flagsToString(e, flags) { - var builder = ""; - for(var i = 1; i < (1 << 31); i = i << 1) { - if((flags & i) != 0) { - for(var k in e) { - if(e[k] == i) { - if(builder.length > 0) { - builder += "|"; - } - builder += k; - break; - } - } - } - } - return builder; - } - TypeScript.flagsToString = flagsToString; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (NodeType) { - NodeType._map = []; - NodeType._map[0] = "None"; - NodeType.None = 0; - NodeType._map[1] = "Empty"; - NodeType.Empty = 1; - NodeType._map[2] = "EmptyExpr"; - NodeType.EmptyExpr = 2; - NodeType._map[3] = "True"; - NodeType.True = 3; - NodeType._map[4] = "False"; - NodeType.False = 4; - NodeType._map[5] = "This"; - NodeType.This = 5; - NodeType._map[6] = "Super"; - NodeType.Super = 6; - NodeType._map[7] = "QString"; - NodeType.QString = 7; - NodeType._map[8] = "Regex"; - NodeType.Regex = 8; - NodeType._map[9] = "Null"; - NodeType.Null = 9; - NodeType._map[10] = "ArrayLit"; - NodeType.ArrayLit = 10; - NodeType._map[11] = "ObjectLit"; - NodeType.ObjectLit = 11; - NodeType._map[12] = "Void"; - NodeType.Void = 12; - NodeType._map[13] = "Comma"; - NodeType.Comma = 13; - NodeType._map[14] = "Pos"; - NodeType.Pos = 14; - NodeType._map[15] = "Neg"; - NodeType.Neg = 15; - NodeType._map[16] = "Delete"; - NodeType.Delete = 16; - NodeType._map[17] = "Await"; - NodeType.Await = 17; - NodeType._map[18] = "In"; - NodeType.In = 18; - NodeType._map[19] = "Dot"; - NodeType.Dot = 19; - NodeType._map[20] = "From"; - NodeType.From = 20; - NodeType._map[21] = "Is"; - NodeType.Is = 21; - NodeType._map[22] = "InstOf"; - NodeType.InstOf = 22; - NodeType._map[23] = "Typeof"; - NodeType.Typeof = 23; - NodeType._map[24] = "NumberLit"; - NodeType.NumberLit = 24; - NodeType._map[25] = "Name"; - NodeType.Name = 25; - NodeType._map[26] = "TypeRef"; - NodeType.TypeRef = 26; - NodeType._map[27] = "Index"; - NodeType.Index = 27; - NodeType._map[28] = "Call"; - NodeType.Call = 28; - NodeType._map[29] = "New"; - NodeType.New = 29; - NodeType._map[30] = "Asg"; - NodeType.Asg = 30; - NodeType._map[31] = "AsgAdd"; - NodeType.AsgAdd = 31; - NodeType._map[32] = "AsgSub"; - NodeType.AsgSub = 32; - NodeType._map[33] = "AsgDiv"; - NodeType.AsgDiv = 33; - NodeType._map[34] = "AsgMul"; - NodeType.AsgMul = 34; - NodeType._map[35] = "AsgMod"; - NodeType.AsgMod = 35; - NodeType._map[36] = "AsgAnd"; - NodeType.AsgAnd = 36; - NodeType._map[37] = "AsgXor"; - NodeType.AsgXor = 37; - NodeType._map[38] = "AsgOr"; - NodeType.AsgOr = 38; - NodeType._map[39] = "AsgLsh"; - NodeType.AsgLsh = 39; - NodeType._map[40] = "AsgRsh"; - NodeType.AsgRsh = 40; - NodeType._map[41] = "AsgRs2"; - NodeType.AsgRs2 = 41; - NodeType._map[42] = "ConditionalExpression"; - NodeType.ConditionalExpression = 42; - NodeType._map[43] = "LogOr"; - NodeType.LogOr = 43; - NodeType._map[44] = "LogAnd"; - NodeType.LogAnd = 44; - NodeType._map[45] = "Or"; - NodeType.Or = 45; - NodeType._map[46] = "Xor"; - NodeType.Xor = 46; - NodeType._map[47] = "And"; - NodeType.And = 47; - NodeType._map[48] = "Eq"; - NodeType.Eq = 48; - NodeType._map[49] = "Ne"; - NodeType.Ne = 49; - NodeType._map[50] = "Eqv"; - NodeType.Eqv = 50; - NodeType._map[51] = "NEqv"; - NodeType.NEqv = 51; - NodeType._map[52] = "Lt"; - NodeType.Lt = 52; - NodeType._map[53] = "Le"; - NodeType.Le = 53; - NodeType._map[54] = "Gt"; - NodeType.Gt = 54; - NodeType._map[55] = "Ge"; - NodeType.Ge = 55; - NodeType._map[56] = "Add"; - NodeType.Add = 56; - NodeType._map[57] = "Sub"; - NodeType.Sub = 57; - NodeType._map[58] = "Mul"; - NodeType.Mul = 58; - NodeType._map[59] = "Div"; - NodeType.Div = 59; - NodeType._map[60] = "Mod"; - NodeType.Mod = 60; - NodeType._map[61] = "Lsh"; - NodeType.Lsh = 61; - NodeType._map[62] = "Rsh"; - NodeType.Rsh = 62; - NodeType._map[63] = "Rs2"; - NodeType.Rs2 = 63; - NodeType._map[64] = "Not"; - NodeType.Not = 64; - NodeType._map[65] = "LogNot"; - NodeType.LogNot = 65; - NodeType._map[66] = "IncPre"; - NodeType.IncPre = 66; - NodeType._map[67] = "DecPre"; - NodeType.DecPre = 67; - NodeType._map[68] = "IncPost"; - NodeType.IncPost = 68; - NodeType._map[69] = "DecPost"; - NodeType.DecPost = 69; - NodeType._map[70] = "TypeAssertion"; - NodeType.TypeAssertion = 70; - NodeType._map[71] = "FuncDecl"; - NodeType.FuncDecl = 71; - NodeType._map[72] = "Member"; - NodeType.Member = 72; - NodeType._map[73] = "VarDecl"; - NodeType.VarDecl = 73; - NodeType._map[74] = "ArgDecl"; - NodeType.ArgDecl = 74; - NodeType._map[75] = "Return"; - NodeType.Return = 75; - NodeType._map[76] = "Break"; - NodeType.Break = 76; - NodeType._map[77] = "Continue"; - NodeType.Continue = 77; - NodeType._map[78] = "Throw"; - NodeType.Throw = 78; - NodeType._map[79] = "For"; - NodeType.For = 79; - NodeType._map[80] = "ForIn"; - NodeType.ForIn = 80; - NodeType._map[81] = "If"; - NodeType.If = 81; - NodeType._map[82] = "While"; - NodeType.While = 82; - NodeType._map[83] = "DoWhile"; - NodeType.DoWhile = 83; - NodeType._map[84] = "Block"; - NodeType.Block = 84; - NodeType._map[85] = "Case"; - NodeType.Case = 85; - NodeType._map[86] = "Switch"; - NodeType.Switch = 86; - NodeType._map[87] = "Try"; - NodeType.Try = 87; - NodeType._map[88] = "TryCatch"; - NodeType.TryCatch = 88; - NodeType._map[89] = "TryFinally"; - NodeType.TryFinally = 89; - NodeType._map[90] = "Finally"; - NodeType.Finally = 90; - NodeType._map[91] = "Catch"; - NodeType.Catch = 91; - NodeType._map[92] = "List"; - NodeType.List = 92; - NodeType._map[93] = "Script"; - NodeType.Script = 93; - NodeType._map[94] = "ClassDeclaration"; - NodeType.ClassDeclaration = 94; - NodeType._map[95] = "InterfaceDeclaration"; - NodeType.InterfaceDeclaration = 95; - NodeType._map[96] = "ModuleDeclaration"; - NodeType.ModuleDeclaration = 96; - NodeType._map[97] = "ImportDeclaration"; - NodeType.ImportDeclaration = 97; - NodeType._map[98] = "With"; - NodeType.With = 98; - NodeType._map[99] = "Label"; - NodeType.Label = 99; - NodeType._map[100] = "LabeledStatement"; - NodeType.LabeledStatement = 100; - NodeType._map[101] = "EBStart"; - NodeType.EBStart = 101; - NodeType._map[102] = "GotoEB"; - NodeType.GotoEB = 102; - NodeType._map[103] = "EndCode"; - NodeType.EndCode = 103; - NodeType._map[104] = "Error"; - NodeType.Error = 104; - NodeType._map[105] = "Comment"; - NodeType.Comment = 105; - NodeType._map[106] = "Debugger"; - NodeType.Debugger = 106; - NodeType.GeneralNode = NodeType.FuncDecl; - NodeType.LastAsg = NodeType.AsgRs2; - })(TypeScript.NodeType || (TypeScript.NodeType = {})); - var NodeType = TypeScript.NodeType; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var BlockIntrinsics = (function () { - function BlockIntrinsics() { - this.prototype = undefined; - this.toString = undefined; - this.toLocaleString = undefined; - this.valueOf = undefined; - this.hasOwnProperty = undefined; - this.propertyIsEnumerable = undefined; - this.isPrototypeOf = undefined; - this["constructor"] = undefined; - } - return BlockIntrinsics; - })(); - TypeScript.BlockIntrinsics = BlockIntrinsics; - var StringHashTable = (function () { - function StringHashTable() { - this.itemCount = 0; - this.table = (new BlockIntrinsics()); - } - StringHashTable.prototype.getAllKeys = function () { - var result = []; - for(var k in this.table) { - if(this.table[k] != undefined) { - result[result.length] = k; - } - } - return result; - }; - StringHashTable.prototype.add = function (key, data) { - if(this.table[key] != undefined) { - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.table[key] != undefined) { - this.table[key] = data; - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.map = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - fn(k, this.table[k], context); - } - } - }; - StringHashTable.prototype.every = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(!fn(k, this.table[k], context)) { - return false; - } - } - } - return true; - }; - StringHashTable.prototype.some = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(fn(k, this.table[k], context)) { - return true; - } - } - } - return false; - }; - StringHashTable.prototype.count = function () { - return this.itemCount; - }; - StringHashTable.prototype.lookup = function (key) { - var data = this.table[key]; - if(data != undefined) { - return data; - } else { - return (null); - } - }; - return StringHashTable; - })(); - TypeScript.StringHashTable = StringHashTable; - var DualStringHashTable = (function () { - function DualStringHashTable(primaryTable, secondaryTable) { - this.primaryTable = primaryTable; - this.secondaryTable = secondaryTable; - this.insertPrimary = true; - } - DualStringHashTable.prototype.getAllKeys = function () { - return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); - }; - DualStringHashTable.prototype.add = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.add(key, data); - } else { - return this.secondaryTable.add(key, data); - } - }; - DualStringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.addOrUpdate(key, data); - } else { - return this.secondaryTable.addOrUpdate(key, data); - } - }; - DualStringHashTable.prototype.map = function (fn, context) { - this.primaryTable.map(fn, context); - this.secondaryTable.map(fn, context); - }; - DualStringHashTable.prototype.every = function (fn, context) { - return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); - }; - DualStringHashTable.prototype.some = function (fn, context) { - return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); - }; - DualStringHashTable.prototype.count = function () { - return this.primaryTable.count() + this.secondaryTable.count(); - }; - DualStringHashTable.prototype.lookup = function (key) { - var data = this.primaryTable.lookup(key); - if(data != undefined) { - return data; - } else { - return this.secondaryTable.lookup(key); - } - }; - return DualStringHashTable; - })(); - TypeScript.DualStringHashTable = DualStringHashTable; - function numberHashFn(key) { - var c2 = 0x27d4eb2d; - key = (key ^ 61) ^ (key >>> 16); - key = key + (key << 3); - key = key ^ (key >>> 4); - key = key * c2; - key = key ^ (key >>> 15); - return key; - } - TypeScript.numberHashFn = numberHashFn; - function combineHashes(key1, key2) { - return key2 ^ ((key1 >> 5) + key1); - } - TypeScript.combineHashes = combineHashes; - var HashEntry = (function () { - function HashEntry(key, data) { - this.key = key; - this.data = data; - } - return HashEntry; - })(); - TypeScript.HashEntry = HashEntry; - var HashTable = (function () { - function HashTable(size, hashFn, equalsFn) { - this.size = size; - this.hashFn = hashFn; - this.equalsFn = equalsFn; - this.itemCount = 0; - this.table = new Array(); - for(var i = 0; i < this.size; i++) { - this.table[i] = null; - } - } - HashTable.prototype.add = function (key, data) { - var current; - var entry = new HashEntry(key, data); - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return false; - } - } - entry.next = this.table[val]; - this.table[val] = entry; - this.itemCount++; - return true; - }; - HashTable.prototype.remove = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - var result = null; - var prevEntry = null; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - result = current.data; - this.itemCount--; - if(prevEntry) { - prevEntry.next = current.next; - } else { - this.table[val] = current.next; - } - break; - } - prevEntry = current; - } - return result; - }; - HashTable.prototype.count = function () { - return this.itemCount; - }; - HashTable.prototype.lookup = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return (current.data); - } - } - return (null); - }; - return HashTable; - })(); - TypeScript.HashTable = HashTable; - var SimpleHashTable = (function () { - function SimpleHashTable() { - this.keys = []; - this.values = []; - } - SimpleHashTable.prototype.lookup = function (key, findValue) { - var searchArray = this.keys; - if(findValue) { - searchArray = this.values; - } - for(var i = 0; i < searchArray.length; i++) { - if(searchArray[i] == key) { - return { - key: this.keys[i], - data: this.values[i] - }; - } - } - return null; - }; - SimpleHashTable.prototype.add = function (key, data) { - var lookupData = this.lookup(key); - if(lookupData) { - return false; - } - this.keys[this.keys.length] = key; - this.values[this.values.length] = data; - return true; - }; - return SimpleHashTable; - })(); - TypeScript.SimpleHashTable = SimpleHashTable; -})(TypeScript || (TypeScript = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -var TypeScript; -(function (TypeScript) { - var ASTSpan = (function () { - function ASTSpan() { - this.minChar = -1; - this.limChar = -1; - } - return ASTSpan; - })(); - TypeScript.ASTSpan = ASTSpan; - var AST = (function (_super) { - __extends(AST, _super); - function AST(nodeType) { - _super.call(this); - this.nodeType = nodeType; - this.type = null; - this.flags = TypeScript.ASTFlags.Writeable; - this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.preComments = null; - this.postComments = null; - this.docComments = null; - this.isParenthesized = false; - } - AST.prototype.isExpression = function () { - return false; - }; - AST.prototype.isStatementOrExpression = function () { - return false; - }; - AST.prototype.isCompoundStatement = function () { - return false; - }; - AST.prototype.isLeaf = function () { - return this.isStatementOrExpression() && (!this.isCompoundStatement()); - }; - AST.prototype.isDeclaration = function () { - return false; - }; - AST.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: - this.type = typeFlow.anyType; - break; - case TypeScript.NodeType.This: - return typeFlow.typeCheckThis(this); - case TypeScript.NodeType.Null: - this.type = typeFlow.nullType; - break; - case TypeScript.NodeType.False: - case TypeScript.NodeType.True: - this.type = typeFlow.booleanType; - break; - case TypeScript.NodeType.Super: - return typeFlow.typeCheckSuper(this); - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Empty: - case TypeScript.NodeType.Void: - this.type = typeFlow.voidType; - break; - default: - throw new Error("please implement in derived class"); - } - return this; - }; - AST.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - switch(this.nodeType) { - case TypeScript.NodeType.This: - emitter.recordSourceMappingStart(this); - if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - emitter.writeToOutput("_this"); - } else { - emitter.writeToOutput("this"); - } - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.Null: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("null"); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.False: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("false"); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.True: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("true"); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.Super: - emitter.recordSourceMappingStart(this); - emitter.emitSuperReference(); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: - break; - case TypeScript.NodeType.Empty: - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.Void: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("void "); - emitter.recordSourceMappingEnd(this); - break; - default: - throw new Error("please implement in derived class"); - } - emitter.emitParensAndCommentsInPlace(this, false); - }; - AST.prototype.print = function (context) { - context.startLine(); - var lineCol = { - line: -1, - col: -1 - }; - var limLineCol = { - line: -1, - col: -1 - }; - if(context.parser !== null) { - context.parser.getSourceLineCol(lineCol, this.minChar); - context.parser.getSourceLineCol(limLineCol, this.limChar); - context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); - } - var lab = this.printLabel(); - if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { - lab += " (Error)"; - } - context.writeLine(lab); - }; - AST.prototype.printLabel = function () { - if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { - return TypeScript.nodeTypeTable[this.nodeType]; - } else { - return (TypeScript.NodeType)._map[this.nodeType]; - } - }; - AST.prototype.addToControlFlow = function (context) { - context.walker.options.goChildren = false; - context.addContent(this); - }; - AST.prototype.netFreeUses = function (container, freeUses) { - }; - AST.prototype.treeViewLabel = function () { - return (TypeScript.NodeType)._map[this.nodeType]; - }; - AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { - if(!name) { - return ""; - } - var resolved = ""; - var start = 0; - var i = 0; - while(i <= name.length - 6) { - if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { - var charCode = parseInt(name.substr(i + 2, 4), 16); - resolved += name.substr(start, i - start); - resolved += String.fromCharCode(charCode); - i += 6; - start = i; - continue; - } - i++; - } - resolved += name.substring(start); - return resolved; - }; - AST.prototype.getDocComments = function () { - if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { - return []; - } - if(!this.docComments) { - var preCommentsLength = this.preComments.length; - var docComments = []; - for(var i = preCommentsLength - 1; i >= 0; i--) { - if(this.preComments[i].isDocComment()) { - var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; - if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { - docComments.push(this.preComments[i]); - continue; - } - } - break; - } - this.docComments = docComments.reverse(); - } - return this.docComments; - }; - return AST; - })(ASTSpan); - TypeScript.AST = AST; - var IncompleteAST = (function (_super) { - __extends(IncompleteAST, _super); - function IncompleteAST(min, lim) { - _super.call(this, TypeScript.NodeType.Error); - this.minChar = min; - this.limChar = lim; - } - return IncompleteAST; - })(AST); - TypeScript.IncompleteAST = IncompleteAST; - var ASTList = (function (_super) { - __extends(ASTList, _super); - function ASTList() { - _super.call(this, TypeScript.NodeType.List); - this.enclosingScope = null; - this.members = new Array(); - } - ASTList.prototype.addToControlFlow = function (context) { - var len = this.members.length; - for(var i = 0; i < len; i++) { - if(context.noContinuation) { - context.addUnreachable(this.members[i]); - break; - } else { - this.members[i] = context.walk(this.members[i], this); - } - } - context.walker.options.goChildren = false; - }; - ASTList.prototype.append = function (ast) { - this.members[this.members.length] = ast; - return this; - }; - ASTList.prototype.appendAll = function (ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - for(var i = 0, len = list.members.length; i < len; i++) { - this.append(list.members[i]); - } - } else { - this.append(ast); - } - return this; - }; - ASTList.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); - emitter.recordSourceMappingEnd(this); - }; - ASTList.prototype.typeCheck = function (typeFlow) { - var len = this.members.length; - typeFlow.nestingLevel++; - for(var i = 0; i < len; i++) { - if(this.members[i]) { - this.members[i] = this.members[i].typeCheck(typeFlow); - } - } - typeFlow.nestingLevel--; - return this; - }; - return ASTList; - })(AST); - TypeScript.ASTList = ASTList; - var Identifier = (function (_super) { - __extends(Identifier, _super); - function Identifier(actualText, hasEscapeSequence) { - _super.call(this, TypeScript.NodeType.Name); - this.actualText = actualText; - this.hasEscapeSequence = hasEscapeSequence; - this.sym = null; - this.cloId = -1; - this.setText(actualText, hasEscapeSequence); - } - Identifier.prototype.setText = function (actualText, hasEscapeSequence) { - this.actualText = actualText; - if(hasEscapeSequence) { - this.text = AST.getResolvedIdentifierName(actualText); - } else { - this.text = actualText; - } - }; - Identifier.prototype.isMissing = function () { - return false; - }; - Identifier.prototype.isLeaf = function () { - return true; - }; - Identifier.prototype.treeViewLabel = function () { - return "id: " + this.actualText; - }; - Identifier.prototype.printLabel = function () { - if(this.actualText) { - return "id: " + this.actualText; - } else { - return "name node"; - } - }; - Identifier.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckName(this); - }; - Identifier.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptName(this, true); - }; - Identifier.fromToken = function fromToken(token) { - return new Identifier(token.getText(), (token).hasEscapeSequence); - }; - return Identifier; - })(AST); - TypeScript.Identifier = Identifier; - var MissingIdentifier = (function (_super) { - __extends(MissingIdentifier, _super); - function MissingIdentifier() { - _super.call(this, "__missing"); - } - MissingIdentifier.prototype.isMissing = function () { - return true; - }; - MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { - }; - return MissingIdentifier; - })(Identifier); - TypeScript.MissingIdentifier = MissingIdentifier; - var Label = (function (_super) { - __extends(Label, _super); - function Label(id) { - _super.call(this, TypeScript.NodeType.Label); - this.id = id; - } - Label.prototype.printLabel = function () { - return this.id.actualText + ":"; - }; - Label.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - Label.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingStart(this.id); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this.id); - emitter.writeLineToOutput(":"); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Label; - })(AST); - TypeScript.Label = Label; - var Expression = (function (_super) { - __extends(Expression, _super); - function Expression(nodeType) { - _super.call(this, nodeType); - } - Expression.prototype.isExpression = function () { - return true; - }; - Expression.prototype.isStatementOrExpression = function () { - return true; - }; - return Expression; - })(AST); - TypeScript.Expression = Expression; - var UnaryExpression = (function (_super) { - __extends(UnaryExpression, _super); - function UnaryExpression(nodeType, operand) { - _super.call(this, nodeType); - this.operand = operand; - this.targetType = null; - this.castTerm = null; - } - UnaryExpression.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - if(this.nodeType == TypeScript.NodeType.Throw) { - context.returnStmt(); - } - }; - UnaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Not: - return typeFlow.typeCheckBitNot(this); - case TypeScript.NodeType.LogNot: - return typeFlow.typeCheckLogNot(this); - case TypeScript.NodeType.Pos: - case TypeScript.NodeType.Neg: - return typeFlow.typeCheckUnaryNumberOperator(this); - case TypeScript.NodeType.IncPost: - case TypeScript.NodeType.IncPre: - case TypeScript.NodeType.DecPost: - case TypeScript.NodeType.DecPre: - return typeFlow.typeCheckIncOrDec(this); - case TypeScript.NodeType.ArrayLit: - typeFlow.typeCheckArrayLit(this); - return this; - case TypeScript.NodeType.ObjectLit: - typeFlow.typeCheckObjectLit(this); - return this; - case TypeScript.NodeType.Throw: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.voidType; - return this; - case TypeScript.NodeType.Typeof: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.stringType; - return this; - case TypeScript.NodeType.Delete: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.booleanType; - break; - case TypeScript.NodeType.TypeAssertion: - this.castTerm = typeFlow.typeCheck(this.castTerm); - var applyTargetType = !this.operand.isParenthesized; - var targetType = applyTargetType ? this.castTerm.type : null; - typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); - typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); - this.type = this.castTerm.type; - return this; - case TypeScript.NodeType.Void: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.checker.undefinedType; - break; - default: - throw new Error("please implement in derived class"); - } - return this; - }; - UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - switch(this.nodeType) { - case TypeScript.NodeType.IncPost: - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - emitter.writeToOutput("++"); - break; - case TypeScript.NodeType.LogNot: - emitter.writeToOutput("!"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); - break; - case TypeScript.NodeType.DecPost: - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - emitter.writeToOutput("--"); - break; - case TypeScript.NodeType.ObjectLit: - emitter.emitObjectLiteral(this.operand); - break; - case TypeScript.NodeType.ArrayLit: - emitter.emitArrayLiteral(this.operand); - break; - case TypeScript.NodeType.Not: - emitter.writeToOutput("~"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.Neg: - emitter.writeToOutput("-"); - if(this.operand.nodeType == TypeScript.NodeType.Neg) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); - break; - case TypeScript.NodeType.Pos: - emitter.writeToOutput("+"); - if(this.operand.nodeType == TypeScript.NodeType.Pos) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); - break; - case TypeScript.NodeType.IncPre: - emitter.writeToOutput("++"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - break; - case TypeScript.NodeType.DecPre: - emitter.writeToOutput("--"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - break; - case TypeScript.NodeType.Throw: - emitter.writeToOutput("throw "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - emitter.writeToOutput(";"); - break; - case TypeScript.NodeType.Typeof: - emitter.writeToOutput("typeof "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.Delete: - emitter.writeToOutput("delete "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.Void: - emitter.writeToOutput("void "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.TypeAssertion: - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - default: - throw new Error("please implement in derived class"); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return UnaryExpression; - })(Expression); - TypeScript.UnaryExpression = UnaryExpression; - var CallExpression = (function (_super) { - __extends(CallExpression, _super); - function CallExpression(nodeType, target, arguments) { - _super.call(this, nodeType); - this.target = target; - this.arguments = arguments; - this.signature = null; - this.minChar = this.target.minChar; - } - CallExpression.prototype.typeCheck = function (typeFlow) { - if(this.nodeType == TypeScript.NodeType.New) { - return typeFlow.typeCheckNew(this); - } else { - return typeFlow.typeCheckCall(this); - } - }; - CallExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.New) { - emitter.emitNew(this.target, this.arguments); - } else { - emitter.emitCall(this, this.target, this.arguments); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return CallExpression; - })(Expression); - TypeScript.CallExpression = CallExpression; - var BinaryExpression = (function (_super) { - __extends(BinaryExpression, _super); - function BinaryExpression(nodeType, operand1, operand2) { - _super.call(this, nodeType); - this.operand1 = operand1; - this.operand2 = operand2; - } - BinaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: - return typeFlow.typeCheckDotOperator(this); - case TypeScript.NodeType.Asg: - return typeFlow.typeCheckAsgOperator(this); - case TypeScript.NodeType.Add: - case TypeScript.NodeType.Sub: - case TypeScript.NodeType.Mul: - case TypeScript.NodeType.Div: - case TypeScript.NodeType.Mod: - case TypeScript.NodeType.Or: - case TypeScript.NodeType.And: - return typeFlow.typeCheckArithmeticOperator(this, false); - case TypeScript.NodeType.Xor: - return typeFlow.typeCheckBitwiseOperator(this, false); - case TypeScript.NodeType.Ne: - case TypeScript.NodeType.Eq: - var text; - if(typeFlow.checker.styleSettings.eqeqeq) { - text = TypeScript.nodeTypeTable[this.nodeType]; - typeFlow.checker.errorReporter.styleError(this, "use of " + text); - } else if(typeFlow.checker.styleSettings.eqnull) { - text = TypeScript.nodeTypeTable[this.nodeType]; - if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { - typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); - } - } - case TypeScript.NodeType.Eqv: - case TypeScript.NodeType.NEqv: - case TypeScript.NodeType.Lt: - case TypeScript.NodeType.Le: - case TypeScript.NodeType.Ge: - case TypeScript.NodeType.Gt: - return typeFlow.typeCheckBooleanOperator(this); - case TypeScript.NodeType.Index: - return typeFlow.typeCheckIndex(this); - case TypeScript.NodeType.Member: - this.type = typeFlow.voidType; - return this; - case TypeScript.NodeType.LogOr: - return typeFlow.typeCheckLogOr(this); - case TypeScript.NodeType.LogAnd: - return typeFlow.typeCheckLogAnd(this); - case TypeScript.NodeType.AsgAdd: - case TypeScript.NodeType.AsgSub: - case TypeScript.NodeType.AsgMul: - case TypeScript.NodeType.AsgDiv: - case TypeScript.NodeType.AsgMod: - case TypeScript.NodeType.AsgOr: - case TypeScript.NodeType.AsgAnd: - return typeFlow.typeCheckArithmeticOperator(this, true); - case TypeScript.NodeType.AsgXor: - return typeFlow.typeCheckBitwiseOperator(this, true); - case TypeScript.NodeType.Lsh: - case TypeScript.NodeType.Rsh: - case TypeScript.NodeType.Rs2: - return typeFlow.typeCheckShift(this, false); - case TypeScript.NodeType.AsgLsh: - case TypeScript.NodeType.AsgRsh: - case TypeScript.NodeType.AsgRs2: - return typeFlow.typeCheckShift(this, true); - case TypeScript.NodeType.Comma: - return typeFlow.typeCheckCommaOperator(this); - case TypeScript.NodeType.InstOf: - return typeFlow.typeCheckInstOf(this); - case TypeScript.NodeType.In: - return typeFlow.typeCheckInOperator(this); - case TypeScript.NodeType.From: - typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); - break; - default: - throw new Error("please implement in derived class"); - } - return this; - }; - BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(binTokenId != undefined) { - emitter.emitJavascript(this.operand1, binTokenId, false); - if(TypeScript.tokenTable[binTokenId].text == "instanceof") { - emitter.writeToOutput(" instanceof "); - } else if(TypeScript.tokenTable[binTokenId].text == "in") { - emitter.writeToOutput(" in "); - } else { - emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); - } - emitter.emitJavascript(this.operand2, binTokenId, false); - } else { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: - if(!emitter.tryEmitConstant(this)) { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); - emitter.writeToOutput("."); - emitter.emitJavascriptName(this.operand2, false); - } - break; - case TypeScript.NodeType.Index: - emitter.emitIndex(this.operand1, this.operand2); - break; - case TypeScript.NodeType.Member: - if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { - var funcDecl = this.operand2; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - emitter.writeToOutput("get "); - } else { - emitter.writeToOutput("set "); - } - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - } else { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - emitter.writeToOutputTrimmable(": "); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - case TypeScript.NodeType.Comma: - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); - if(emitter.emitState.inObjectLiteral) { - emitter.writeLineToOutput(", "); - } else { - emitter.writeToOutput(","); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - case TypeScript.NodeType.Is: - throw new Error("should be de-sugared during type check"); - default: - throw new Error("please implement in derived class"); - } - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return BinaryExpression; - })(Expression); - TypeScript.BinaryExpression = BinaryExpression; - var ConditionalExpression = (function (_super) { - __extends(ConditionalExpression, _super); - function ConditionalExpression(operand1, operand2, operand3) { - _super.call(this, TypeScript.NodeType.ConditionalExpression); - this.operand1 = operand1; - this.operand2 = operand2; - this.operand3 = operand3; - } - ConditionalExpression.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckQMark(this); - }; - ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" ? "); - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" : "); - emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ConditionalExpression; - })(Expression); - TypeScript.ConditionalExpression = ConditionalExpression; - var NumberLiteral = (function (_super) { - __extends(NumberLiteral, _super); - function NumberLiteral(value, text) { - _super.call(this, TypeScript.NodeType.NumberLit); - this.value = value; - this.text = text; - } - NumberLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.doubleType; - return this; - }; - NumberLiteral.prototype.treeViewLabel = function () { - return "num: " + this.printLabel(); - }; - NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - NumberLiteral.prototype.printLabel = function () { - return this.text; - }; - return NumberLiteral; - })(Expression); - TypeScript.NumberLiteral = NumberLiteral; - var RegexLiteral = (function (_super) { - __extends(RegexLiteral, _super); - function RegexLiteral(text) { - _super.call(this, TypeScript.NodeType.Regex); - this.text = text; - } - RegexLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.regexType; - return this; - }; - RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return RegexLiteral; - })(Expression); - TypeScript.RegexLiteral = RegexLiteral; - var StringLiteral = (function (_super) { - __extends(StringLiteral, _super); - function StringLiteral(text) { - _super.call(this, TypeScript.NodeType.QString); - this.text = text; - } - StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitStringLiteral(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - StringLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.stringType; - return this; - }; - StringLiteral.prototype.treeViewLabel = function () { - return "st: " + this.text; - }; - StringLiteral.prototype.printLabel = function () { - return this.text; - }; - return StringLiteral; - })(Expression); - TypeScript.StringLiteral = StringLiteral; - var ModuleElement = (function (_super) { - __extends(ModuleElement, _super); - function ModuleElement(nodeType) { - _super.call(this, nodeType); - } - return ModuleElement; - })(AST); - TypeScript.ModuleElement = ModuleElement; - var ImportDeclaration = (function (_super) { - __extends(ImportDeclaration, _super); - function ImportDeclaration(id, alias) { - _super.call(this, TypeScript.NodeType.ImportDeclaration); - this.id = id; - this.alias = alias; - this.varFlags = TypeScript.VarFlags.None; - this.isDynamicImport = false; - } - ImportDeclaration.prototype.isStatementOrExpression = function () { - return true; - }; - ImportDeclaration.prototype.isDeclaration = function () { - return true; - }; - ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - var mod = this.alias.type; - if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { - var prevModAliasId = emitter.modAliasId; - var prevFirstModAlias = emitter.firstModAlias; - emitter.recordSourceMappingStart(this); - emitter.emitParensAndCommentsInPlace(this, true); - emitter.writeToOutput("var " + this.id.actualText + " = "); - emitter.modAliasId = this.id.actualText; - emitter.firstModAlias = this.firstAliasedModToString(); - emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); - if(!this.isDynamicImport) { - emitter.writeToOutput(";"); - } - emitter.emitParensAndCommentsInPlace(this, false); - emitter.recordSourceMappingEnd(this); - emitter.modAliasId = prevModAliasId; - emitter.firstModAlias = prevFirstModAlias; - } - }; - ImportDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckImportDecl(this); - }; - ImportDeclaration.prototype.getAliasName = function (aliasAST) { - if (typeof aliasAST === "undefined") { aliasAST = this.alias; } - if(aliasAST.nodeType == TypeScript.NodeType.Name) { - return (aliasAST).actualText; - } else { - var dotExpr = aliasAST; - return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); - } - }; - ImportDeclaration.prototype.firstAliasedModToString = function () { - if(this.alias.nodeType == TypeScript.NodeType.Name) { - return (this.alias).actualText; - } else { - var dotExpr = this.alias; - var firstMod = dotExpr.operand1; - return firstMod.actualText; - } - }; - return ImportDeclaration; - })(ModuleElement); - TypeScript.ImportDeclaration = ImportDeclaration; - var BoundDecl = (function (_super) { - __extends(BoundDecl, _super); - function BoundDecl(id, nodeType, nestingLevel) { - _super.call(this, nodeType); - this.id = id; - this.nestingLevel = nestingLevel; - this.init = null; - this.typeExpr = null; - this.varFlags = TypeScript.VarFlags.None; - this.sym = null; - } - BoundDecl.prototype.isDeclaration = function () { - return true; - }; - BoundDecl.prototype.isStatementOrExpression = function () { - return true; - }; - BoundDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); - }; - BoundDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); - }; - BoundDecl.prototype.isProperty = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); - }; - BoundDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckBoundDecl(this); - }; - BoundDecl.prototype.printLabel = function () { - return this.treeViewLabel(); - }; - return BoundDecl; - })(AST); - TypeScript.BoundDecl = BoundDecl; - var VarDecl = (function (_super) { - __extends(VarDecl, _super); - function VarDecl(id, nest) { - _super.call(this, id, TypeScript.NodeType.VarDecl, nest); - } - VarDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - VarDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - VarDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); - }; - VarDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptVarDecl(this, tokenId); - }; - VarDecl.prototype.treeViewLabel = function () { - return "var " + this.id.actualText; - }; - return VarDecl; - })(BoundDecl); - TypeScript.VarDecl = VarDecl; - var ArgDecl = (function (_super) { - __extends(ArgDecl, _super); - function ArgDecl(id) { - _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); - this.isOptional = false; - this.parameterPropertySym = null; - } - ArgDecl.prototype.isOptionalArg = function () { - return this.isOptional || this.init; - }; - ArgDecl.prototype.treeViewLabel = function () { - return "arg: " + this.id.actualText; - }; - ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ArgDecl; - })(BoundDecl); - TypeScript.ArgDecl = ArgDecl; - var internalId = 0; - var FuncDecl = (function (_super) { - __extends(FuncDecl, _super); - function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { - _super.call(this, nodeType); - this.name = name; - this.bod = bod; - this.isConstructor = isConstructor; - this.arguments = arguments; - this.vars = vars; - this.scopes = scopes; - this.statics = statics; - this.hint = null; - this.fncFlags = TypeScript.FncFlags.None; - this.returnTypeAnnotation = null; - this.variableArgList = false; - this.jumpRefs = null; - this.internalNameCache = null; - this.tmp1Declared = false; - this.enclosingFnc = null; - this.freeVariables = []; - this.unitIndex = -1; - this.classDecl = null; - this.boundToProperty = null; - this.isOverload = false; - this.innerStaticFuncs = []; - this.isInlineCallLiteral = false; - this.accessorSymbol = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.returnStatementsWithExpressions = []; - this.scopeType = null; - this.endingToken = null; - this.constructorSpan = null; - } - FuncDecl.prototype.isDeclaration = function () { - return true; - }; - FuncDecl.prototype.internalName = function () { - if(this.internalNameCache == null) { - var extName = this.getNameText(); - if(extName) { - this.internalNameCache = "_internal_" + extName; - } else { - this.internalNameCache = "_internal_" + internalId++; - } - } - return this.internalNameCache; - }; - FuncDecl.prototype.hasSelfReference = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); - }; - FuncDecl.prototype.setHasSelfReference = function () { - this.fncFlags |= TypeScript.FncFlags.HasSelfReference; - }; - FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); - }; - FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { - this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; - }; - FuncDecl.prototype.addCloRef = function (id, sym) { - if(this.envids == null) { - this.envids = new Array(); - } - this.envids[this.envids.length] = id; - var outerFnc = this.enclosingFnc; - if(sym) { - while(outerFnc && (outerFnc.type.symbol != sym.container)) { - outerFnc.addJumpRef(sym); - outerFnc = outerFnc.enclosingFnc; - } - } - return this.envids.length - 1; - }; - FuncDecl.prototype.addJumpRef = function (sym) { - if(this.jumpRefs == null) { - this.jumpRefs = new Array(); - } - var id = new Identifier(sym.name); - this.jumpRefs[this.jumpRefs.length] = id; - id.sym = sym; - id.cloId = this.addCloRef(id, null); - }; - FuncDecl.prototype.buildControlFlow = function () { - var entry = new TypeScript.BasicBlock(); - var exit = new TypeScript.BasicBlock(); - var context = new TypeScript.ControlFlowContext(entry, exit); - var controlFlowPrefix = function (ast, parent, walker) { - ast.addToControlFlow(walker.state); - return ast; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); - context.walker = walker; - walker.walk(this.bod, this); - return context; - }; - FuncDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFunction(this); - }; - FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptFunction(this); - }; - FuncDecl.prototype.getNameText = function () { - if(this.name) { - return this.name.actualText; - } else { - return this.hint; - } - }; - FuncDecl.prototype.isMethod = function () { - return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isCallMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); - }; - FuncDecl.prototype.isConstructMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); - }; - FuncDecl.prototype.isIndexerMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); - }; - FuncDecl.prototype.isSpecialFn = function () { - return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); - }; - FuncDecl.prototype.isAnonymousFn = function () { - return this.name === null; - }; - FuncDecl.prototype.isAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isGetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); - }; - FuncDecl.prototype.isSetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); - }; - FuncDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); - }; - FuncDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); - }; - FuncDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); - }; - FuncDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); - }; - FuncDecl.prototype.treeViewLabel = function () { - if(this.name == null) { - return "funcExpr"; - } else { - return "func: " + this.name.actualText; - } - }; - FuncDecl.prototype.ClearFlags = function () { - this.fncFlags = TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isSignature = function () { - return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; - }; - return FuncDecl; - })(AST); - TypeScript.FuncDecl = FuncDecl; - var LocationInfo = (function () { - function LocationInfo(filename, lineMap, unitIndex) { - this.filename = filename; - this.lineMap = lineMap; - this.unitIndex = unitIndex; - } - return LocationInfo; - })(); - TypeScript.LocationInfo = LocationInfo; - TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); - var Script = (function (_super) { - __extends(Script, _super); - function Script(vars, scopes) { - _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); - this.locationInfo = null; - this.referencedFiles = []; - this.requiresGlobal = false; - this.requiresExtendsBlock = false; - this.isResident = false; - this.isDeclareFile = false; - this.hasBeenTypeChecked = false; - this.topLevelMod = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.externallyVisibleImportedSymbols = []; - this.vars = vars; - } - Script.prototype.setCachedEmitRequired = function (value) { - this.cachedEmitRequired = value; - return this.cachedEmitRequired; - }; - Script.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckScript(this); - }; - Script.prototype.treeViewLabel = function () { - return "Script"; - }; - Script.prototype.emitRequired = function (emitOptions) { - if(this.cachedEmitRequired != undefined) { - return this.cachedEmitRequired; - } - if(!this.isDeclareFile && !this.isResident && this.bod) { - if(this.bod.members.length == 0) { - return this.setCachedEmitRequired(true); - } - for(var i = 0, len = this.bod.members.length; i < len; i++) { - var stmt = this.bod.members[i]; - if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { - if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType == TypeScript.NodeType.VarDecl) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { - if(!(stmt).isSignature()) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { - return this.setCachedEmitRequired(true); - } - } - if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { - return this.setCachedEmitRequired(true); - } - } - return this.setCachedEmitRequired(false); - }; - Script.prototype.emit = function (emitter, tokenId, startLine) { - if(this.emitRequired(emitter.emitOptions)) { - emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); - } - }; - Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { - if(this.isExternallyVisibleSymbol(symbol)) { - return; - } - if(!symbol.getType().symbol.isExternallyVisible(checker)) { - var quotes = ""; - var moduleName = symbol.getType().symbol.prettyName; - if(!TypeScript.isQuoted(moduleName)) { - quotes = "'"; - } - checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); - } - this.externallyVisibleImportedSymbols.push(symbol); - }; - Script.prototype.isExternallyVisibleSymbol = function (symbol) { - for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { - if(this.externallyVisibleImportedSymbols[i] == symbol) { - return true; - } - } - return false; - }; - return Script; - })(FuncDecl); - TypeScript.Script = Script; - var NamedDeclaration = (function (_super) { - __extends(NamedDeclaration, _super); - function NamedDeclaration(nodeType, name, members) { - _super.call(this, nodeType); - this.name = name; - this.members = members; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - } - NamedDeclaration.prototype.isDeclaration = function () { - return true; - }; - return NamedDeclaration; - })(ModuleElement); - TypeScript.NamedDeclaration = NamedDeclaration; - var ModuleDeclaration = (function (_super) { - __extends(ModuleDeclaration, _super); - function ModuleDeclaration(name, members, vars, endingToken) { - _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); - this.endingToken = endingToken; - this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; - this.amdDependencies = []; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.vars = vars; - this.prettyName = this.name.actualText; - } - ModuleDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); - }; - ModuleDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); - }; - ModuleDeclaration.prototype.isEnum = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); - }; - ModuleDeclaration.prototype.isWholeFile = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - ModuleDeclaration.prototype.recordNonInterface = function () { - this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - }; - ModuleDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckModule(this); - }; - ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.emitJavascriptModule(this); - emitter.emitParensAndCommentsInPlace(this, false); - } - }; - return ModuleDeclaration; - })(NamedDeclaration); - TypeScript.ModuleDeclaration = ModuleDeclaration; - var TypeDeclaration = (function (_super) { - __extends(TypeDeclaration, _super); - function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { - _super.call(this, nodeType, name, members); - this.extendsList = extendsList; - this.implementsList = implementsList; - this.varFlags = TypeScript.VarFlags.None; - } - TypeDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - TypeDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - return TypeDeclaration; - })(NamedDeclaration); - TypeScript.TypeDeclaration = TypeDeclaration; - var ClassDeclaration = (function (_super) { - __extends(ClassDeclaration, _super); - function ClassDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); - this.knownMemberNames = { - }; - this.constructorDecl = null; - this.constructorNestingLevel = 0; - this.endingToken = null; - } - ClassDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckClass(this); - }; - ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptClass(this); - }; - return ClassDeclaration; - })(TypeDeclaration); - TypeScript.ClassDeclaration = ClassDeclaration; - var InterfaceDeclaration = (function (_super) { - __extends(InterfaceDeclaration, _super); - function InterfaceDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); - } - InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckInterface(this); - }; - InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - }; - return InterfaceDeclaration; - })(TypeDeclaration); - TypeScript.InterfaceDeclaration = InterfaceDeclaration; - var Statement = (function (_super) { - __extends(Statement, _super); - function Statement(nodeType) { - _super.call(this, nodeType); - this.flags |= TypeScript.ASTFlags.IsStatement; - } - Statement.prototype.isLoop = function () { - return false; - }; - Statement.prototype.isStatementOrExpression = function () { - return true; - }; - Statement.prototype.isCompoundStatement = function () { - return this.isLoop(); - }; - Statement.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - return Statement; - })(ModuleElement); - TypeScript.Statement = Statement; - var LabeledStatement = (function (_super) { - __extends(LabeledStatement, _super); - function LabeledStatement(labels, stmt) { - _super.call(this, TypeScript.NodeType.LabeledStatement); - this.labels = labels; - this.stmt = stmt; - } - LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.labels) { - var labelsLen = this.labels.members.length; - for(var i = 0; i < labelsLen; i++) { - this.labels.members[i].emit(emitter, tokenId, startLine); - } - } - this.stmt.emit(emitter, tokenId, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - LabeledStatement.prototype.typeCheck = function (typeFlow) { - typeFlow.typeCheck(this.labels); - this.stmt = this.stmt.typeCheck(typeFlow); - return this; - }; - LabeledStatement.prototype.addToControlFlow = function (context) { - var beforeBB = context.current; - var bb = new TypeScript.BasicBlock(); - context.current = bb; - beforeBB.addSuccessor(bb); - }; - return LabeledStatement; - })(Statement); - TypeScript.LabeledStatement = LabeledStatement; - var Block = (function (_super) { - __extends(Block, _super); - function Block(statements, isStatementBlock) { - _super.call(this, TypeScript.NodeType.Block); - this.statements = statements; - this.isStatementBlock = isStatementBlock; - } - Block.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.isStatementBlock) { - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - } else { - emitter.setInVarBlock(this.statements.members.length); - } - var temp = emitter.setInObjectLiteral(false); - if(this.statements) { - emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); - } - if(this.isStatementBlock) { - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Block.prototype.addToControlFlow = function (context) { - var afterIfNeeded = new TypeScript.BasicBlock(); - context.pushStatement(this, context.current, afterIfNeeded); - if(this.statements) { - context.walk(this.statements, this); - } - context.walker.options.goChildren = false; - context.popStatement(); - if(afterIfNeeded.predecessors.length > 0) { - context.current.addSuccessor(afterIfNeeded); - context.current = afterIfNeeded; - } - }; - Block.prototype.typeCheck = function (typeFlow) { - if(!typeFlow.checker.styleSettings.emptyBlocks) { - if((this.statements === null) || (this.statements.members.length == 0)) { - typeFlow.checker.errorReporter.styleError(this, "empty block"); - } - } - typeFlow.typeCheck(this.statements); - return this; - }; - return Block; - })(Statement); - TypeScript.Block = Block; - var Jump = (function (_super) { - __extends(Jump, _super); - function Jump(nodeType) { - _super.call(this, nodeType); - this.target = null; - this.resolvedTarget = null; - } - Jump.prototype.hasExplicitTarget = function () { - return (this.target); - }; - Jump.prototype.setResolvedTarget = function (parser, stmt) { - if(stmt.isLoop()) { - this.resolvedTarget = stmt; - return true; - } - if(this.nodeType === TypeScript.NodeType.Continue) { - parser.reportParseError("continue statement applies only to loops"); - return false; - } else { - if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { - this.resolvedTarget = stmt; - return true; - } else { - parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); - return false; - } - } - }; - Jump.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); - }; - Jump.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.Break) { - emitter.writeToOutput("break"); - } else { - emitter.writeToOutput("continue"); - } - if(this.hasExplicitTarget()) { - emitter.writeToOutput(" " + this.target); - } - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Jump; - })(Statement); - TypeScript.Jump = Jump; - var WhileStatement = (function (_super) { - __extends(WhileStatement, _super); - function WhileStatement(cond) { - _super.call(this, TypeScript.NodeType.While); - this.cond = cond; - this.body = null; - } - WhileStatement.prototype.isLoop = function () { - return true; - }; - WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("while("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, false); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWhile(this); - }; - WhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - context.addContent(this.cond); - var condBlock = context.current; - var targetInfo = null; - if(this.body) { - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return WhileStatement; - })(Statement); - TypeScript.WhileStatement = WhileStatement; - var DoWhileStatement = (function (_super) { - __extends(DoWhileStatement, _super); - function DoWhileStatement() { - _super.call(this, TypeScript.NodeType.DoWhile); - this.body = null; - this.whileAST = null; - this.cond = null; - } - DoWhileStatement.prototype.isLoop = function () { - return true; - }; - DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("do"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingStart(this.whileAST); - emitter.writeToOutput("while"); - emitter.recordSourceMappingEnd(this.whileAST); - emitter.writeToOutput('('); - emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); - emitter.writeToOutput(")"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - DoWhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckDoWhile(this); - }; - DoWhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var targetInfo = null; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - context.addContent(this.cond); - context.current = afterLoop; - loopEnd.addSuccessor(afterLoop); - } else { - context.addUnreachable(this.cond); - } - context.walker.options.goChildren = false; - }; - return DoWhileStatement; - })(Statement); - TypeScript.DoWhileStatement = DoWhileStatement; - var IfStatement = (function (_super) { - __extends(IfStatement, _super); - function IfStatement(cond) { - _super.call(this, TypeScript.NodeType.If); - this.cond = cond; - this.elseBod = null; - this.statement = new ASTSpan(); - } - IfStatement.prototype.isCompoundStatement = function () { - return true; - }; - IfStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("if("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.thenBod, true); - if(this.elseBod) { - if(this.elseBod.nodeType === TypeScript.NodeType.If) { - emitter.writeToOutput(" else "); - this.elseBod.emit(emitter, tokenId, false); - } else { - emitter.writeToOutput(" else"); - emitter.emitJavascriptStatements(this.elseBod, true); - } - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - IfStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckIf(this); - }; - IfStatement.prototype.addToControlFlow = function (context) { - this.cond.addToControlFlow(context); - var afterIf = new TypeScript.BasicBlock(); - var beforeIf = context.current; - context.pushStatement(this, beforeIf, afterIf); - var hasContinuation = false; - context.current = new TypeScript.BasicBlock(); - beforeIf.addSuccessor(context.current); - context.walk(this.thenBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } - if(this.elseBod) { - context.current = new TypeScript.BasicBlock(); - context.noContinuation = false; - beforeIf.addSuccessor(context.current); - context.walk(this.elseBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } else { - if(hasContinuation) { - context.noContinuation = false; - } - } - } else { - beforeIf.addSuccessor(afterIf); - context.noContinuation = false; - hasContinuation = true; - } - var targetInfo = context.popStatement(); - if(afterIf.predecessors.length > 0) { - context.noContinuation = false; - hasContinuation = true; - } - if(hasContinuation) { - context.current = afterIf; - } - context.walker.options.goChildren = false; - }; - return IfStatement; - })(Statement); - TypeScript.IfStatement = IfStatement; - var ReturnStatement = (function (_super) { - __extends(ReturnStatement, _super); - function ReturnStatement() { - _super.call(this, TypeScript.NodeType.Return); - this.returnExpression = null; - } - ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - if(this.returnExpression) { - emitter.writeToOutput("return "); - emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); - if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { - emitter.writeToOutput(";"); - } - } else { - emitter.writeToOutput("return;"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ReturnStatement.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.returnStmt(); - }; - ReturnStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckReturn(this); - }; - return ReturnStatement; - })(Statement); - TypeScript.ReturnStatement = ReturnStatement; - var EndCode = (function (_super) { - __extends(EndCode, _super); - function EndCode() { - _super.call(this, TypeScript.NodeType.EndCode); - } - return EndCode; - })(AST); - TypeScript.EndCode = EndCode; - var ForInStatement = (function (_super) { - __extends(ForInStatement, _super); - function ForInStatement(lval, obj) { - _super.call(this, TypeScript.NodeType.ForIn); - this.lval = lval; - this.obj = obj; - this.statement = new ASTSpan(); - if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { - (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; - } - } - ForInStatement.prototype.isLoop = function () { - return true; - }; - ForInStatement.prototype.isFiltered = function () { - if(this.body) { - var singleItem = null; - if(this.body.nodeType == TypeScript.NodeType.List) { - var stmts = this.body; - if(stmts.members.length == 1) { - singleItem = stmts.members[0]; - } - } else { - singleItem = this.body; - } - if(singleItem !== null) { - if(singleItem.nodeType == TypeScript.NodeType.Block) { - var block = singleItem; - if((block.statements !== null) && (block.statements.members.length == 1)) { - singleItem = block.statements.members[0]; - } - } - if(singleItem.nodeType == TypeScript.NodeType.If) { - var cond = (singleItem).cond; - if(cond.nodeType == TypeScript.NodeType.Call) { - var target = (cond).target; - if(target.nodeType == TypeScript.NodeType.Dot) { - var binex = target; - if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { - var prop = binex.operand2; - if(prop.actualText == "hasOwnProperty") { - var args = (cond).arguments; - if((args !== null) && (args.members.length == 1)) { - var arg = args.members[0]; - if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { - if(((this.lval).actualText) == (arg).actualText) { - return true; - } - } - } - } - } - } - } - } - } - } - return false; - }; - ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("for("); - emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); - emitter.writeToOutput(" in "); - emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForInStatement.prototype.typeCheck = function (typeFlow) { - if(typeFlow.checker.styleSettings.forin) { - if(!this.isFiltered()) { - typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); - } - } - return typeFlow.typeCheckForIn(this); - }; - ForInStatement.prototype.addToControlFlow = function (context) { - if(this.lval) { - context.addContent(this.lval); - } - if(this.obj) { - context.addContent(this.obj); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - context.noContinuation = false; - loopHeader.addSuccessor(afterLoop); - context.walker.options.goChildren = false; - }; - return ForInStatement; - })(Statement); - TypeScript.ForInStatement = ForInStatement; - var ForStatement = (function (_super) { - __extends(ForStatement, _super); - function ForStatement(init) { - _super.call(this, TypeScript.NodeType.For); - this.init = init; - } - ForStatement.prototype.isLoop = function () { - return true; - }; - ForStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("for("); - if(this.init) { - if(this.init.nodeType != TypeScript.NodeType.List) { - emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); - } else { - emitter.setInVarBlock((this.init).members.length); - emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); - } - } - emitter.writeToOutput("; "); - emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); - emitter.writeToOutput("; "); - emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFor(this); - }; - ForStatement.prototype.addToControlFlow = function (context) { - if(this.init) { - context.addContent(this.init); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var condBlock = null; - var continueTarget = loopStart; - var incrBB = null; - if(this.incr) { - incrBB = new TypeScript.BasicBlock(); - continueTarget = incrBB; - } - if(this.cond) { - condBlock = context.current; - context.addContent(this.cond); - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - } - var targetInfo = null; - if(this.body) { - context.pushStatement(this, continueTarget, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(this.incr) { - if(context.noContinuation) { - if(incrBB.predecessors.length == 0) { - context.addUnreachable(this.incr); - } - } else { - context.current.addSuccessor(incrBB); - context.current = incrBB; - context.addContent(this.incr); - } - } - var loopEnd = context.current; - if(!(context.noContinuation)) { - loopEnd.addSuccessor(loopStart); - } - if(condBlock) { - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - } - if(afterLoop.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterLoop; - } - context.walker.options.goChildren = false; - }; - return ForStatement; - })(Statement); - TypeScript.ForStatement = ForStatement; - var WithStatement = (function (_super) { - __extends(WithStatement, _super); - function WithStatement(expr) { - _super.call(this, TypeScript.NodeType.With); - this.expr = expr; - this.withSym = null; - } - WithStatement.prototype.isCompoundStatement = function () { - return true; - }; - WithStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("with ("); - if(this.expr) { - emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); - } - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WithStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWith(this); - }; - return WithStatement; - })(Statement); - TypeScript.WithStatement = WithStatement; - var SwitchStatement = (function (_super) { - __extends(SwitchStatement, _super); - function SwitchStatement(val) { - _super.call(this, TypeScript.NodeType.Switch); - this.val = val; - this.defaultCase = null; - this.statement = new ASTSpan(); - } - SwitchStatement.prototype.isCompoundStatement = function () { - return true; - }; - SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("switch("); - emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - var casesLen = this.caseList.members.length; - for(var i = 0; i < casesLen; i++) { - var caseExpr = this.caseList.members[i]; - emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); - } - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - SwitchStatement.prototype.typeCheck = function (typeFlow) { - var len = this.caseList.members.length; - this.val = typeFlow.typeCheck(this.val); - for(var i = 0; i < len; i++) { - this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); - } - this.defaultCase = typeFlow.typeCheck(this.defaultCase); - this.type = typeFlow.voidType; - return this; - }; - SwitchStatement.prototype.addToControlFlow = function (context) { - var condBlock = context.current; - context.addContent(this.val); - var execBlock = new TypeScript.BasicBlock(); - var afterSwitch = new TypeScript.BasicBlock(); - condBlock.addSuccessor(execBlock); - context.pushSwitch(execBlock); - context.current = execBlock; - context.pushStatement(this, execBlock, afterSwitch); - context.walk(this.caseList, this); - context.popSwitch(); - var targetInfo = context.popStatement(); - var hasCondContinuation = (this.defaultCase == null); - if(this.defaultCase == null) { - condBlock.addSuccessor(afterSwitch); - } - if(afterSwitch.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterSwitch; - } else { - context.noContinuation = true; - } - context.walker.options.goChildren = false; - }; - return SwitchStatement; - })(Statement); - TypeScript.SwitchStatement = SwitchStatement; - var CaseStatement = (function (_super) { - __extends(CaseStatement, _super); - function CaseStatement() { - _super.call(this, TypeScript.NodeType.Case); - this.expr = null; - this.colonSpan = new ASTSpan(); - } - CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.expr) { - emitter.writeToOutput("case "); - emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); - } else { - emitter.writeToOutput("default"); - } - emitter.recordSourceMappingStart(this.colonSpan); - emitter.writeToOutput(":"); - emitter.recordSourceMappingEnd(this.colonSpan); - if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { - emitter.emitJavascriptStatements(this.body, false); - } else { - emitter.writeLineToOutput(""); - emitter.indenter.increaseIndent(); - emitter.emitBareJavascriptStatements(this.body); - emitter.indenter.decreaseIndent(); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - CaseStatement.prototype.typeCheck = function (typeFlow) { - this.expr = typeFlow.typeCheck(this.expr); - typeFlow.typeCheck(this.body); - this.type = typeFlow.voidType; - return this; - }; - CaseStatement.prototype.addToControlFlow = function (context) { - var execBlock = new TypeScript.BasicBlock(); - var sw = context.currentSwitch[context.currentSwitch.length - 1]; - if(this.expr) { - var exprBlock = new TypeScript.BasicBlock(); - context.current = exprBlock; - sw.addSuccessor(exprBlock); - context.addContent(this.expr); - exprBlock.addSuccessor(execBlock); - } else { - sw.addSuccessor(execBlock); - } - context.current = execBlock; - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return CaseStatement; - })(Statement); - TypeScript.CaseStatement = CaseStatement; - var TypeReference = (function (_super) { - __extends(TypeReference, _super); - function TypeReference(term, arrayCount) { - _super.call(this, TypeScript.NodeType.TypeRef); - this.term = term; - this.arrayCount = arrayCount; - } - TypeReference.prototype.emit = function (emitter, tokenId, startLine) { - throw new Error("should not emit a type ref"); - }; - TypeReference.prototype.typeCheck = function (typeFlow) { - var prevInTCTR = typeFlow.inTypeRefTypeCheck; - typeFlow.inTypeRefTypeCheck = true; - var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); - typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); - if(this.term) { - typeFlow.typeCheck(this.term); - } - typeFlow.checkForVoidConstructor(typeLink.type, this); - this.type = typeLink.type; - if(this.term) { - this.term.type = this.type; - } - typeFlow.inTypeRefTypeCheck = prevInTCTR; - return this; - }; - return TypeReference; - })(AST); - TypeScript.TypeReference = TypeReference; - var TryFinally = (function (_super) { - __extends(TryFinally, _super); - function TryFinally(tryNode, finallyNode) { - _super.call(this, TypeScript.NodeType.TryFinally); - this.tryNode = tryNode; - this.finallyNode = finallyNode; - } - TryFinally.prototype.isCompoundStatement = function () { - return true; - }; - TryFinally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - }; - TryFinally.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.finallyNode = typeFlow.typeCheck(this.finallyNode); - this.type = typeFlow.voidType; - return this; - }; - TryFinally.prototype.addToControlFlow = function (context) { - var afterFinally = new TypeScript.BasicBlock(); - context.walk(this.tryNode, this); - var finBlock = new TypeScript.BasicBlock(); - if(context.current) { - context.current.addSuccessor(finBlock); - } - context.current = finBlock; - context.pushStatement(this, null, afterFinally); - context.walk(this.finallyNode, this); - if(!context.noContinuation && context.current) { - context.current.addSuccessor(afterFinally); - } - if(afterFinally.predecessors.length > 0) { - context.current = afterFinally; - } else { - context.noContinuation = true; - } - context.popStatement(); - context.walker.options.goChildren = false; - }; - return TryFinally; - })(Statement); - TypeScript.TryFinally = TryFinally; - var TryCatch = (function (_super) { - __extends(TryCatch, _super); - function TryCatch(tryNode, catchNode) { - _super.call(this, TypeScript.NodeType.TryCatch); - this.tryNode = tryNode; - this.catchNode = catchNode; - } - TryCatch.prototype.isCompoundStatement = function () { - return true; - }; - TryCatch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - TryCatch.prototype.addToControlFlow = function (context) { - var beforeTry = context.current; - var tryBlock = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(tryBlock); - context.current = tryBlock; - var afterTryCatch = new TypeScript.BasicBlock(); - context.pushStatement(this, null, afterTryCatch); - context.walk(this.tryNode, this); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(context.current); - context.walk(this.catchNode, this); - context.popStatement(); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = afterTryCatch; - context.walker.options.goChildren = false; - }; - TryCatch.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.catchNode = typeFlow.typeCheck(this.catchNode); - this.type = typeFlow.voidType; - return this; - }; - return TryCatch; - })(Statement); - TypeScript.TryCatch = TryCatch; - var Try = (function (_super) { - __extends(Try, _super); - function Try(body) { - _super.call(this, TypeScript.NodeType.Try); - this.body = body; - } - Try.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("try "); - emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Try.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - Try.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - return Try; - })(Statement); - TypeScript.Try = Try; - var Catch = (function (_super) { - __extends(Catch, _super); - function Catch(param, body) { - _super.call(this, TypeScript.NodeType.Catch); - this.param = param; - this.body = body; - this.statement = new ASTSpan(); - this.containedScope = null; - if(this.param) { - this.param.varFlags |= TypeScript.VarFlags.AutoInit; - } - } - Catch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(" "); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("catch ("); - emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Catch.prototype.addToControlFlow = function (context) { - if(this.param) { - context.addContent(this.param); - var bodBlock = new TypeScript.BasicBlock(); - context.current.addSuccessor(bodBlock); - context.current = bodBlock; - } - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - Catch.prototype.typeCheck = function (typeFlow) { - var prevScope = typeFlow.scope; - typeFlow.scope = this.containedScope; - this.param = typeFlow.typeCheck(this.param); - var exceptVar = new TypeScript.ValueLocation(); - var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); - exceptVar.symbol = varSym; - exceptVar.typeLink = new TypeScript.TypeLink(); - exceptVar.typeLink.type = typeFlow.anyType; - var thisFnc = typeFlow.thisFnc; - if(thisFnc && thisFnc.type) { - exceptVar.symbol.container = thisFnc.type.symbol; - } else { - exceptVar.symbol.container = null; - } - this.param.sym = exceptVar.symbol; - typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); - this.body = typeFlow.typeCheck(this.body); - if(typeFlow.checker.inProvisionalTypecheckMode()) { - var table = typeFlow.scope.getTable(); - (table).secondaryTable.table[exceptVar.symbol.name] = undefined; - } - this.type = typeFlow.voidType; - typeFlow.scope = prevScope; - return this; - }; - return Catch; - })(Statement); - TypeScript.Catch = Catch; - var Finally = (function (_super) { - __extends(Finally, _super); - function Finally(body) { - _super.call(this, TypeScript.NodeType.Finally); - this.body = body; - } - Finally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("finally"); - emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Finally.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - Finally.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - return Finally; - })(Statement); - TypeScript.Finally = Finally; - var Comment = (function (_super) { - __extends(Comment, _super); - function Comment(content, isBlockComment, endsLine) { - _super.call(this, TypeScript.NodeType.Comment); - this.content = content; - this.isBlockComment = isBlockComment; - this.endsLine = endsLine; - this.text = null; - this.docCommentText = null; - } - Comment.prototype.getText = function () { - if(this.text == null) { - if(this.isBlockComment) { - this.text = this.content.split("\n"); - for(var i = 0; i < this.text.length; i++) { - this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); - } - } else { - this.text = [ - (this.content.replace(/^\s+|\s+$/g, '')) - ]; - } - } - return this.text; - }; - Comment.prototype.isDocComment = function () { - if(this.isBlockComment) { - return this.content.charAt(2) == "*" && this.content.charAt(3) != "/"; - } - return false; - }; - Comment.prototype.getDocCommentText = function () { - if(this.docCommentText == null) { - this.docCommentText = Comment.cleanJSDocComment(this.content); - } - return this.docCommentText; - }; - Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { - var endIndex = line.length; - if(maxSpacesToRemove != undefined) { - endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); - } - for(; startIndex < endIndex; startIndex++) { - var charCode = line.charCodeAt(startIndex); - if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { - return startIndex; - } - } - if(endIndex != line.length) { - return endIndex; - } - return -1; - }; - Comment.isSpaceChar = function isSpaceChar(line, index) { - var length = line.length; - if(index < length) { - var charCode = line.charCodeAt(index); - return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; - } - return index == length; - }; - Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { - var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); - if(nonSpaceIndex != -1) { - var jsDocSpacesRemoved = nonSpaceIndex; - if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { - var startIndex = nonSpaceIndex + 1; - nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); - if(nonSpaceIndex != -1) { - jsDocSpacesRemoved = nonSpaceIndex - startIndex; - } else { - return null; - } - } - return { - minChar: nonSpaceIndex, - limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, - jsDocSpacesRemoved: jsDocSpacesRemoved - }; - } - return null; - }; - Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { - var docCommentLines = []; - content = content.replace("/**", ""); - if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { - content = content.substring(0, content.length - 2); - } - var lines = content.split("\n"); - var inParamTag = false; - for(var l = 0; l < lines.length; l++) { - var line = lines[l]; - var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); - if(!cleanLinePos) { - continue; - } - var docCommentText = ""; - var prevPos = cleanLinePos.minChar; - for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { - var wasInParamtag = inParamTag; - if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { - if(!wasInParamtag) { - docCommentText += line.substring(prevPos, i); - } - prevPos = i; - inParamTag = true; - } else if(wasInParamtag) { - prevPos = i; - inParamTag = false; - } - } - if(!inParamTag) { - docCommentText += line.substring(prevPos, cleanLinePos.limChar); - } - var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); - if(newCleanPos) { - if(spacesToRemove == undefined) { - spacesToRemove = cleanLinePos.jsDocSpacesRemoved; - } - docCommentLines.push(docCommentText); - } - } - return docCommentLines.join("\n"); - }; - Comment.getDocCommentText = function getDocCommentText(comments) { - var docCommentText = []; - for(var c = 0; c < comments.length; c++) { - var commentText = comments[c].getDocCommentText(); - if(commentText != "") { - docCommentText.push(commentText); - } - } - return docCommentText.join("\n"); - }; - Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { - if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { - return ""; - } - for(var i = 0; i < fncDocComments.length; i++) { - var commentContents = fncDocComments[i].content; - for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { - j += 6; - if(!Comment.isSpaceChar(commentContents, j)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j); - if(j == -1) { - break; - } - if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { - j++; - var charCode = 0; - for(var curlies = 1; j < commentContents.length; j++) { - charCode = commentContents.charCodeAt(j); - if(charCode == TypeScript.LexCodeLC) { - curlies++; - continue; - } - if(charCode == TypeScript.LexCodeRC) { - curlies--; - if(curlies == 0) { - break; - } else { - continue; - } - } - if(charCode == TypeScript.LexCodeAtSign) { - break; - } - } - if(j == commentContents.length) { - break; - } - if(charCode == TypeScript.LexCodeAtSign) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + 1); - if(j == -1) { - break; - } - } - if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + param.length); - if(j == -1) { - return ""; - } - var endOfParam = commentContents.indexOf("@", j); - var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); - var paramSpacesToRemove = undefined; - var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; - if(paramLineIndex != 0) { - if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { - paramLineIndex++; - } - } - var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); - if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { - paramSpacesToRemove = j - startSpaceRemovalIndex - 1; - } - return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); - } - } - return ""; - }; - Comment.getDocCommentFirstOverloadSignature = function getDocCommentFirstOverloadSignature(signatureGroup) { - for(var i = 0; i < signatureGroup.signatures.length; i++) { - var signature = signatureGroup.signatures[i]; - if(signature == signatureGroup.definitionSignature) { - continue; - } - return TypeScript.Comment.getDocCommentText(signature.declAST.getDocComments()); - } - return ""; - }; - return Comment; - })(AST); - TypeScript.Comment = Comment; - var DebuggerStatement = (function (_super) { - __extends(DebuggerStatement, _super); - function DebuggerStatement() { - _super.call(this, TypeScript.NodeType.Debugger); - } - DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("debugger"); - emitter.recordSourceMappingEnd(this); - emitter.writeLineToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return DebuggerStatement; - })(Statement); - TypeScript.DebuggerStatement = DebuggerStatement; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstWalkOptions = (function () { - function AstWalkOptions() { - this.goChildren = true; - this.goNextSibling = true; - this.reverseSiblings = false; - } - AstWalkOptions.prototype.stopWalk = function (stop) { - if (typeof stop === "undefined") { stop = true; } - this.goChildren = !stop; - this.goNextSibling = !stop; - }; - return AstWalkOptions; - })(); - TypeScript.AstWalkOptions = AstWalkOptions; - var AstWalker = (function () { - function AstWalker(childrenWalkers, pre, post, options, state) { - this.childrenWalkers = childrenWalkers; - this.pre = pre; - this.post = post; - this.options = options; - this.state = state; - } - AstWalker.prototype.walk = function (ast, parent) { - var preAst = this.pre(ast, parent, this); - if(preAst === undefined) { - preAst = ast; - } - if(this.options.goChildren) { - var svGoSib = this.options.goNextSibling; - this.options.goNextSibling = true; - this.childrenWalkers[ast.nodeType](ast, parent, this); - this.options.goNextSibling = svGoSib; - } else { - this.options.goChildren = true; - } - if(this.post) { - var postAst = this.post(preAst, parent, this); - if(postAst === undefined) { - postAst = preAst; - } - return postAst; - } else { - return preAst; - } - }; - return AstWalker; - })(); - var AstWalkerFactory = (function () { - function AstWalkerFactory() { - this.childrenWalkers = []; - this.initChildrenWalkers(); - } - AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { - return this.getWalker(pre, post, options, state).walk(ast, null); - }; - AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { - return this.getSlowWalker(pre, post, options, state); - }; - AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { - if(!options) { - options = new AstWalkOptions(); - } - return new AstWalker(this.childrenWalkers, pre, post, options, state); - }; - AstWalkerFactory.prototype.initChildrenWalkers = function () { - this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; - this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; - this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; - this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; - this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; - this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; - this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; - this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; - this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; - this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; - this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; - this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; - this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; - this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; - this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; - for(var e in (TypeScript.NodeType)._map) { - if((this.childrenWalkers)[e] === undefined) { - throw new Error("initWalkers function is not up to date with enum content!"); - } - } - }; - return AstWalkerFactory; - })(); - TypeScript.AstWalkerFactory = AstWalkerFactory; - var globalAstWalkerFactory; - function getAstWalkerFactory() { - if(!globalAstWalkerFactory) { - globalAstWalkerFactory = new AstWalkerFactory(); - } - return globalAstWalkerFactory; - } - TypeScript.getAstWalkerFactory = getAstWalkerFactory; - var ChildrenWalkers; - (function (ChildrenWalkers) { - function walkNone(preAst, parent, walker) { - } - ChildrenWalkers.walkNone = walkNone; - function walkListChildren(preAst, parent, walker) { - var len = preAst.members.length; - if(walker.options.reverseSiblings) { - for(var i = len - 1; i >= 0; i--) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } else { - for(var i = 0; i < len; i++) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } - } - ChildrenWalkers.walkListChildren = walkListChildren; - function walkUnaryExpressionChildren(preAst, parent, walker) { - if(preAst.castTerm) { - preAst.castTerm = walker.walk(preAst.castTerm, preAst); - } - if(preAst.operand) { - preAst.operand = walker.walk(preAst.operand, preAst); - } - } - ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; - function walkBinaryExpressionChildren(preAst, parent, walker) { - if(walker.options.reverseSiblings) { - if(preAst.operand2) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if((preAst.operand1) && (walker.options.goNextSibling)) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - } else { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if((preAst.operand2) && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - } - } - ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; - function walkTypeReferenceChildren(preAst, parent, walker) { - if(preAst.term) { - preAst.term = walker.walk(preAst.term, preAst); - } - } - ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; - function walkCallExpressionChildren(preAst, parent, walker) { - if(!walker.options.reverseSiblings) { - preAst.target = walker.walk(preAst.target, preAst); - } - if(preAst.arguments && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { - preAst.target = walker.walk(preAst.target, preAst); - } - } - ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; - function walkTrinaryExpressionChildren(preAst, parent, walker) { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if(preAst.operand2 && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if(preAst.operand3 && (walker.options.goNextSibling)) { - preAst.operand3 = walker.walk(preAst.operand3, preAst); - } - } - ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; - function walkFuncDeclChildren(preAst, parent, walker) { - if(preAst.name) { - preAst.name = walker.walk(preAst.name, preAst); - } - if(preAst.arguments && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { - preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); - } - if(preAst.bod && (walker.options.goNextSibling)) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; - function walkBoundDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if((preAst.typeExpr) && (walker.options.goNextSibling)) { - preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); - } - } - ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; - function walkReturnStatementChildren(preAst, parent, walker) { - if(preAst.returnExpression) { - preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); - } - } - ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; - function walkForStatementChildren(preAst, parent, walker) { - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if(preAst.cond && walker.options.goNextSibling) { - preAst.cond = walker.walk(preAst.cond, preAst); - } - if(preAst.incr && walker.options.goNextSibling) { - preAst.incr = walker.walk(preAst.incr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; - function walkForInStatementChildren(preAst, parent, walker) { - preAst.lval = walker.walk(preAst.lval, preAst); - if(walker.options.goNextSibling) { - preAst.obj = walker.walk(preAst.obj, preAst); - } - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; - function walkIfStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.thenBod && (walker.options.goNextSibling)) { - preAst.thenBod = walker.walk(preAst.thenBod, preAst); - } - if(preAst.elseBod && (walker.options.goNextSibling)) { - preAst.elseBod = walker.walk(preAst.elseBod, preAst); - } - } - ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; - function walkWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; - function walkDoWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; - function walkBlockChildren(preAst, parent, walker) { - if(preAst.statements) { - preAst.statements = walker.walk(preAst.statements, preAst); - } - } - ChildrenWalkers.walkBlockChildren = walkBlockChildren; - function walkCaseStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; - function walkSwitchStatementChildren(preAst, parent, walker) { - if(preAst.val) { - preAst.val = walker.walk(preAst.val, preAst); - } - if((preAst.caseList) && walker.options.goNextSibling) { - preAst.caseList = walker.walk(preAst.caseList, preAst); - } - } - ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; - function walkTryChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkTryChildren = walkTryChildren; - function walkTryCatchChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if((preAst.catchNode) && walker.options.goNextSibling) { - preAst.catchNode = walker.walk(preAst.catchNode, preAst); - } - } - ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; - function walkTryFinallyChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if(preAst.finallyNode && walker.options.goNextSibling) { - preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); - } - } - ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; - function walkFinallyChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; - function walkCatchChildren(preAst, parent, walker) { - if(preAst.param) { - preAst.param = walker.walk(preAst.param, preAst); - } - if((preAst.body) && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCatchChildren = walkCatchChildren; - function walkRecordChildren(preAst, parent, walker) { - preAst.name = walker.walk(preAst.name, preAst); - if(walker.options.goNextSibling && preAst.members) { - preAst.members = walker.walk(preAst.members, preAst); - } - } - ChildrenWalkers.walkRecordChildren = walkRecordChildren; - function walkNamedTypeChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; - function walkClassDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; - function walkScriptChildren(preAst, parent, walker) { - if(preAst.bod) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkScriptChildren = walkScriptChildren; - function walkTypeDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; - function walkModuleDeclChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; - function walkImportDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.alias) { - preAst.alias = walker.walk(preAst.alias, preAst); - } - } - ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; - function walkWithStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; - function walkLabelChildren(preAst, parent, walker) { - } - ChildrenWalkers.walkLabelChildren = walkLabelChildren; - function walkLabeledStatementChildren(preAst, parent, walker) { - preAst.labels = walker.walk(preAst.labels, preAst); - if(walker.options.goNextSibling) { - preAst.stmt = walker.walk(preAst.stmt, preAst); - } - } - ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; - })(ChildrenWalkers || (ChildrenWalkers = {})); -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (AstWalkerWithDetailCallback) { - function walk(script, callback) { - var pre = function (cur, parent) { - walker.options.goChildren = AstWalkerCallback(true, cur, callback); - return cur; - }; - var post = function (cur, parent) { - AstWalkerCallback(false, cur, callback); - return cur; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); - walker.walk(script, null); - } - AstWalkerWithDetailCallback.walk = walk; - function AstWalkerCallback(pre, ast, callback) { - var nodeType = ast.nodeType; - var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; - if(callback[callbackString]) { - return callback[callbackString](pre, ast); - } - if(callback.DefaultCallback) { - return callback.DefaultCallback(pre, ast); - } - return true; - } - })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); - var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function lastOf(items) { - return (items === null || items.length === 0) ? null : items[items.length - 1]; - } - TypeScript.lastOf = lastOf; - function max(a, b) { - return a >= b ? a : b; - } - TypeScript.max = max; - function min(a, b) { - return a <= b ? a : b; - } - TypeScript.min = min; - var AstPath = (function () { - function AstPath() { - this.asts = []; - this.top = -1; - } - AstPath.reverseIndexOf = function reverseIndexOf(items, index) { - return (items === null || items.length <= index) ? null : items[items.length - index - 1]; - }; - AstPath.prototype.clone = function () { - var clone = new AstPath(); - clone.asts = this.asts.map(function (value) { - return value; - }); - clone.top = this.top; - return clone; - }; - AstPath.prototype.pop = function () { - var head = this.ast(); - this.up(); - while(this.asts.length > this.count()) { - this.asts.pop(); - } - return head; - }; - AstPath.prototype.push = function (ast) { - while(this.asts.length > this.count()) { - this.asts.pop(); - } - this.top = this.asts.length; - this.asts.push(ast); - }; - AstPath.prototype.up = function () { - if(this.top <= -1) { - throw new Error("Invalid call to 'up'"); - } - this.top--; - }; - AstPath.prototype.down = function () { - if(this.top == this.ast.length - 1) { - throw new Error("Invalid call to 'down'"); - } - this.top++; - }; - AstPath.prototype.nodeType = function () { - if(this.ast() == null) { - return TypeScript.NodeType.None; - } - return this.ast().nodeType; - }; - AstPath.prototype.ast = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); - }; - AstPath.prototype.parent = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); - }; - AstPath.prototype.count = function () { - return this.top + 1; - }; - AstPath.prototype.get = function (index) { - return this.asts[index]; - }; - AstPath.prototype.isNameOfClass = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfInterface = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfArgument = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfVariable = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfModule = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfFunction = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isChildOfScript = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; - }; - AstPath.prototype.isChildOfModule = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; - }; - AstPath.prototype.isChildOfClass = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; - }; - AstPath.prototype.isArgumentOfClassConstructor = function () { - var ast = lastOf(this.asts); - return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); - }; - AstPath.prototype.isChildOfInterface = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; - }; - AstPath.prototype.isTopLevelImplicitModule = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfScript = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfSwitch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfModule = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfClass = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfInterface = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfBlock = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFor = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCase = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfTry = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCatch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDoWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfForIn = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWith = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFinally = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; - }; - AstPath.prototype.isDefaultCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; - }; - AstPath.prototype.isListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfObjectLit = function () { - return this.isListOfObjectLit(); - }; - AstPath.prototype.isEmptyListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; - }; - AstPath.prototype.isMemberOfObjectLit = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; - }; - AstPath.prototype.isNameOfMemberOfObjectLit = function () { - return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; - }; - AstPath.prototype.isListOfArrayLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isTargetOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; - }; - AstPath.prototype.isMemberOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; - }; - AstPath.prototype.isItemOfList = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; - }; - AstPath.prototype.isThenOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isElseOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDefaultCase = function () { - return this.isBodyOfCase(); - }; - AstPath.prototype.isSingleStatementList = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; - }; - AstPath.prototype.isArgumentListOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentOfFunction = function () { - return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; - }; - AstPath.prototype.isArgumentListOfCall = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentListOfNew = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isSynthesizedBlock = function () { - return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; - }; - return AstPath; - })(); - TypeScript.AstPath = AstPath; - function isValidAstNode(ast) { - if(ast === null) { - return false; - } - if(ast.minChar === -1 || ast.limChar === -1) { - return false; - } - return true; - } - TypeScript.isValidAstNode = isValidAstNode; - var AstPathContext = (function () { - function AstPathContext() { - this.path = new TypeScript.AstPath(); - } - return AstPathContext; - })(); - TypeScript.AstPathContext = AstPathContext; - (function (GetAstPathOptions) { - GetAstPathOptions._map = []; - GetAstPathOptions.Default = 0; - GetAstPathOptions.EdgeInclusive = 1; - GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; - })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); - var GetAstPathOptions = TypeScript.GetAstPathOptions; - function getAstPathToPosition(script, pos, options) { - if (typeof options === "undefined") { options = GetAstPathOptions.Default; } - var lookInComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - var minChar = comments[i].minChar; - var limChar = comments[i].limChar; - if(!comments[i].isBlockComment) { - limChar++; - } - if(pos >= minChar && pos < limChar) { - ctx.path.push(comments[i]); - } - } - } - }; - var pre = function (cur, parent, walker) { - if(isValidAstNode(cur)) { - var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; - var minChar = cur.minChar; - var limChar = cur.limChar + (inclusive ? 1 : 0); - if(pos >= minChar && pos < limChar) { - var previous = ctx.path.ast(); - if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { - ctx.path.push(cur); - } else { - } - } - if(pos < limChar) { - lookInComments(cur.preComments); - } - if(pos >= minChar) { - lookInComments(cur.postComments); - } - if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { - walker.options.goChildren = (minChar <= pos && pos <= limChar); - } - } - return cur; - }; - var ctx = new AstPathContext(); - TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); - return ctx.path; - } - TypeScript.getAstPathToPosition = getAstPathToPosition; - function getTokenizationOffset(script, position) { - var bestOffset = 0; - var pre = function (cur, parent, walker) { - if(TypeScript.isValidAstNode(cur)) { - if(cur.minChar <= position) { - bestOffset = max(bestOffset, cur.minChar); - } - if(cur.minChar > position || cur.limChar < bestOffset) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return bestOffset; - } - TypeScript.getTokenizationOffset = getTokenizationOffset; - function walkAST(ast, callback) { - var pre = function (cur, parent, walker) { - var path = walker.state; - path.push(cur); - callback(path, walker); - return cur; - }; - var post = function (cur, parent, walker) { - var path = walker.state; - path.pop(); - return cur; - }; - var path = new AstPath(); - TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); - } - TypeScript.walkAST = walkAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstLogger = (function () { - function AstLogger(logger) { - this.logger = logger; - } - AstLogger.prototype.logScript = function (script) { - var _this = this; - this.logLinemap(script.locationInfo.lineMap); - var stack = []; - var pre = function (cur, parent) { - stack.push(cur); - var indent = (stack.length - 1) * 2; - _this.logComments(script, cur.preComments, indent); - _this.logNode(script, cur, indent); - _this.logComments(script, cur.postComments, indent); - return cur; - }; - var post = function (cur, parent) { - stack.pop(); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre, post); - }; - AstLogger.prototype.logNode = function (script, cur, indent) { - var msg = this.addPadding("", indent, "| ", true); - msg = msg.concat("+ " + cur.treeViewLabel()); - msg = this.addPadding(msg, 70, " ", false); - msg = msg + this.addLineColumn(script, cur.minChar); - msg = this.addPadding(msg, 80, " ", false); - msg = msg + "=> "; - msg = msg + this.addLineColumn(script, cur.limChar); - msg = this.addPadding(msg, 102, " ", false); - msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); - msg = this.addPadding(msg, 115, " ", false); - msg = msg.concat("sym=" + (cur).sym); - msg = this.addPadding(msg, 135, " ", false); - msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); - this.logger.log(msg); - }; - AstLogger.prototype.logComments = function (script, comments, indent) { - if(comments == null) { - return; - } - for(var i = 0; i < comments.length; i++) { - this.logNode(script, comments[i], indent); - } - }; - AstLogger.prototype.logLinemap = function (linemap) { - var result = "["; - for(var i = 0; i < linemap.length; i++) { - if(i > 0) { - result += ","; - } - result += linemap[i]; - } - result += "]"; - this.logger.log("linemap: " + result); - }; - AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { - var result = (leftPadding ? "" : s); - for(var i = s.length; i < targetLength; i++) { - result = result + paddingString; - } - result = result + (leftPadding ? s : ""); - return result; - }; - AstLogger.prototype.addLineColumn = function (script, position) { - var lineInfo = { - line: -1, - col: -1 - }; - TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); - if(lineInfo.col !== -1) { - lineInfo.col++; - } - return "(" + lineInfo.line + ", " + lineInfo.col + ")"; - }; - return AstLogger; - })(); - TypeScript.AstLogger = AstLogger; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Binder = (function () { - function Binder(checker) { - this.checker = checker; - } - Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { - var extendsList = null; - if(typeLinks) { - extendsList = new Array(); - for(var i = 0, len = typeLinks.length; i < len; i++) { - extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); - } - } - return extendsList; - }; - Binder.prototype.resolveBases = function (scope, type) { - type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); - var i = 0, len = type.extendsList.length; - var derivedIsClass = type.isClassInstance(); - for(; i < len; i++) { - var baseIsClass = type.extendsList[i].isClassInstance(); - if(type.extendsList[i] != this.checker.anyType) { - var baseRef = type.extendsTypeLinks[i].ast; - if(derivedIsClass) { - if(!baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); - } - } else { - if(baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); - } - } - } - } - type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); - if(type.implementsList) { - for(i = 0 , len = type.implementsList.length; i < len; i++) { - var iface = type.implementsList[i]; - var baseRef = type.implementsTypeLinks[i].ast; - if(iface.isClassInstance()) { - if(derivedIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); - } - } - } - } - }; - Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { - var supplyVar = !(signatureGroup.hasImplementation); - for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { - var signature = signatureGroup.signatures[i]; - if(instanceType) { - signature.returnType.type = instanceType; - } else { - this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - this.bindSymbol(scope, signature.parameters[j]); - } - if(signature.hasVariableArgList) { - var lastParam = signature.parameters[paramLen - 1]; - lastParam.argsOffset = paramLen - 1; - if(!lastParam.getType().isArray()) { - this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); - lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); - } - } - } - }; - Binder.prototype.bindType = function (scope, type, instanceType) { - if(instanceType) { - this.bindType(scope, instanceType, null); - } - var callAndConstructScope = scope; - if(type.hasMembers()) { - var members = type.members; - var ambientMembers = type.ambientMembers; - var typeMembers = type.getAllEnclosedTypes(); - var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); - var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); - var agg = new TypeScript.SymbolAggregateScope(type.symbol); - var prevCurrentModDecl = this.checker.currentModDecl; - var prevBindStatus = this.checker.inBind; - agg.addParentScope(memberScope); - agg.addParentScope(scope); - if(type.isModuleType()) { - this.checker.currentModDecl = type.symbol.declAST; - this.checker.inBind = true; - } - if(members) { - this.bind(agg, type.members.allMembers); - } - if(typeMembers) { - this.bind(agg, typeMembers.allMembers); - } - if(ambientMembers) { - this.bind(agg, ambientMembers.allMembers); - } - if(ambientTypeMembers) { - this.bind(agg, ambientTypeMembers.allMembers); - } - if(type.isModuleType()) { - callAndConstructScope = agg; - } - this.checker.currentModDecl = prevCurrentModDecl; - this.checker.inBind = prevBindStatus; - } - if(type.extendsTypeLinks) { - this.resolveBases(scope, type); - } - if(type.construct) { - this.resolveSignatureGroup(type.construct, callAndConstructScope, instanceType); - } - if(type.call) { - this.resolveSignatureGroup(type.call, callAndConstructScope, null); - } - if(type.index) { - this.resolveSignatureGroup(type.index, scope, null); - } - if(type.elementType) { - this.bindType(scope, type.elementType, null); - } - }; - Binder.prototype.bindSymbol = function (scope, symbol) { - if(!symbol.bound) { - var prevLocationInfo = this.checker.locationInfo; - if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[symbol.unitIndex]; - } - switch(symbol.kind()) { - case TypeScript.SymbolKind.Type: - if(symbol.flags & TypeScript.SymbolFlags.Bound) { - break; - } - var typeSymbol = symbol; - typeSymbol.flags |= TypeScript.SymbolFlags.Bound; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { - this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); - if(typeSymbol.type.isModuleType()) { - for(var i = 0; i < typeSymbol.expansions.length; i++) { - this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); - } - } - } - break; - case TypeScript.SymbolKind.Field: - this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); - break; - case TypeScript.SymbolKind.Parameter: - this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); - break; - } - this.checker.locationInfo = prevLocationInfo; - } - symbol.bound = true; - }; - Binder.prototype.bind = function (scope, table) { - table.map(function (key, sym, binder) { - binder.bindSymbol(scope, sym); - }, this); - }; - return Binder; - })(); - TypeScript.Binder = Binder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Base64Format = (function () { - function Base64Format() { } - Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - Base64Format.encode = function encode(inValue) { - if(inValue < 64) { - return Base64Format.encodedValues.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - }; - Base64Format.decodeChar = function decodeChar(inChar) { - if(inChar.length === 1) { - return Base64Format.encodedValues.indexOf(inChar); - } else { - throw TypeError('"' + inChar + '" must have length 1'); - } - }; - return Base64Format; - })(); - var Base64VLQFormat = (function () { - function Base64VLQFormat() { } - Base64VLQFormat.encode = function encode(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 + Base64Format.encode(currentDigit); - }while(inValue > 0); - return encodedStr; - }; - Base64VLQFormat.decode = function decode(inString) { - var result = 0; - var negative = false; - var shift = 0; - for(var i = 0; i < inString.length; i++) { - var byte = Base64Format.decodeChar(inString[i]); - if(i === 0) { - if((byte & 1) === 1) { - negative = true; - } - result = (byte >> 1) & 15; - } else { - result = result | ((byte & 31) << shift); - } - shift += (i == 0) ? 4 : 5; - if((byte & 32) === 32) { - } else { - return { - value: negative ? -(result) : result, - rest: inString.substr(i + 1) - }; - } - } - throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); - }; - return Base64VLQFormat; - })(); - TypeScript.Base64VLQFormat = Base64VLQFormat; -})(TypeScript || (TypeScript = {})); -var JSON2 = { -}; -((function () { - 'use strict'; - function f(n) { - return n < 10 ? '0' + n : n; - } - if(typeof Date.prototype.toJSON !== 'function') { - Date.prototype.toJSON = function (key) { - return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; - }; - var strProto = String.prototype; - var numProto = Number.prototype; - numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"': '\\"', - '\\': '\\\\' - }, rep; - function quote(string) { - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - function str(key, holder) { - var i, k = null, v, length, mind = gap, partial, value = holder[key]; - if(value && typeof value === 'object' && typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - if(typeof rep === 'function') { - value = rep.call(holder, key, value); - } - switch(typeof value) { - case 'string': - return quote(value); - case 'number': - return isFinite(value) ? String(value) : 'null'; - case 'boolean': - case 'null': - return String(value); - case 'object': - if(!value) { - return 'null'; - } - gap += indent; - partial = []; - if(Object.prototype.toString.apply(value, []) === '[object Array]') { - length = value.length; - for(i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - if(rep && typeof rep === 'object') { - length = rep.length; - for(i = 0; i < length; i += 1) { - if(typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - for(k in value) { - if(Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - if(typeof JSON2.stringify !== 'function') { - JSON2.stringify = function (value, replacer, space) { - var i; - gap = ''; - indent = ''; - if(typeof space === 'number') { - for(i = 0; i < space; i += 1) { - indent += ' '; - } - } else if(typeof space === 'string') { - indent = space; - } - rep = replacer; - if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - return str('', { - '': value - }); - }; - } -})()); -var TypeScript; -(function (TypeScript) { - var SourceMapPosition = (function () { - function SourceMapPosition() { } - return SourceMapPosition; - })(); - TypeScript.SourceMapPosition = SourceMapPosition; - var SourceMapping = (function () { - function SourceMapping() { - this.start = new SourceMapPosition(); - this.end = new SourceMapPosition(); - this.nameIndex = -1; - this.childMappings = []; - } - return SourceMapping; - })(); - TypeScript.SourceMapping = SourceMapping; - var SourceMapper = (function () { - function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter, emitFullPathOfSourceMap) { - this.jsFile = jsFile; - this.sourceMapOut = sourceMapOut; - this.errorReporter = errorReporter; - this.sourceMappings = []; - this.currentMappings = []; - this.names = []; - this.currentNameIndex = []; - this.currentMappings.push(this.sourceMappings); - jsFileName = TypeScript.switchToForwardSlashes(jsFileName); - this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); - var removalIndex = jsFileName.lastIndexOf(this.jsFileName); - var fixedPath = jsFileName.substring(0, removalIndex); - if(emitFullPathOfSourceMap) { - if(jsFileName.indexOf("://") == -1) { - jsFileName = "file:///" + jsFileName; - } - this.jsFileName = jsFileName; - } - this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); - } - SourceMapper.MapFileExtension = ".map"; - SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { - var sourceMapper = allSourceMappers[0]; - sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); - var sourceMapOut = sourceMapper.sourceMapOut; - var mappingsString = ""; - var tsFiles = []; - var prevEmittedColumn = 0; - var prevEmittedLine = 0; - var prevSourceColumn = 0; - var prevSourceLine = 0; - var prevSourceIndex = 0; - var prevNameIndex = 0; - var namesList = []; - var namesCount = 0; - var emitComma = false; - var recordedPosition = null; - for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { - sourceMapper = allSourceMappers[sourceMapperIndex]; - var currentSourceIndex = tsFiles.length; - tsFiles.push(sourceMapper.tsFileName); - if(sourceMapper.names.length > 0) { - namesList.push.apply(namesList, sourceMapper.names); - } - var recordSourceMapping = function (mappedPosition, nameIndex) { - if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { - return; - } - if(prevEmittedLine !== mappedPosition.emittedLine) { - while(prevEmittedLine < mappedPosition.emittedLine) { - prevEmittedColumn = 0; - mappingsString = mappingsString + ";"; - prevEmittedLine++; - } - emitComma = false; - } else if(emitComma) { - mappingsString = mappingsString + ","; - } - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); - prevEmittedColumn = mappedPosition.emittedColumn; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); - prevSourceIndex = currentSourceIndex; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); - prevSourceLine = mappedPosition.sourceLine - 1; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); - prevSourceColumn = mappedPosition.sourceColumn; - if(nameIndex >= 0) { - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); - prevNameIndex = namesCount + nameIndex; - } - emitComma = true; - recordedPosition = mappedPosition; - }; - var recordSourceMappingSiblings = function (sourceMappings) { - for(var i = 0; i < sourceMappings.length; i++) { - var sourceMapping = sourceMappings[i]; - recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); - recordSourceMappingSiblings(sourceMapping.childMappings); - recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); - } - }; - recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); - namesCount = namesCount + sourceMapper.names.length; - } - sourceMapOut.Write(JSON2.stringify({ - version: 3, - file: sourceMapper.jsFileName, - sources: tsFiles, - names: namesList, - mappings: mappingsString - })); - try { - sourceMapOut.Close(); - } catch (ex) { - sourceMapper.errorReporter.emitterError(null, ex.message); - } - }; - return SourceMapper; - })(); - TypeScript.SourceMapper = SourceMapper; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (EmitContainer) { - EmitContainer._map = []; - EmitContainer._map[0] = "Prog"; - EmitContainer.Prog = 0; - EmitContainer._map[1] = "Module"; - EmitContainer.Module = 1; - EmitContainer._map[2] = "DynamicModule"; - EmitContainer.DynamicModule = 2; - EmitContainer._map[3] = "Class"; - EmitContainer.Class = 3; - EmitContainer._map[4] = "Constructor"; - EmitContainer.Constructor = 4; - EmitContainer._map[5] = "Function"; - EmitContainer.Function = 5; - EmitContainer._map[6] = "Args"; - EmitContainer.Args = 6; - EmitContainer._map[7] = "Interface"; - EmitContainer.Interface = 7; - })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); - var EmitContainer = TypeScript.EmitContainer; - var EmitState = (function () { - function EmitState() { - this.column = 0; - this.line = 0; - this.pretty = false; - this.inObjectLiteral = false; - this.container = EmitContainer.Prog; - } - return EmitState; - })(); - TypeScript.EmitState = EmitState; - var EmitOptions = (function () { - function EmitOptions(settings) { - this.ioHost = null; - this.outputMany = true; - this.commonDirectoryPath = ""; - this.minWhitespace = settings.minWhitespace; - this.propagateConstants = settings.propagateConstants; - this.emitComments = settings.emitComments; - this.outputOption = settings.outputOption; - this.emitFullSourceMapPath = settings.emitFullSourceMapPath; - } - EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { - if(this.outputMany) { - var updatedFileName = fileName; - if(this.outputOption != "") { - updatedFileName = fileName.replace(this.commonDirectoryPath, ""); - updatedFileName = this.outputOption + updatedFileName; - } - return extensionChanger(updatedFileName, false); - } else { - return extensionChanger(this.outputOption, true); - } - }; - return EmitOptions; - })(); - TypeScript.EmitOptions = EmitOptions; - var Indenter = (function () { - function Indenter() { - this.indentAmt = 0; - } - Indenter.indentStep = 4; - Indenter.indentStepString = " "; - Indenter.indentStrings = []; - Indenter.prototype.increaseIndent = function () { - this.indentAmt += Indenter.indentStep; - }; - Indenter.prototype.decreaseIndent = function () { - this.indentAmt -= Indenter.indentStep; - }; - Indenter.prototype.getIndent = function () { - var indentString = Indenter.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { - indentString += Indenter.indentStepString; - } - Indenter.indentStrings[this.indentAmt] = indentString; - } - return indentString; - }; - return Indenter; - })(); - TypeScript.Indenter = Indenter; - var Emitter = (function () { - function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { - this.checker = checker; - this.emittingFileName = emittingFileName; - this.outfile = outfile; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.globalThisCapturePrologueEmitted = false; - this.extendsPrologueEmitted = false; - this.thisClassNode = null; - this.thisFnc = null; - this.moduleDeclList = []; - this.moduleName = ""; - this.emitState = new EmitState(); - this.indenter = new Indenter(); - this.ambientModule = false; - this.modAliasId = null; - this.firstModAlias = null; - this.allSourceMappers = []; - this.sourceMapper = null; - this.captureThisStmtString = "var _this = this;"; - this.varListCountStack = [ - 0 - ]; - } - Emitter.prototype.setSourceMappings = function (mapper) { - this.allSourceMappers.push(mapper); - this.sourceMapper = mapper; - }; - Emitter.prototype.writeToOutput = function (s) { - this.outfile.Write(s); - this.emitState.column += s.length; - }; - Emitter.prototype.writeToOutputTrimmable = function (s) { - if(this.emitOptions.minWhitespace) { - s = s.replace(/[\s]*/g, ''); - } - this.writeToOutput(s); - }; - Emitter.prototype.writeLineToOutput = function (s) { - if(this.emitOptions.minWhitespace) { - this.writeToOutput(s); - var c = s.charCodeAt(s.length - 1); - if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { - this.writeToOutput(' '); - } - } else { - this.outfile.WriteLine(s); - this.emitState.column = 0; - this.emitState.line++; - } - }; - Emitter.prototype.writeCaptureThisStatement = function (ast) { - this.emitIndent(); - this.recordSourceMappingStart(ast); - this.writeToOutput(this.captureThisStmtString); - this.recordSourceMappingEnd(ast); - this.writeLineToOutput(""); - }; - Emitter.prototype.setInVarBlock = function (count) { - this.varListCountStack[this.varListCountStack.length - 1] = count; - }; - Emitter.prototype.setInObjectLiteral = function (val) { - var temp = this.emitState.inObjectLiteral; - this.emitState.inObjectLiteral = val; - return temp; - }; - Emitter.prototype.setContainer = function (c) { - var temp = this.emitState.container; - this.emitState.container = c; - return temp; - }; - Emitter.prototype.getIndentString = function () { - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - Emitter.prototype.emitIndent = function () { - this.writeToOutput(this.getIndentString()); - }; - Emitter.prototype.emitCommentInPlace = function (comment) { - var text = comment.getText(); - var hadNewLine = false; - if(comment.isBlockComment) { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.recordSourceMappingStart(comment); - this.writeToOutput(text[0]); - if(text.length > 1 || comment.endsLine) { - for(var i = 1; i < text.length; i++) { - this.writeLineToOutput(""); - this.emitIndent(); - this.writeToOutput(text[i]); - } - this.recordSourceMappingEnd(comment); - this.writeLineToOutput(""); - hadNewLine = true; - } else { - this.recordSourceMappingEnd(comment); - } - } else { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.recordSourceMappingStart(comment); - this.writeToOutput(text[0]); - this.recordSourceMappingEnd(comment); - this.writeLineToOutput(""); - hadNewLine = true; - } - if(hadNewLine) { - this.emitIndent(); - } else { - this.writeToOutput(" "); - } - }; - Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { - var comments = pre ? ast.preComments : ast.postComments; - if(ast.isParenthesized && !pre) { - this.writeToOutput(")"); - } - if(this.emitOptions.emitComments && comments && comments.length != 0) { - for(var i = 0; i < comments.length; i++) { - this.emitCommentInPlace(comments[i]); - } - } - if(ast.isParenthesized && pre) { - this.writeToOutput("("); - } - }; - Emitter.prototype.emitObjectLiteral = function (content) { - this.writeLineToOutput("{"); - this.indenter.increaseIndent(); - var inObjectLiteral = this.setInObjectLiteral(true); - this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); - this.setInObjectLiteral(inObjectLiteral); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - }; - Emitter.prototype.emitArrayLiteral = function (content) { - this.writeToOutput("["); - if(content) { - this.writeLineToOutput(""); - this.indenter.increaseIndent(); - this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); - this.indenter.decreaseIndent(); - this.emitIndent(); - } - this.writeToOutput("]"); - }; - Emitter.prototype.emitNew = function (target, args) { - this.writeToOutput("new "); - if(target.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = target; - if(typeRef.arrayCount) { - this.writeToOutput("Array()"); - } else { - this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); - this.writeToOutput("()"); - } - } else { - this.emitJavascript(target, TypeScript.TokenID.Tilde, false); - this.recordSourceMappingStart(args); - this.writeToOutput("("); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } - }; - Emitter.prototype.getConstantValue = function (init) { - if(init) { - if(init.nodeType === TypeScript.NodeType.NumberLit) { - var numLit = init; - return numLit.value; - } else if(init.nodeType === TypeScript.NodeType.Lsh) { - var binop = init; - if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { - return (binop.operand1).value << (binop.operand2).value; - } - } else if(init.nodeType === TypeScript.NodeType.Name) { - var ident = init; - if(ident.sym !== null && ident.sym.declAST.nodeType === TypeScript.NodeType.VarDecl) { - var varDecl = ident.sym.declAST; - return this.getConstantValue(varDecl.init); - } - } - } - return null; - }; - Emitter.prototype.tryEmitConstant = function (dotExpr) { - if(!this.emitOptions.propagateConstants) { - return false; - } - var propertyName = dotExpr.operand2; - if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { - if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { - if(propertyName.sym.declAST) { - var boundDecl = propertyName.sym.declAST; - var value = this.getConstantValue(boundDecl.init); - if(value !== null) { - this.writeToOutput(value.toString()); - var comment = " /* "; - comment += propertyName.actualText; - comment += " */ "; - this.writeToOutput(comment); - return true; - } - } - } - } - return false; - }; - Emitter.prototype.emitCall = function (callNode, target, args) { - if(!this.emitSuperCall(callNode)) { - if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput("("); - } - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("_super.call"); - } else { - this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); - } - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput(")"); - } - this.recordSourceMappingStart(args); - this.writeToOutput("("); - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("this"); - if(args && args.members.length) { - this.writeToOutput(", "); - } - } - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } else { - this.indenter.decreaseIndent(); - this.indenter.decreaseIndent(); - var constructorCall = new TypeScript.ASTList(); - constructorCall.members[0] = callNode; - this.emitConstructorCalls(constructorCall, this.thisClassNode); - this.indenter.increaseIndent(); - this.indenter.increaseIndent(); - } - } - }; - Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - this.recordSourceMappingStart(classDecl); - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - baseSymbol = (baseExpr).target.type.symbol; - } else { - baseSymbol = baseExpr.type.symbol; - } - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.emitIndent(); - this.writeToOutput("_super.call(this"); - var args = (baseExpr).arguments; - if(args && (args.members.length > 0)) { - this.writeToOutput(", "); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - } else { - if(baseExpr.type && (baseExpr.type.isClassInstance())) { - this.emitIndent(); - this.writeToOutput(classDecl.name.actualText + "._super.constructor"); - this.writeToOutput(".call(this)"); - } - } - } - this.recordSourceMappingEnd(classDecl); - }; - Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { - var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); - var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); - this.emitParensAndCommentsInPlace(funcDecl, true); - if(shouldParenthesize) { - this.writeToOutput("("); - } - this.recordSourceMappingStart(funcDecl); - if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { - this.writeToOutput("function "); - } - if(printName) { - var id = funcDecl.getNameText(); - if(id && !funcDecl.isAccessor()) { - if(funcDecl.name) { - this.recordSourceMappingStart(funcDecl.name); - } - this.writeToOutput(id); - if(funcDecl.name) { - this.recordSourceMappingEnd(funcDecl.name); - } - } - } - this.writeToOutput("("); - var argsLen = 0; - var i = 0; - var arg; - var defaultArgs = []; - if(funcDecl.arguments) { - var tempContainer = this.setContainer(EmitContainer.Args); - argsLen = funcDecl.arguments.members.length; - var printLen = argsLen; - if(funcDecl.variableArgList) { - printLen--; - } - for(i = 0; i < printLen; i++) { - arg = funcDecl.arguments.members[i]; - if(arg.init) { - defaultArgs.push(arg); - } - this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); - if(i < (printLen - 1)) { - this.writeToOutput(", "); - } - } - this.setContainer(tempContainer); - } - this.writeLineToOutput(") {"); - if(funcDecl.isConstructor) { - this.recordSourceMappingNameStart("constructor"); - } else if(funcDecl.isGetAccessor()) { - this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); - } else if(funcDecl.isSetAccessor()) { - this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); - } else { - this.recordSourceMappingNameStart(funcDecl.getNameText()); - } - this.indenter.increaseIndent(); - for(i = 0; i < defaultArgs.length; i++) { - var arg = defaultArgs[i]; - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); - this.writeLineToOutput("; }"); - this.recordSourceMappingEnd(arg); - } - if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { - if(funcDecl.arguments) { - argsLen = funcDecl.arguments.members.length; - for(i = 0; i < argsLen; i++) { - arg = funcDecl.arguments.members[i]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - this.emitConstructorCalls(bases, classDecl); - } - } - if(hasSelfRef) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.variableArgList) { - argsLen = funcDecl.arguments.members.length; - var lastArg = funcDecl.arguments.members[argsLen - 1]; - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var "); - this.recordSourceMappingStart(lastArg.id); - this.writeToOutput(lastArg.id.actualText); - this.recordSourceMappingEnd(lastArg.id); - this.writeLineToOutput(" = [];"); - this.recordSourceMappingEnd(lastArg); - this.emitIndent(); - this.writeToOutput("for ("); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var _i = 0;"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput(" "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput("; "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i++"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(") {"); - this.indenter.increaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { - var nProps = (this.thisClassNode.members).members.length; - for(var i = 0; i < nProps; i++) { - if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(funcDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(funcDecl.endingToken); - this.recordSourceMappingEnd(funcDecl); - if(shouldParenthesize) { - this.writeToOutput(")"); - } - this.recordSourceMappingEnd(funcDecl); - this.emitParensAndCommentsInPlace(funcDecl, false); - if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isConstructor)) { - this.writeLineToOutput(""); - } else if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { - if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { - this.writeLineToOutput(";"); - } - } - }; - Emitter.prototype.emitJavascriptModule = function (moduleDecl) { - var modName = moduleDecl.name.actualText; - if(TypeScript.isTSFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 3)); - } else if(TypeScript.isSTRFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 4)); - } - if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { - var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); - var prevOutFile = this.outfile; - var prevOutFileName = this.emittingFileName; - var prevAllSourceMappers = this.allSourceMappers; - var prevSourceMapper = this.sourceMapper; - var prevColumn = this.emitState.column; - var prevLine = this.emitState.line; - var temp = this.setContainer(EmitContainer.Module); - var svModuleName = this.moduleName; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; - var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); - this.moduleName = moduleDecl.name.actualText; - if(isDynamicMod) { - var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); - var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; - modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); - if(this.emitOptions.ioHost) { - if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { - this.emittingFileName = modFilePath; - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); - if(prevSourceMapper != null) { - this.allSourceMappers = []; - var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); - this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter, this.emitOptions.emitFullSourceMapPath)); - this.emitState.column = 0; - this.emitState.line = 0; - } - } else { - TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); - } - } - this.setContainer(EmitContainer.DynamicModule); - this.recordSourceMappingStart(moduleDecl); - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - var dependencyList = "[\"require\", \"exports\""; - var importList = "require, exports"; - var importStatement = null; - for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { - importStatement = (moduleDecl.mod).importedModules[i]; - if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { - if(i <= (moduleDecl.mod).importedModules.length - 1) { - dependencyList += ", "; - importList += ", "; - } - importList += "__" + importStatement.id.actualText + "__"; - dependencyList += importStatement.firstAliasedModToString(); - } - } - for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { - dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; - } - dependencyList += "]"; - this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); - } else { - } - } else { - if(!isExported) { - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("var "); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(moduleDecl); - this.emitIndent(); - } - this.writeToOutput("("); - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("function ("); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(") {"); - } - if(!isWholeFile) { - this.recordSourceMappingNameStart(this.moduleName); - } - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.increaseIndent(); - } - if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { - this.writeCaptureThisStatement(moduleDecl); - } - this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.decreaseIndent(); - } - this.emitIndent(); - if(isDynamicMod) { - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("})"); - } else { - } - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl); - if(this.outfile != prevOutFile) { - this.Close(); - if(prevSourceMapper != null) { - this.allSourceMappers = prevAllSourceMappers; - this.sourceMapper = prevSourceMapper; - this.emitState.column = prevColumn; - this.emitState.line = prevLine; - } - this.outfile = prevOutFile; - this.emittingFileName = prevOutFileName; - } - } else { - var containingMod = null; - if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { - containingMod = moduleDecl.type.symbol.container.declAST; - } - var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); - this.recordSourceMappingStart(moduleDecl.endingToken); - if(temp == EmitContainer.Prog && isExported) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); - } else if(isExported || temp == EmitContainer.Prog) { - var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); - } else if(!isExported && temp != EmitContainer.Prog) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); - } else { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")();"); - } - this.recordSourceMappingEnd(moduleDecl); - this.writeLineToOutput(""); - if(temp != EmitContainer.Prog && isExported) { - this.emitIndent(); - this.recordSourceMappingStart(moduleDecl); - if(parentIsDynamic) { - this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); - } else { - this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); - } - this.recordSourceMappingEnd(moduleDecl); - } - } - this.setContainer(temp); - this.moduleName = svModuleName; - this.moduleDeclList.length--; - } - }; - Emitter.prototype.emitIndex = function (operand1, operand2) { - var temp = this.setInObjectLiteral(false); - this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); - this.writeToOutput("["); - this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput("]"); - this.setInObjectLiteral(temp); - }; - Emitter.prototype.emitStringLiteral = function (text) { - this.writeToOutput(text); - }; - Emitter.prototype.emitJavascriptFunction = function (funcDecl) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { - return; - } - var temp; - var tempFnc = this.thisFnc; - this.thisFnc = funcDecl; - if(funcDecl.isConstructor) { - temp = this.setContainer(EmitContainer.Constructor); - } else { - temp = this.setContainer(EmitContainer.Function); - } - var bases = null; - var hasSelfRef = false; - var funcName = funcDecl.getNameText(); - if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { - var tempLit = this.setInObjectLiteral(false); - if(this.thisClassNode) { - bases = this.thisClassNode.extendsList; - } - hasSelfRef = Emitter.shouldCaptureThis(funcDecl); - this.recordSourceMappingStart(funcDecl); - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { - this.writeToOutput("this." + funcName + " = "); - this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); - } else { - this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); - } - this.setInObjectLiteral(tempLit); - } - this.setContainer(temp); - this.thisFnc = tempFnc; - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { - if(this.thisClassNode) { - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - } else if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { - this.emitIndent(); - var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - }; - Emitter.prototype.emitAmbientVarDecl = function (varDecl) { - if(varDecl.init) { - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.recordSourceMappingEnd(varDecl); - this.writeToOutput(";"); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.varListCount = function () { - return this.varListCountStack[this.varListCountStack.length - 1]; - }; - Emitter.prototype.emitVarDeclVar = function () { - if(this.varListCount() >= 0) { - this.writeToOutput("var "); - this.setInVarBlock(-this.varListCount()); - } - return true; - }; - Emitter.prototype.onEmitVar = function () { - if(this.varListCount() > 0) { - this.setInVarBlock(this.varListCount() - 1); - } else if(this.varListCount() < 0) { - this.setInVarBlock(this.varListCount() + 1); - } - }; - Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { - if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { - this.emitAmbientVarDecl(varDecl); - this.onEmitVar(); - } else { - var sym = varDecl.sym; - var hasInitializer = (varDecl.init != null); - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { - var type = (sym.container).type; - if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { - if(this.emitState.container != EmitContainer.Args) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { - this.writeToOutput(sym.container.name + "."); - } else { - this.writeToOutput("this."); - } - } - } else if(type.hasImplementation()) { - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - this.emitVarDeclVar(); - } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { - this.writeToOutput("."); - } else { - if(this.emitState.container == EmitContainer.DynamicModule) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(this.moduleName + "."); - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { - this.writeToOutput("this."); - } else { - this.emitVarDeclVar(); - } - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - this.emitVarDeclVar(); - } - } - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - if(hasInitializer) { - this.writeToOutputTrimmable(" = "); - this.varListCountStack.push(0); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.varListCountStack.pop(); - } - this.onEmitVar(); - if((tokenId != TypeScript.TokenID.OpenParen)) { - if(this.varListCount() < 0) { - this.writeToOutput(", "); - } else if(tokenId != TypeScript.TokenID.For) { - this.writeToOutputTrimmable(";"); - } - } - this.recordSourceMappingEnd(varDecl); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.declEnclosed = function (moduleDecl) { - if(moduleDecl == null) { - return true; - } - for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { - if(this.moduleDeclList[i] == moduleDecl) { - return true; - } - } - return false; - }; - Emitter.prototype.emitJavascriptName = function (name, addThis) { - var sym = name.sym; - this.emitParensAndCommentsInPlace(name, true); - this.recordSourceMappingStart(name); - if(!name.isMissing()) { - if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { - if(sym.container && (sym.container.name != TypeScript.globalId)) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } else if(sym.kind() == TypeScript.SymbolKind.Field) { - var fieldSym = sym; - if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { - if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { - if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } - } else { - if(sym.isInstanceProperty()) { - this.emitThis(); - this.writeToOutput("."); - } - } - } else if(sym.kind() == TypeScript.SymbolKind.Type) { - if(sym.isInstanceProperty()) { - var typeSym = sym; - var type = typeSym.type; - if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { - this.emitThis(); - this.writeToOutput("."); - } - } else if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { - this.writeToOutput(sym.container.name + "."); - } - } - } else if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { - this.writeToOutput("this."); - } - } - if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { - var moduleDecl = sym.declAST; - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("__" + this.modAliasId + "__;"); - } else { - var modPath = name.actualText; - var isSingleQuotedMod = TypeScript.isSingleQuoted(modPath); - var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); - modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); - modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); - if(isSingleQuotedMod) { - modPath = TypeScript.changeToSingleQuote(modPath); - } - this.writeToOutput("require(" + modPath + ")"); - } - } else { - this.writeToOutput(name.actualText); - } - } - this.recordSourceMappingEnd(name); - this.emitParensAndCommentsInPlace(name, false); - }; - Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { - if(stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); - if(emitEmptyBod || hasContents) { - var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); - this.recordSourceMappingStart(stmts); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(" {"); - this.indenter.increaseIndent(); - } - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - } - this.recordSourceMappingEnd(stmts); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else if(emitEmptyBod) { - this.writeToOutput("{ }"); - } - }; - Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if(stmts.nodeType != TypeScript.NodeType.Block) { - if(stmts.nodeType == TypeScript.NodeType.List) { - var stmtList = stmts; - if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { - this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); - this.writeLineToOutput(""); - } else { - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - }; - Emitter.prototype.recordSourceMappingNameStart = function (name) { - if(this.sourceMapper) { - var finalName = name; - if(!name) { - finalName = ""; - } else if(this.sourceMapper.currentNameIndex.length > 0) { - finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]] + "." + name; - } - this.sourceMapper.names.push(finalName); - this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); - } - }; - Emitter.prototype.recordSourceMappingNameEnd = function () { - if(this.sourceMapper) { - this.sourceMapper.currentNameIndex.pop(); - } - }; - Emitter.prototype.recordSourceMappingStart = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - var lineCol = { - line: -1, - col: -1 - }; - var sourceMapping = new TypeScript.SourceMapping(); - sourceMapping.start.emittedColumn = this.emitState.column; - sourceMapping.start.emittedLine = this.emitState.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); - sourceMapping.start.sourceColumn = lineCol.col; - sourceMapping.start.sourceLine = lineCol.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); - sourceMapping.end.sourceColumn = lineCol.col; - sourceMapping.end.sourceLine = lineCol.line; - if(this.sourceMapper.currentNameIndex.length > 0) { - sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; - } - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - siblings.push(sourceMapping); - this.sourceMapper.currentMappings.push(sourceMapping.childMappings); - } - }; - Emitter.prototype.recordSourceMappingEnd = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - this.sourceMapper.currentMappings.pop(); - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - var sourceMapping = siblings[siblings.length - 1]; - sourceMapping.end.emittedColumn = this.emitState.column; - sourceMapping.end.emittedLine = this.emitState.line; - } - }; - Emitter.prototype.Close = function () { - if(this.sourceMapper != null) { - TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); - } - try { - this.outfile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if (typeof emitPrologue === "undefined") { emitPrologue = false; } - if(ast == null) { - return; - } else if(ast.nodeType != TypeScript.NodeType.List) { - this.emitPrologue(emitPrologue); - this.emitJavascript(ast, tokenId, startLine); - } else { - var list = ast; - this.emitParensAndCommentsInPlace(ast, true); - if(list.members.length == 0) { - this.emitParensAndCommentsInPlace(ast, false); - return; - } - var len = list.members.length; - for(var i = 0; i < len; i++) { - if(emitPrologue) { - if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { - this.emitPrologue(requiresExtendsBlock); - emitPrologue = false; - } - } - if(i == 1 && emitClassPropertiesAfterSuperCall) { - var constructorDecl = (this.thisClassNode).constructorDecl; - if(constructorDecl && constructorDecl.arguments) { - var argsLen = constructorDecl.arguments.members.length; - for(var iArg = 0; iArg < argsLen; iArg++) { - var arg = constructorDecl.arguments.members[iArg]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - var nProps = (this.thisClassNode.members).members.length; - for(var iMember = 0; iMember < nProps; iMember++) { - if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[iMember]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - var emitNode = list.members[i]; - var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); - if(onlyStatics ? !isStaticDecl : isStaticDecl) { - continue; - } - this.emitJavascript(emitNode, tokenId, startLine); - if(delimiter && (i < (len - 1))) { - if(startLine) { - this.writeLineToOutput(delimiter); - } else { - this.writeToOutput(delimiter); - } - } else if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { - this.writeLineToOutput(""); - } - } - this.emitParensAndCommentsInPlace(ast, false); - } - }; - Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { - if(ast == null) { - return; - } - if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { - if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { - this.emitIndent(); - } - } - ast.emit(this, tokenId, startLine); - if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { - this.writeToOutput(";"); - } - }; - Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { - if(!(funcDecl.accessorSymbol).hasBeenEmitted) { - var accessorSymbol = funcDecl.accessorSymbol; - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); - this.indenter.increaseIndent(); - if(accessorSymbol.getter) { - var getter = accessorSymbol.getter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(getter); - this.writeToOutput("get: "); - this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); - this.writeLineToOutput(","); - } - if(accessorSymbol.setter) { - var setter = accessorSymbol.setter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(setter); - this.writeToOutput("set: "); - this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); - this.writeLineToOutput(","); - } - this.emitIndent(); - this.writeLineToOutput("enumerable: true,"); - this.emitIndent(); - this.writeLineToOutput("configurable: true"); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("});"); - this.recordSourceMappingEnd(funcDecl); - accessorSymbol.hasBeenEmitted = true; - } - }; - Emitter.prototype.emitPrototypeMember = function (member, className) { - if(member.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = member; - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, className, true); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); - this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); - this.writeLineToOutput(";"); - } - } else if(member.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = member; - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(className + ".prototype." + varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.recordSourceMappingEnd(varDecl); - this.writeLineToOutput(";"); - } - } - }; - Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { - if(base.members) { - var baseSymbol = base.symbol; - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - base.members.allMembers.map(function (key, s, c) { - var sym = s; - if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { - this.recordSourceMappingStart(sym.declAST); - this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); - this.recordSourceMappingEnd(sym.declAST); - } - }, null); - } - if(base.extendsList) { - for(var i = 0, len = base.extendsList.length; i < len; i++) { - this.emitAddBaseMethods(className, base.extendsList[i], classDecl); - } - } - }; - Emitter.prototype.emitJavascriptClass = function (classDecl) { - if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { - var svClassNode = this.thisClassNode; - var i = 0; - this.thisClassNode = classDecl; - var className = classDecl.name.actualText; - this.emitParensAndCommentsInPlace(classDecl, true); - var temp = this.setContainer(EmitContainer.Class); - this.recordSourceMappingStart(classDecl); - if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { - this.writeToOutput("this." + className); - } else { - this.writeToOutput("var " + className); - } - var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; - var baseNameDecl = null; - var baseName = null; - if(hasBaseClass) { - this.writeLineToOutput(" = (function (_super) {"); - } else { - this.writeLineToOutput(" = (function () {"); - } - this.recordSourceMappingNameStart(className); - this.indenter.increaseIndent(); - if(hasBaseClass) { - baseNameDecl = classDecl.extendsList.members[0]; - baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; - this.emitIndent(); - this.writeLineToOutput("__extends(" + className + ", _super);"); - } - this.emitIndent(); - var constrDecl = classDecl.constructorDecl; - if(constrDecl) { - this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); - } else { - var wroteProps = 0; - this.recordSourceMappingStart(classDecl); - this.indenter.increaseIndent(); - this.writeToOutput("function " + classDecl.name.actualText + "() {"); - this.recordSourceMappingNameStart("constructor"); - if(hasBaseClass) { - this.writeLineToOutput(""); - this.emitIndent(); - this.writeLineToOutput("_super.apply(this, arguments);"); - wroteProps++; - } - if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { - this.writeCaptureThisStatement(classDecl); - } - var members = (this.thisClassNode.members).members; - for(var i = 0; i < members.length; i++) { - if(members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.writeLineToOutput(""); - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - wroteProps++; - } - } - } - if(wroteProps) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } else { - this.writeLineToOutput(" }"); - this.indenter.decreaseIndent(); - } - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl); - } - var membersLen = classDecl.members.members.length; - for(var j = 0; j < membersLen; j++) { - var memberDecl = classDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var fn = memberDecl; - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { - if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { - this.emitPrototypeMember(fn, className); - } else { - if(fn.isAccessor()) { - this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(fn); - this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); - this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); - this.writeLineToOutput(";"); - } - } - } - } else if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = memberDecl; - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(varDecl); - } - } - } else { - throw Error("We want to catch this"); - } - } - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeLineToOutput("return " + className + ";"); - this.recordSourceMappingEnd(classDecl.endingToken); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl.endingToken); - this.recordSourceMappingStart(classDecl); - this.writeToOutput(")("); - if(hasBaseClass) { - this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); - } - this.writeToOutput(");"); - this.recordSourceMappingEnd(classDecl); - if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { - this.writeLineToOutput(""); - this.emitIndent(); - var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(classDecl); - this.writeToOutput(modName + "." + className + " = " + className + ";"); - this.recordSourceMappingEnd(classDecl); - } - this.emitIndent(); - this.recordSourceMappingEnd(classDecl); - this.emitParensAndCommentsInPlace(classDecl, false); - this.setContainer(temp); - this.thisClassNode = svClassNode; - } - }; - Emitter.prototype.emitPrologue = function (reqInherits) { - if(!this.extendsPrologueEmitted) { - if(reqInherits) { - this.extendsPrologueEmitted = true; - this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); - this.writeLineToOutput(" function __() { this.constructor = d; }"); - this.writeLineToOutput(" __.prototype = b.prototype;"); - this.writeLineToOutput(" d.prototype = new __();"); - this.writeLineToOutput("};"); - } - } - if(!this.globalThisCapturePrologueEmitted) { - if(this.checker.mustCaptureGlobalThis) { - this.globalThisCapturePrologueEmitted = true; - this.writeLineToOutput(this.captureThisStmtString); - } - } - }; - Emitter.prototype.emitSuperReference = function () { - this.writeToOutput("_super.prototype"); - }; - Emitter.prototype.emitSuperCall = function (callEx) { - if(callEx.target.nodeType == TypeScript.NodeType.Dot) { - var dotNode = callEx.target; - if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { - this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); - this.writeToOutput(".call("); - this.emitThis(); - if(callEx.arguments && callEx.arguments.members.length > 0) { - this.writeToOutput(", "); - this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - return true; - } - } - return false; - }; - Emitter.prototype.emitThis = function () { - if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { - this.writeToOutput("_this"); - } else { - this.writeToOutput("this"); - } - }; - Emitter.shouldCaptureThis = function shouldCaptureThis(func) { - return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); - }; - Emitter.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitOptions.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return Emitter; - })(); - TypeScript.Emitter = Emitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ErrorReporter = (function () { - function ErrorReporter(outfile) { - this.outfile = outfile; - this.parser = null; - this.checker = null; - this.lineCol = { - line: 0, - col: 0 - }; - this.emitAsComments = true; - this.hasErrors = false; - this.pushToErrorSink = false; - this.errorSink = []; - } - ErrorReporter.prototype.getCapturedErrors = function () { - return this.errorSink; - }; - ErrorReporter.prototype.freeCapturedErrors = function () { - this.errorSink = []; - }; - ErrorReporter.prototype.captureError = function (emsg) { - this.errorSink[this.errorSink.length] = emsg; - }; - ErrorReporter.prototype.setErrOut = function (outerr) { - this.outfile = outerr; - this.emitAsComments = false; - }; - ErrorReporter.prototype.emitPrefix = function () { - if(this.emitAsComments) { - this.outfile.Write("// "); - } - this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); - }; - ErrorReporter.prototype.writePrefix = function (ast) { - if(ast) { - this.setError(ast); - } else { - this.lineCol.line = 0; - this.lineCol.col = 0; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.writePrefixFromSym = function (symbol) { - if(symbol && this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); - } else { - this.lineCol.line = -1; - this.lineCol.col = -1; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.setError = function (ast) { - if(ast) { - ast.flags |= TypeScript.ASTFlags.Error; - if(this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); - } - } - }; - ErrorReporter.prototype.reportError = function (ast, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(ast && this.parser.errorRecovery && this.parser.errorCallback) { - var len = (ast.limChar - ast.minChar); - this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefix(ast); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(this.parser.errorRecovery && this.parser.errorCallback) { - this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefixFromSym(symbol); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.emitterError = function (ast, message) { - this.reportError(ast, message); - throw Error("EmitError"); - }; - ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { - this.reportError(ast, "Duplicate identifier '" + name + "'"); - }; - ErrorReporter.prototype.showRef = function (ast, text, symbol) { - var defLineCol = { - line: -1, - col: -1 - }; - this.parser.getSourceLineCol(defLineCol, symbol.location); - this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); - }; - ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); - }; - ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not refer to a value"); - }; - ErrorReporter.prototype.styleError = function (ast, msg) { - var bkThrow = this.pushToErrorSink; - this.pushToErrorSink = false; - this.reportError(ast, "STYLE: " + msg); - this.pushToErrorSink = bkThrow; - }; - ErrorReporter.prototype.simpleError = function (ast, msg) { - this.reportError(ast, msg); - }; - ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { - this.reportErrorFromSym(sym, msg); - }; - ErrorReporter.prototype.invalidSuperReference = function (ast) { - this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); - }; - ErrorReporter.prototype.valueCannotBeModified = function (ast) { - this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); - }; - ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { - var targetType = ast.target.type; - var typeName = targetType.getScopedTypeName(scope); - if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { - this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); - } else { - var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; - this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); - } - }; - ErrorReporter.prototype.indexLHS = function (ast, scope) { - var targetType = ast.operand1.type.getScopedTypeName(scope); - var indexType = ast.operand2.type.getScopedTypeName(scope); - this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); - }; - ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { - if(!t1) { - t1 = this.checker.anyType; - } - if(!t2) { - t2 = this.checker.anyType; - } - var reason = comparisonInfo ? comparisonInfo.message : ""; - if(op) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } else { - this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } - }; - ErrorReporter.prototype.expectedClassOrInterface = function (ast) { - this.simpleError(ast, "Expected var, class, interface, or module"); - }; - ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); - }; - return ErrorReporter; - })(); - TypeScript.ErrorReporter = ErrorReporter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeContext) { - TypeContext._map = []; - TypeContext.NoTypes = 0; - TypeContext.ArraySuffix = 1; - TypeContext.Primitive = 2; - TypeContext.Named = 4; - TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; - TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; - })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); - var TypeContext = TypeScript.TypeContext; - var QuickParseResult = (function () { - function QuickParseResult(Script, endLexState) { - this.Script = Script; - this.endLexState = endLexState; - } - return QuickParseResult; - })(); - TypeScript.QuickParseResult = QuickParseResult; - var Parser = (function () { - function Parser() { - this.varLists = []; - this.scopeLists = []; - this.staticsLists = []; - this.scanner = new TypeScript.Scanner(); - this.currentToken = null; - this.needTerminator = false; - this.inFunction = false; - this.inInterfaceDecl = false; - this.currentClassDecl = null; - this.inFncDecl = false; - this.anonId = new TypeScript.Identifier("_anonymous"); - this.style_requireSemi = false; - this.style_funcInLoop = true; - this.incremental = false; - this.errorRecovery = false; - this.outfile = undefined; - this.errorCallback = null; - this.ambientModule = false; - this.ambientClass = false; - this.topLevel = true; - this.allowImportDeclaration = true; - this.currentUnitIndex = (-1); - this.prevIDTok = null; - this.statementInfoStack = new Array(); - this.hasTopLevelImportOrExport = false; - this.strictMode = false; - this.nestingLevel = 0; - this.prevExpr = null; - this.currentClassDefinition = null; - this.parsingClassConstructorDefinition = false; - this.parsingDeclareFile = false; - this.amdDependencies = []; - this.inferPropertiesFromThisAssignment = false; - this.requiresExtendsBlock = false; - this.fname = ""; - } - Parser.prototype.resetStmtStack = function () { - this.statementInfoStack = new Array(); - }; - Parser.prototype.inLoop = function () { - for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { - if(this.statementInfoStack[j].stmt.isLoop()) { - return true; - } - } - return false; - }; - Parser.prototype.pushStmt = function (stmt, labels) { - var info = { - stmt: stmt, - labels: labels - }; - this.statementInfoStack.push(info); - }; - Parser.prototype.popStmt = function () { - return this.statementInfoStack.pop(); - }; - Parser.prototype.resolveJumpTarget = function (jump) { - var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); - var len = this.statementInfoStack.length; - for(var i = len - 1; i >= 0; i--) { - var info = this.statementInfoStack[i]; - if(jump.target) { - if(info.labels && (info.labels.members.length > 0)) { - for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { - var label = info.labels.members[j]; - if(label.id.text == resolvedTarget) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - } else { - if(info.stmt.isLoop()) { - jump.setResolvedTarget(this, info.stmt); - return; - } else if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - if(jump.target) { - this.reportParseError("could not find enclosing statement with label " + jump.target); - } else { - if(jump.nodeType == TypeScript.NodeType.Break) { - this.reportParseError("break statement requires enclosing loop or switch"); - } else { - this.reportParseError("continue statement requires enclosing loop"); - } - } - }; - Parser.prototype.setErrorRecovery = function (outfile) { - this.outfile = outfile; - this.errorRecovery = true; - }; - Parser.prototype.getSourceLineCol = function (lineCol, minChar) { - TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); - }; - Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { - var id = new TypeScript.Identifier(text, hasEscapeSequence); - id.minChar = minChar; - return id; - }; - Parser.prototype.reportParseStyleError = function (message) { - this.reportParseError("STYLE: " + message); - }; - Parser.prototype.reportParseError = function (message, startPos, pos) { - if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } - if (typeof pos === "undefined") { pos = this.scanner.pos; } - var len = Math.max(1, pos - startPos); - if(this.errorCallback) { - this.errorCallback(startPos, len, message, this.currentUnitIndex); - } else if(this.errorRecovery) { - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, startPos); - if(this.outfile) { - this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); - } - } else { - throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); - } - }; - Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(tokenId, errorRecoverySet, errorText); - }; - Parser.prototype.skip = function (errorRecoverySet) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; - var ersTok = TypeScript.ErrorRecoverySet.None; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - var pendingRightCurlies = 0; - while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { - if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - pendingRightCurlies++; - } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - pendingRightCurlies--; - } - this.currentToken = this.scanner.scan(); - ersTok = TypeScript.ErrorRecoverySet.None; - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - } - }; - Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - if(this.currentToken.tokenId != tokenId) { - errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; - this.reportParseError(errorText); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - } - } else { - this.currentToken = this.scanner.scan(); - } - }; - Parser.prototype.pushDeclLists = function () { - this.staticsLists.push(new TypeScript.ASTList()); - this.varLists.push(new TypeScript.ASTList()); - this.scopeLists.push(new TypeScript.ASTList()); - }; - Parser.prototype.popDeclLists = function () { - this.staticsLists.pop(); - this.varLists.pop(); - this.scopeLists.pop(); - }; - Parser.prototype.topVarList = function () { - return this.varLists[this.varLists.length - 1]; - }; - Parser.prototype.topScopeList = function () { - return this.scopeLists[this.scopeLists.length - 1]; - }; - Parser.prototype.topStaticsList = function () { - return this.staticsLists[this.staticsLists.length - 1]; - }; - Parser.prototype.parseComment = function (comment) { - if(comment) { - var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); - c.minChar = comment.startPos; - c.limChar = comment.startPos + comment.value.length; - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, c.minChar); - c.minLine = lineCol.line; - this.getSourceLineCol(lineCol, c.limChar); - c.limLine = lineCol.line; - if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { - var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); - if(dependencyPath) { - this.amdDependencies.push(dependencyPath); - } - if(TypeScript.getImplicitImport(comment.value)) { - this.hasTopLevelImportOrExport = true; - } - } - return c; - } else { - return null; - } - }; - Parser.prototype.parseCommentsInner = function (comments) { - if(comments) { - var commentASTs = new Array(); - for(var i = 0; i < comments.length; i++) { - commentASTs.push(this.parseComment(comments[i])); - } - return commentASTs; - } else { - return null; - } - }; - Parser.prototype.parseComments = function () { - var comments = this.scanner.getComments(); - return this.parseCommentsInner(comments); - }; - Parser.prototype.parseCommentsForLine = function (line) { - var comments = this.scanner.getCommentsForLine(line); - return this.parseCommentsInner(comments); - }; - Parser.prototype.combineComments = function (comment1, comment2) { - if(comment1 == null) { - return comment2; - } else if(comment2 == null) { - return comment1; - } else { - return comment1.concat(comment2); - } - }; - Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Enum declaration requires identifier"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.startPos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - this.pushDeclLists(); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); - mapDecl.varFlags |= TypeScript.VarFlags.Exported; - mapDecl.varFlags |= TypeScript.VarFlags.Private; - mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); - mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); - members.append(mapDecl); - var lastValue = null; - var memberNames = []; - for(; ; ) { - var minChar = this.scanner.startPos; - var limChar; - var memberName = null; - var memberValue = null; - var preComments = null; - var postComments = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - memberNames.push(memberName); - } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } else { - this.reportParseError("Expected identifer of enum member"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - } - } - limChar = this.scanner.pos; - preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - postComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - this.currentToken = this.scanner.scan(); - memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - lastValue = memberValue; - limChar = memberValue.limChar; - } else { - if(lastValue == null) { - memberValue = new TypeScript.NumberLiteral(0, "0"); - lastValue = memberValue; - } else { - var nextValue = lastValue.value + 1; - memberValue = new TypeScript.NumberLiteral(nextValue, nextValue.toString()); - lastValue = memberValue; - } - var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); - members.append(map); - } - var member = new TypeScript.VarDecl(memberName, this.nestingLevel); - member.minChar = minChar; - member.limChar = limChar; - member.init = memberValue; - member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); - member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); - if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { - member.varFlags |= TypeScript.VarFlags.Constant; - } else if(memberValue.nodeType === TypeScript.NodeType.Lsh) { - var binop = memberValue; - if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { - member.varFlags |= TypeScript.VarFlags.Constant; - } - } else if(memberValue.nodeType === TypeScript.NodeType.Name) { - var nameNode = memberValue; - for(var i = 0; i < memberNames.length; i++) { - var memberName = memberNames[i]; - if(memberName.text === nameNode.text) { - member.varFlags |= TypeScript.VarFlags.Constant; - break; - } - } - } - member.preComments = preComments; - members.append(member); - member.postComments = postComments; - member.varFlags |= TypeScript.VarFlags.Exported; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { - continue; - } - } - break; - } - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - members.limChar = this.scanner.lastTokenLimChar(); - var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), endingToken); - modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; - this.popDeclLists(); - modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return modDecl; - }; - Parser.prototype.parseDottedName = function (enclosedList) { - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.preComments = this.parseComments(); - enclosedList[enclosedList.length] = id; - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - this.parseDottedName(enclosedList); - } - } else { - this.reportParseError("need identifier after '.'"); - } - }; - Parser.prototype.isValidImportPath = function (importPath) { - importPath = TypeScript.stripQuotes(importPath); - if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { - return false; - } - return true; - }; - Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { - var name = null; - var alias = null; - var importDecl = null; - var minChar = this.scanner.startPos; - var isDynamicImport = false; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - } else { - this.reportParseError("Expected identifer after 'import'"); - name = new TypeScript.MissingIdentifier(); - } - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - var aliasPreComments = this.parseComments(); - var limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Module) { - limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } else if(!this.allowImportDeclaration) { - this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); - } - var aliasText = this.currentToken.getText(); - alias = TypeScript.Identifier.fromToken(this.currentToken); - alias.minChar = this.scanner.startPos; - alias.limChar = this.scanner.pos; - if(!this.isValidImportPath((alias).text)) { - this.reportParseError("Invalid import path"); - } - isDynamicImport = true; - this.currentToken = this.scanner.scan(); - alias.preComments = aliasPreComments; - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - alias.preComments = aliasPreComments; - } - } - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(alias) { - alias.postComments = this.parseComments(); - } - } - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - limChar = this.scanner.pos; - } - } else { - this.reportParseError("Expected module name"); - alias = new TypeScript.MissingIdentifier(); - alias.minChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - alias.limChar = this.scanner.startPos; - } else { - alias.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - alias.flags |= TypeScript.ASTFlags.Error; - limChar = alias.limChar; - } - importDecl = new TypeScript.ImportDeclaration(name, alias); - importDecl.isDynamicImport = isDynamicImport; - importDecl.minChar = minChar; - importDecl.limChar = limChar; - return importDecl; - }; - Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var svAmbient = this.ambientModule; - var svTopLevel = this.topLevel; - this.topLevel = false; - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.ambientModule = true; - } - this.currentToken = this.scanner.scan(); - var name = null; - var enclosedList = null; - this.pushDeclLists(); - var minChar = this.scanner.startPos; - var isDynamicMod = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var nameText = this.currentToken.getText(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - isDynamicMod = true; - if(!this.ambientModule) { - this.reportParseError("Only ambient dynamic modules may have string literal names"); - } - if(!svTopLevel) { - this.reportParseError("Dynamic modules may not be nested within other modules"); - } - } - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - this.reportParseError("Module name missing"); - name = new TypeScript.Identifier(""); - name.minChar = minChar; - name.limChar = minChar; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - enclosedList = new Array(); - this.parseDottedName(enclosedList); - } - if(name == null) { - name = new TypeScript.MissingIdentifier(); - } - var moduleBody = new TypeScript.ASTList(); - var bodyMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(svTopLevel && isDynamicMod) { - this.allowImportDeclaration = true; - } else { - this.allowImportDeclaration = false; - } - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); - moduleBody.minChar = bodyMinChar; - moduleBody.limChar = this.scanner.pos; - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var limChar = this.scanner.lastTokenLimChar(); - var moduleDecl; - this.allowImportDeclaration = svTopLevel; - if(enclosedList && (enclosedList.length > 0)) { - var len = enclosedList.length; - var innerName = enclosedList[len - 1]; - var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), endingToken); - innerDecl.preComments = preComments; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - innerDecl.minChar = minChar; - innerDecl.limChar = limChar; - this.popDeclLists(); - var outerModBod; - for(var i = len - 2; i >= 0; i--) { - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - innerName = enclosedList[i]; - innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), endingToken); - outerModBod.minChar = innerDecl.minChar = minChar; - outerModBod.limChar = innerDecl.limChar = limChar; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - outerModBod.minChar = minChar; - outerModBod.limChar = limChar; - moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), endingToken); - } else { - moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), endingToken); - moduleDecl.preComments = preComments; - this.popDeclLists(); - } - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - if(isDynamicMod) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; - } - this.ambientModule = svAmbient; - this.topLevel = svTopLevel; - moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - moduleDecl.limChar = moduleBody.limChar; - return moduleDecl; - }; - Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { - var result = new TypeScript.TypeReference(term, 0); - result.minChar = minChar; - while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { - this.currentToken = this.scanner.scan(); - result.arrayCount++; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); - } - result.limChar = this.scanner.lastTokenLimChar(); - return result; - }; - Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var op2 = TypeScript.Identifier.fromToken(this.currentToken); - op2.minChar = this.scanner.startPos; - op2.limChar = this.scanner.pos; - var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); - dotNode.minChar = term.minChar; - dotNode.limChar = op2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); - } else { - this.reportParseError("need identifier after '.'"); - if(this.errorRecovery) { - term.flags |= TypeScript.ASTFlags.DotLHS; - term.limChar = this.scanner.lastTokenLimChar(); - return term; - } else { - var eop2 = new TypeScript.MissingIdentifier(); - eop2.minChar = this.scanner.pos; - eop2.limChar = this.scanner.pos; - var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); - edotNode.flags |= TypeScript.ASTFlags.Error; - edotNode.minChar = term.minChar; - edotNode.limChar = eop2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); - } - } - } else { - if(tail) { - return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); - } else { - return term; - } - } - }; - Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { - var minChar = this.scanner.startPos; - var isConstructorMember = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Void: - if(!allowVoid) { - this.reportParseError("void not a valid type in this context"); - } - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.String: { - var text = TypeScript.tokenTable[this.currentToken.tokenId].text; - var predefinedIdentifier = new TypeScript.Identifier(text); - predefinedIdentifier.minChar = minChar; - predefinedIdentifier.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); - } - case TypeScript.TokenID.Identifier: - var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); - ident.limChar = this.scanner.pos; - return this.parseNamedType(errorRecoverySet, minChar, ident, true); - case TypeScript.TokenID.OpenBrace: - return this.parseObjectType(minChar, errorRecoverySet); - case TypeScript.TokenID.New: - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { - this.reportParseError("Expected '('"); - } else { - isConstructorMember = true; - } - case TypeScript.TokenID.OpenParen: { - var formals = new TypeScript.ASTList(); - var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); - this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); - var returnType = this.parseTypeReference(errorRecoverySet, true); - var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); - funcDecl.returnTypeAnnotation = returnType; - funcDecl.variableArgList = variableArgList; - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - if(isConstructorMember) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = null; - } - funcDecl.minChar = minChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); - } - default: - this.reportParseError("Expected type name"); - var etr = new TypeScript.TypeReference(null, 0); - etr.flags |= TypeScript.ASTFlags.Error; - etr.minChar = this.scanner.pos; - etr.limChar = this.scanner.pos; - return etr; - } - }; - Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { - this.currentToken = this.scanner.scan(); - var members = new TypeScript.ASTList(); - members.minChar = minChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); - interfaceDecl.minChar = minChar; - interfaceDecl.limChar = members.limChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); - }; - Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - var savedInFunction = this.inFunction; - this.inFunction = true; - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); - bod.minChar = bodMinChar; - bod.limChar = this.scanner.pos; - this.inFunction = savedInFunction; - if(bod.limChar > bod.minChar) { - var ec = new TypeScript.EndCode(); - ec.minChar = bod.limChar; - ec.limChar = ec.minChar; - bod.append(ec); - } - }; - Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { - this.pushDeclLists(); - var svStmtStack = this.statementInfoStack; - this.resetStmtStack(); - var bod = null; - var wasShorthand = false; - var isAnonLambda = false; - var limChar; - if(requiresSignature) { - limChar = this.scanner.pos; - if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { - this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - } else { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); - } - } else { - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { - if(isMethod) { - this.reportParseError("'=>' may not be used for class methods"); - } - wasShorthand = true; - this.currentToken = this.scanner.scan(); - } - if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.returnExpression = retExpr; - retStmt.minChar = retExpr.minChar; - retStmt.limChar = retExpr.limChar; - bod.minChar = bodMinChar; - bod.limChar = retExpr.limChar; - bod.append(retStmt); - } else if(this.currentToken.tokenId != TypeScript.TokenID.EndOfFile) { - isAnonLambda = wasShorthand; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - } - limChar = this.scanner.pos; - } - var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); - this.popDeclLists(); - var scopeList = this.topScopeList(); - scopeList.append(funcDecl); - var staticFuncDecl = false; - if(!requiresSignature) { - if(!wasShorthand || isAnonLambda) { - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = this.scanner.startPos; - funcDecl.endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(isAnonLambda) { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - } - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = bod.members[0].minChar; - funcDecl.endingToken.limChar = bod.members[0].limChar; - } - } - funcDecl.minChar = minChar; - funcDecl.limChar = limChar; - if(requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - this.statementInfoStack = svStmtStack; - return funcDecl; - }; - Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { - var _this = this; - var translateBinExOperand = function (operand) { - if(operand.nodeType == TypeScript.NodeType.Comma) { - return _this.transformAnonymousArgsIntoFormals(formals, operand); - } else if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { - var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; - opArg.isParenthesized = false; - var arg = new TypeScript.ArgDecl(opArg); - arg.preComments = opArg.preComments; - arg.postComments = opArg.postComments; - arg.minChar = operand.minChar; - arg.limChar = operand.limChar; - if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - arg.isOptional = true; - } - if(operand.nodeType == TypeScript.NodeType.Asg) { - arg.init = (operand).operand2; - } - formals.append(arg); - return arg.isOptional || arg.init; - } else { - _this.reportParseError("Invalid lambda argument"); - } - return false; - }; - if(argList) { - if(argList.nodeType == TypeScript.NodeType.Comma) { - var commaList = argList; - if(commaList.operand1.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); - } - if(commaList.operand2.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); - } - var isOptional = translateBinExOperand(commaList.operand1); - isOptional = translateBinExOperand(commaList.operand2) || isOptional; - return isOptional; - } else { - return translateBinExOperand(argList); - } - } - }; - Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { - formals.minChar = this.scanner.startPos; - if(isIndexer) { - this.currentToken = this.scanner.scan(); - } else if(!isLambda) { - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); - } - var sawEllipsis = false; - var firstArg = true; - var hasOptional = false; - var haveFirstArgID = false; - if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { - hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); - formals.minChar = preProcessedLambdaArgs.minChar; - haveFirstArgID = true; - } - while(true) { - var munchedArg = false; - var argFlags = TypeScript.VarFlags.None; - var argMinChar = this.scanner.startPos; - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { - this.reportParseError("Static properties can not be declared as parameter properties"); - this.currentToken = this.scanner.scan(); - } - if(argFlags != TypeScript.VarFlags.None) { - if(!isClassConstr) { - this.reportParseError("only constructor parameters can be properties"); - } - this.currentToken = this.scanner.scan(); - if(TypeScript.isModifier(this.currentToken)) { - this.reportParseError("Multiple modifiers may not be applied to parameters"); - this.currentToken = this.scanner.scan(); - } - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - this.currentToken = this.scanner.scan(); - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - sawEllipsis = true; - this.currentToken = this.scanner.scan(); - if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - sawEllipsis = false; - } - } - var argId = null; - if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - argId = TypeScript.Identifier.fromToken(this.currentToken); - argId.minChar = this.scanner.startPos; - argId.limChar = this.scanner.pos; - } - if(haveFirstArgID || argId) { - munchedArg = true; - var type = null; - var arg = null; - if(haveFirstArgID && formals.members.length) { - arg = formals.members[formals.members.length - 1]; - if(arg.isOptional) { - hasOptional = true; - } - } else { - arg = new TypeScript.ArgDecl(argId); - if(isGetter) { - this.reportParseError("Property getters may not take any arguments"); - } - if(isSetter && !firstArg) { - this.reportParseError("Property setters may only take one argument"); - } - arg.minChar = argMinChar; - arg.preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - arg.isOptional = true; - hasOptional = true; - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - type = this.parseTypeReference(errorRecoverySet, false); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(isSig) { - this.reportParseError("Arguments in signatures may not have default values"); - } - hasOptional = true; - this.currentToken = this.scanner.scan(); - arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); - } - if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { - this.reportParseError("Optional parameters may only be followed by other optional parameters"); - } - if(sawEllipsis && arg.isOptionalArg()) { - this.reportParseError("Varargs may not be optional or have default parameters"); - } - if(sawEllipsis && !type) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - } - arg.postComments = this.parseComments(); - arg.typeExpr = type; - arg.limChar = this.scanner.lastTokenLimChar(); - arg.varFlags |= argFlags; - if(!haveFirstArgID) { - formals.append(arg); - } else { - haveFirstArgID = false; - } - } - firstArg = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - if((munchedArg) && (!sawEllipsis)) { - this.currentToken = this.scanner.scan(); - continue; - } else { - this.reportParseError("Unexpected ',' in argument list"); - if(this.errorRecovery) { - this.currentToken = this.scanner.scan(); - continue; - } - } - } else { - break; - } - } - if(isIndexer) { - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } else if(expectClosingRParen) { - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } - formals.limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); - return sawEllipsis; - }; - Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var prevInConstr = this.parsingClassConstructorDefinition; - this.parsingClassConstructorDefinition = false; - var name = null; - var fnMin = this.scanner.startPos; - var minChar = this.scanner.pos; - var prevNestingLevel = this.nestingLevel; - var preComments = this.parseComments(); - var isLambda = !!lambdaArgContext; - this.nestingLevel = 0; - if((!this.style_funcInLoop) && this.inLoop()) { - this.reportParseStyleError("function declaration in loop"); - } - if(!isMethod && !isStatic && !indexer && !lambdaArgContext && !methodName) { - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - if(isDecl) { - this.reportParseError("Function declaration must include identifier"); - this.nestingLevel = prevNestingLevel; - return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); - } - } else { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } else { - if(methodName) { - name = methodName; - } - } - var args = new TypeScript.ASTList(); - var variableArgList = false; - var isOverload = false; - var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); - var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); - } - var returnType = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { - this.reportParseError("Property setters may not declare a return type"); - } - returnType = this.parseTypeReference(errorRecoverySet, true); - } - if(indexer && args.members.length == 0) { - this.reportParseError("Index signatures require a parameter type to be specified"); - } - if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { - this.reportParseError("Expected '=>'"); - } - if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && !this.ambientModule && !this.ambientClass && !this.inInterfaceDecl && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - isOverload = true; - isDecl = false; - requiresSignature = true; - } - var svInFncDecl = this.inFncDecl; - this.inFncDecl = true; - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); - this.inFncDecl = svInFncDecl; - funcDecl.variableArgList = variableArgList; - funcDecl.isOverload = isOverload; - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(indexer) { - funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; - } - funcDecl.returnTypeAnnotation = returnType; - if(isMethod) { - funcDecl.fncFlags |= TypeScript.FncFlags.Method; - funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; - } - funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - this.nestingLevel = prevNestingLevel; - this.parsingClassConstructorDefinition = prevInConstr; - funcDecl.preComments = preComments; - return funcDecl; - }; - Parser.prototype.convertToTypeReference = function (ast) { - var result; - switch(ast.nodeType) { - case TypeScript.NodeType.TypeRef: - return ast; - case TypeScript.NodeType.Name: - result = new TypeScript.TypeReference(ast, 0); - result.minChar = ast.minChar; - result.limChar = ast.limChar; - return result; - case TypeScript.NodeType.Index: { - var expr = ast; - result = this.convertToTypeReference(expr.operand1); - if(result) { - result.arrayCount++; - result.minChar = expr.minChar; - result.limChar = expr.limChar; - return result; - } else { - var etr = new TypeScript.AST(TypeScript.NodeType.Error); - return etr; - } - } - } - return null; - }; - Parser.prototype.parseArgList = function (errorRecoverySet) { - var args = new TypeScript.ASTList(); - args.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { - while(true) { - if(args.members.length > 0xffff) { - this.reportParseError("max number of args exceeded"); - break; - } - var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - args.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - } - args.limChar = this.scanner.pos; - return args; - }; - Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { - var keyword = true; - var currentList = extendsList; - for(; ; ) { - if(keyword) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - currentList = implementsList; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - this.currentToken = this.scanner.scan(); - keyword = false; - } - var baseName = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var minChar = this.scanner.startPos; - baseName = TypeScript.Identifier.fromToken(this.currentToken); - baseName.minChar = minChar; - baseName.limChar = this.scanner.pos; - baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); - } else { - this.reportParseError("Expected base name"); - if(this.errorRecovery) { - baseName = new TypeScript.MissingIdentifier(); - baseName.minChar = this.scanner.pos; - baseName.limChar = this.scanner.pos; - baseName.flags |= TypeScript.ASTFlags.Error; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - if(isClass) { - this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); - } else { - this.reportParseError("Interfaces may not be extended with a call expression"); - } - } else { - currentList.append(baseName); - } - if(isClass && currentList == extendsList && extendsList.members.length > 1) { - this.reportParseError("A class may only extend one other class"); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - continue; - } else if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - currentList = extendsList; - keyword = true; - continue; - } - break; - } - }; - Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - this.reportParseError("const modifier is implicit for class"); - } - if(this.parsingDeclareFile || this.ambientModule) { - modifiers |= TypeScript.Modifiers.Ambient; - modifiers |= TypeScript.Modifiers.Exported; - } - var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; - var svAmbientClass = this.ambientClass; - this.ambientClass = classIsMarkedAsAmbient; - this.currentToken = this.scanner.scan(); - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("class missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - var requiresSignature = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); - } - var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); - this.currentClassDefinition = classDecl; - this.parseClassElements(classDecl, errorRecoverySet, modifiers); - if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - classDecl.varFlags |= TypeScript.VarFlags.Exported; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - classDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - classDecl.varFlags |= TypeScript.VarFlags.Class; - this.ambientClass = svAmbientClass; - classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return classDecl; - }; - Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { - var modifiers = parentModifiers; - var resetModifiers = false; - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); - this.nestingLevel++; - var currentMemberMinChar = this.scanner.startPos; - var wasGetOrSetId = false; - while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - var scanNext = true; - var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Duplicate 'get' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Getter already marked as a setter"); - } - modifiers |= TypeScript.Modifiers.Getter; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Duplicate 'set' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Setter already marked as a getter"); - } - modifiers |= TypeScript.Modifiers.Setter; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Private; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Public; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Static) { - if(modifiers & TypeScript.Modifiers.Static) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Static; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { - if(modifiers != parentModifiers) { - this.reportParseError("Constructors may not have modifiers"); - } - this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - resetModifiers = true; - } else if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { - var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); - var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - if(wasGetOrSetId) { - modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); - wasGetOrSetId = false; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - } else { - if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Property accessors must be functions"); - } - var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); - if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - scanNext = false; - } - } else if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - scanNext = false; - varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Expected ';'"); - scanNext = false; - } - } - resetModifiers = true; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Super) { - this.reportParseError("Base class initializers must be the first statement in a class definition"); - } else if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { - wasGetOrSetId = true; - scanNext = false; - } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); - resetModifiers = true; - } - if(scanNext) { - this.currentToken = this.scanner.scan(); - } - if(resetModifiers) { - modifiers = parentModifiers; - currentMemberMinChar = this.scanner.startPos; - resetModifiers = false; - } - } - var membersLimChar = this.scanner.pos; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - classDecl.endingToken = new TypeScript.ASTSpan(); - classDecl.endingToken.minChar = this.scanner.startPos; - classDecl.endingToken.limChar = this.scanner.pos; - if(!this.currentClassDefinition.members.members.length) { - this.currentClassDefinition.preComments = this.parseComments(); - } - this.currentToken = this.scanner.scan(); - } - this.nestingLevel--; - this.currentClassDefinition.members.minChar = membersMinChar; - this.currentClassDefinition.members.limChar = membersLimChar; - this.currentClassDefinition.limChar = membersLimChar; - this.currentClassDefinition = null; - }; - Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { - this.parsingClassConstructorDefinition = true; - var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - var args = new TypeScript.ASTList(); - var variableArgList = false; - var preComments = this.parseComments(); - var constructorSpan = new TypeScript.ASTSpan(); - constructorSpan.minChar = this.scanner.startPos; - constructorSpan.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); - if(args.members.length > 0) { - var lastArg = args.members[args.members.length - 1]; - } - } - var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; - if(requiresSignature) { - for(var i = 0; i < args.members.length; i++) { - var arg = args.members[i]; - if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { - this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); - } - } - } - if(!requiresSignature) { - this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; - } - var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); - constructorFuncDecl.constructorSpan = constructorSpan; - constructorFuncDecl.preComments = preComments; - if(requiresSignature && !isAmbient) { - constructorFuncDecl.isOverload = true; - } - constructorFuncDecl.variableArgList = variableArgList; - this.currentClassDecl = null; - constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); - constructorFuncDecl.classDecl = this.currentClassDefinition; - if(isAmbient) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(requiresSignature) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; - } - if(this.currentClassDefinition.constructorDecl) { - if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { - this.reportParseError("Duplicate constructor definition"); - } - } - if(isAmbient || !constructorFuncDecl.isSignature()) { - this.currentClassDefinition.constructorDecl = constructorFuncDecl; - } - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; - this.parsingClassConstructorDefinition = false; - return constructorFuncDecl; - }; - Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.minChar = minChar; - var isStatic = false; - varDecl.preComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(!(modifiers & TypeScript.Modifiers.Static)) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - varDecl.limChar = this.scanner.pos; - } - if(modifiers & TypeScript.Modifiers.Static) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - isStatic = true; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } else { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - if(isDeclaredInConstructor) { - varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; - } - if(!isDeclaredInConstructor && !isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; - } - this.currentClassDefinition.knownMemberNames[text.actualText] = true; - if(!isDeclaredInConstructor) { - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; - } - varDecl.postComments = this.parseComments(); - return varDecl; - }; - Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); - var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; - if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { - this.reportParseError("Property accessors may not be declared in ambient classes"); - } - var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } - var funcDecl = ast; - funcDecl.minChar = minChar; - if(funcDecl.bod !== null) { - funcDecl.limChar = funcDecl.bod.limChar; - } - if(modifiers & TypeScript.Modifiers.Private) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); - } - } - funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; - return funcDecl; - }; - Parser.prototype.parseTypeMember = function (errorRecoverySet) { - var minChar = this.scanner.startPos; - var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); - if(propertyDecl) { - propertyDecl.minChar = minChar; - if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - } - } - return propertyDecl; - }; - Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; - while(true) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.CloseBrace: - case TypeScript.TokenID.EndOfFile: - members.limChar = this.scanner.pos; - return; - } - var element = this.parseTypeMember(errorRecoverySet); - if(element) { - members.append(element); - } - } - }; - Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - this.currentToken = this.scanner.scan(); - var minChar = this.scanner.pos; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("interface missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - this.reportParseError("Expected 'extends'"); - } - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - extendsList.minChar = this.scanner.startPos; - this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Private; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Public; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; - } - interfaceDecl.limChar = members.limChar; - interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return interfaceDecl; - }; - Parser.prototype.makeVarDecl = function (id, nest) { - var varDecl = new TypeScript.VarDecl(id, nest); - var currentVarList = this.topVarList(); - if(currentVarList) { - currentVarList.append(varDecl); - } - return varDecl; - }; - Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic, unnamedAmbientFunctionOk) { - var text = null; - var minChar = this.scanner.startPos; - var nameLimChar = minChar; - var isNew = false; - var isIndexer = false; - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - requireSignature = true; - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { - if(!requireSignature && !isStatic) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - text = new TypeScript.MissingIdentifier(); - } - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.New) { - if(requireSignature) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - isNew = true; - } - } - if(!isNew) { - if(!requireSignature) { - this.currentToken = this.scanner.scan(); - } - text = new TypeScript.Identifier("new"); - text.minChar = this.scanner.pos - 3; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - } - } else if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { - isIndexer = true; - text = new TypeScript.Identifier("__item"); - } else if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - var eminChar = this.scanner.startPos; - var curpos = this.scanner.pos; - this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); - if(this.scanner.pos == curpos) { - this.currentToken = this.scanner.scan(); - } - var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - epd.flags |= TypeScript.ASTFlags.Error; - epd.minChar = eminChar; - epd.limChar = this.scanner.lastTokenLimChar(); - return epd; - } - } else { - if(wasAccessorID) { - text = TypeScript.Identifier.fromToken(this.prevIDTok); - text.minChar = this.scanner.lastTokenLimChar() - 3; - text.limChar = this.scanner.lastTokenLimChar(); - nameLimChar = text.limChar; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { - this.currentToken = this.scanner.scan(); - } - this.prevIDTok = null; - } else { - text = TypeScript.Identifier.fromToken(this.currentToken); - text.minChar = this.scanner.startPos; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - if(this.inInterfaceDecl && text) { - text.flags |= TypeScript.ASTFlags.OptionalName; - } else { - this.reportParseError("Optional properties may only be declared on interface or object types"); - } - this.currentToken = this.scanner.scan(); - } - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { - var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; - if(isIndexer) { - ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; - } - if(!text && unnamedAmbientFunctionOk && !isIndexer) { - text = new TypeScript.MissingIdentifier(); - } - var ast = this.parseFncDecl(ers, true, requireSignature, this.currentClassDefinition || this.inInterfaceDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); - var funcDecl; - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } else { - funcDecl = ast; - } - if(funcDecl.name) { - funcDecl.name.minChar = minChar; - funcDecl.name.limChar = nameLimChar; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(modifiers & TypeScript.Modifiers.Ambient) { - this.reportParseError("Property accessors may not be declared in ambient types"); - } - } - if(text == null || (text.isMissing() && unnamedAmbientFunctionOk && !isIndexer)) { - if(isNew) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = this.currentClassDecl; - } else { - funcDecl.hint = "_call"; - funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; - } - } - return funcDecl; - } else { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.preComments = this.parseComments(); - varDecl.minChar = minChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(requireSignature) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.text; - funcDecl.boundToProperty = varDecl; - } else if(isAccessor) { - this.reportParseError("Accessors may only be functions"); - } - } else { - varDecl.limChar = this.scanner.pos; - } - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - return varDecl; - } - }; - Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { - var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); - var minChar = this.scanner.startPos; - var varDecl = null; - var declList = null; - var multivar = false; - this.currentToken = this.scanner.scan(); - var varDeclPreComments = this.parseComments(); - while(true) { - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - this.reportParseError("Expected identifier in variable declaration"); - if(this.errorRecovery) { - varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - varDecl.minChar = minChar; - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); - if(this.strictMode && (varDeclName.text == "eval")) { - this.reportParseError("'eval' may not name a variable in strict mode"); - } - varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); - varDecl.id.minChar = this.scanner.startPos; - varDecl.id.limChar = this.scanner.pos; - varDecl.preComments = varDeclPreComments; - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - varDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - varDecl.varFlags |= TypeScript.VarFlags.Exported; - } - varDecl.minChar = minChar; - if(declList) { - declList.append(varDecl); - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - var prevInFncDecl = this.inFncDecl; - this.inFncDecl = false; - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - this.inFncDecl = prevInFncDecl; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { - this.reportParseError("Ambient variable can not have an initializer"); - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.actualText; - } - } else { - if(isConst) { - this.reportParseError("const declaration requires initializer"); - } - varDecl.limChar = this.scanner.pos; - } - varDecl.postComments = this.parseCommentsForLine(this.scanner.line); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - if(declList) { - declList.limChar = varDecl.limChar; - return declList; - } else { - return varDecl; - } - } - if(!multivar) { - declList = new TypeScript.ASTList(); - declList.minChar = varDecl.minChar; - declList.append(varDecl); - multivar = true; - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.startPos; - } - }; - Parser.prototype.parseMemberList = function (errorRecoverySet) { - var elements = new TypeScript.ASTList(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - return elements; - } - var idHint = null; - var memberName = null; - var memberExpr = null; - var member = null; - var minChar = this.scanner.startPos; - var isSet = false; - var skippedTokenForGetSetId = false; - var getSetTok = null; - var getSetStartPos = 0; - var getSetPos = 0; - for(; ; ) { - var accessorPattern = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { - isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; - getSetTok = this.currentToken; - getSetStartPos = this.scanner.startPos; - getSetPos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = isSet ? "set" : "get"; - idHint = idHint + this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - accessorPattern = true; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - } else if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { - this.reportParseError("Expected identifier, string or number as accessor name"); - } else { - skippedTokenForGetSetId = true; - memberName = TypeScript.Identifier.fromToken(getSetTok); - memberName.minChar = getSetStartPos; - memberName.limChar = getSetPos; - } - } else if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - idHint = this.currentToken.getText(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { - var ntok = this.currentToken; - idHint = ntok.value.toString(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - this.reportParseError("Expected identifier, string or number as member name"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); - memberName.limChar = this.scanner.lastTokenLimChar(); - } - } - if(!skippedTokenForGetSetId) { - this.currentToken = this.scanner.scan(); - } else { - skippedTokenForGetSetId = false; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - memberName.flags |= TypeScript.ASTFlags.OptionalName; - this.currentToken = this.scanner.scan(); - } - if(accessorPattern) { - var args = new TypeScript.ASTList(); - this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); - if(isSet && funcDecl.returnTypeAnnotation) { - this.reportParseError("Property setters may not declare a return type"); - } - funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - funcDecl.hint = idHint; - memberExpr = funcDecl; - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { - this.reportParseError("Expected 'new' on array declaration in member definition"); - } - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else { - this.reportParseError("Expected ':' in member definition"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - elements.flags |= TypeScript.ASTFlags.Error; - elements.minChar = minChar; - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - } - } - idHint = null; - elements.append(member); - member.limChar = this.scanner.lastTokenLimChar(); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } - } - if(member) { - elements.limChar = member.limChar; - } - elements.minChar = minChar; - return elements; - }; - Parser.prototype.parseArrayList = function (errorRecoverySet) { - var elements = null; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - return elements; - } else { - elements = new TypeScript.ASTList(); - elements.minChar = this.scanner.startPos; - } - var arg; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { - arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - } else { - arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - } - elements.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - }; - Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { - var arrayLiteral = null; - arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); - return arrayLiteral; - }; - Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { - var ast = null; - var sawId = false; - var inNew = false; - var minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var parseAsLambda = false; - var expectlambdaRParen = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Any: - case TypeScript.TokenID.String: - var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); - if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { - ast = new TypeScript.TypeReference(tid, 0); - sawId = true; - } else { - ast = tid; - sawId = true; - } - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.This: - ast = new TypeScript.AST(TypeScript.NodeType.This); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.Super: - ast = new TypeScript.AST(TypeScript.NodeType.Super); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.True: - ast = new TypeScript.AST(TypeScript.NodeType.True); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - case TypeScript.TokenID.False: - ast = new TypeScript.AST(TypeScript.NodeType.False); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - case TypeScript.TokenID.Null: - ast = new TypeScript.AST(TypeScript.NodeType.Null); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - case TypeScript.TokenID.New: - this.currentToken = this.scanner.scan(); - var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); - if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { - this.reportParseError("Cannot invoke 'new' on this expression"); - } else { - ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); - ast.minChar = minChar; - limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); - inNew = true; - } - break; - case TypeScript.TokenID.Function: - minChar = this.scanner.pos; - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = minChar; - limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - break; - } - if(ast == null) { - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var idText = this.currentToken.getText(); - ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); - sawId = true; - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; - } - limChar = this.scanner.lastTokenLimChar(); - } - } - if(inCast) { - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - } - if(ast == null) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: - minChar = this.scanner.pos; - var prevTokId = this.scanner.previousToken().tokenId; - this.currentToken = this.scanner.scan(); - var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; - if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - parseAsLambda = true; - expectlambdaRParen = false; - this.currentToken = this.scanner.scan(); - } else if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - parseAsLambda = true; - expectlambdaRParen = true; - } else { - ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); - limChar = this.scanner.lastTokenLimChar(); - parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); - expectlambdaRParen = true; - } - if((ast && !parseAsLambda)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); - break; - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast.isParenthesized = true; - } - break; - case TypeScript.TokenID.NumberLiteral: { - var numTok = this.currentToken; - this.currentToken = this.scanner.scan(); - ast = new TypeScript.NumberLiteral(numTok.value, numTok.text); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - case TypeScript.TokenID.StringLiteral: - ast = new TypeScript.StringLiteral(this.currentToken.getText()); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.RegularExpressionLiteral: { - var rtok = this.currentToken; - ast = new TypeScript.RegexLiteral(rtok.text); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - case TypeScript.TokenID.OpenBracket: - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); - ast.minChar = minChar; - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - case TypeScript.TokenID.OpenBrace: - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - members.minChar = minChar; - members.limChar = limChar; - break; - case TypeScript.TokenID.LessThan: - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); - (ast).castTerm = term; - break; - default: - if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - parseAsLambda = true; - ast = this.prevExpr; - } else { - this.reportParseError("Check format of expression term"); - if(this.errorRecovery) { - var ident = new TypeScript.MissingIdentifier(); - ident.minChar = minChar; - ident.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - } else { - limChar = this.scanner.lastTokenLimChar(); - } - ast = ident; - } - } - } - } - if(parseAsLambda) { - if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - } else if(ast) { - ast.isParenthesized = true; - } - } - if(sawId && (typeContext != TypeContext.NoTypes)) { - typeContext |= TypeContext.ArraySuffix; - } - var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); - if(postFix) { - if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { - var binExpr = postFix; - if(binExpr.operand2 == null) { - postFix = this.convertToTypeReference(postFix); - } - } - postFix.minChar = minChar; - postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); - return postFix; - } else { - return new TypeScript.AST(TypeScript.NodeType.Error); - } - }; - Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { - var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: lambdaArgs - }, expectClosingRParen); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - if(!skipNextRParen) { - ast.flags |= TypeScript.ASTFlags.SkipNextRParen; - } - ast.limChar = this.scanner.lastTokenLimChar(); - ; - return ast; - }; - Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { - if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } - var ast = null; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - var canAssign = true; - var idHint = null; - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - var exprIsAnonLambda = false; - if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { - canAssign = false; - this.currentToken = this.scanner.scan(); - var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); - ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); - ast.limChar = tempExpr.limChar; - ast.minChar = minChar; - } else { - ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); - var id; - var temp; - if(ast.nodeType == TypeScript.NodeType.Name) { - id = ast; - idHint = id.actualText; - } else if(ast.nodeType == TypeScript.NodeType.Dot) { - var subsumedExpr = false; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { - if((ast).operand2.nodeType == TypeScript.NodeType.Name) { - var op2ID = ((ast).operand2); - if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { - ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); - subsumedExpr = true; - } - } - } - if(!subsumedExpr) { - temp = ast; - while(temp.nodeType == TypeScript.NodeType.Dot) { - var binExpr = temp; - temp = binExpr.operand2; - } - if(temp.nodeType == TypeScript.NodeType.Name) { - id = temp; - idHint = id.actualText; - } - } - } - if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { - canAssign = false; - var operand = ast; - ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); - ast.limChar = this.scanner.pos; - ast.minChar = operand.minChar; - this.currentToken = this.scanner.scan(); - } - } - for(; ; ) { - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { - break; - } - if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { - break; - } - if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { - if(tokenInfo.binopPrecedence < minPrecedence) { - break; - } - if(!canAssign) { - this.reportParseError("illegal assignment"); - } - } else if(tokenInfo.binopPrecedence <= minPrecedence) { - break; - } - if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { - exprIsAnonLambda = true; - canAssign = false; - ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); - break; - } - this.currentToken = this.scanner.scan(); - canAssign = false; - if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { - if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { - exprIsAnonLambda = true; - canAssign = true; - } else { - this.prevExpr = ast; - var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - this.prevExpr = null; - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); - } - } else { - var tc = TypeContext.NoTypes; - var binExpr2; - binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); - if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = binExpr2.operand2; - funcDecl.hint = idHint; - } - binExpr2.minChar = ast.minChar; - binExpr2.limChar = this.scanner.lastTokenLimChar(); - idHint = null; - ast = binExpr2; - } - } - if(canAssign) { - ast.flags |= TypeScript.ASTFlags.Writeable; - } - if(!exprIsAnonLambda) { - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - if(preComments) { - ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; - } - ast.postComments = this.parseCommentsForLine(this.scanner.line); - } - return ast; - }; - Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { - var count = 0; - if(!ast) { - ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - ast.isParenthesized = true; - } - ast.minChar = lhsMinChar; - ast.limChar = lhsLimChar; - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: - if(inNew) { - var callExpr = ast; - callExpr.arguments = this.parseArgList(errorRecoverySet); - inNew = false; - } else { - if(!allowCall) { - return ast; - } - ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); - ast.minChar = lhsMinChar; - } - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - break; - case TypeScript.TokenID.OpenBracket: - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { - this.currentToken = this.scanner.scan(); - if(ast.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = ast; - typeRef.arrayCount++; - } else { - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); - } - ast.limChar = this.scanner.pos; - break; - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - case TypeScript.TokenID.Dot: { - var name = null; - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { - ast.flags |= TypeScript.ASTFlags.DotLHS; - name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Expected identifier following dot"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); - return ast; - } else { - name = new TypeScript.MissingIdentifier(); - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - } - case TypeScript.TokenID.EqualsGreaterThan: - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: ast - }, false); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - default: - return ast; - } - } - }; - Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{'"); - if(this.errorRecovery) { - var etryNode = tryNode; - etryNode.minChar = minChar; - etryNode.limChar = this.scanner.lastTokenLimChar(); - etryNode.flags |= TypeScript.ASTFlags.Error; - return etryNode; - } - } - tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - tryNode.minChar = minChar; - tryNode.limChar = tryNode.body.limChar; - tryNode.preComments = preComments; - tryNode.postComments = this.parseComments(); - return tryNode; - }; - Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { - var catchMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("Expected identifier in catch header"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = this.scanner.pos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); - param.id.minChar = this.scanner.startPos; - param.id.limChar = this.scanner.pos; - param.minChar = param.id.minChar; - param.limChar = param.id.limChar; - this.currentToken = this.scanner.scan(); - var statementPos = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start catch body"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = statementPos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var catchNode = new TypeScript.Catch(param, catchStmt); - catchNode.statement.minChar = catchMinChar; - catchNode.statement.limChar = statementPos; - catchNode.minChar = catchMinChar; - catchNode.limChar = catchStmt.limChar; - catchNode.preComments = preComments; - catchNode.postComments = this.parseComments(); - return catchNode; - }; - Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { - var finMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start body of finally statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); - efin.flags |= TypeScript.ASTFlags.Error; - efin.minChar = this.scanner.startPos; - efin.limChar = this.scanner.pos; - return efin; - } - } - var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var fin = new TypeScript.Finally(finBody); - fin.minChar = finMinChar; - fin.limChar = fin.body.limChar; - fin.preComments = preComments; - fin.postComments = this.parseComments(); - return fin; - }; - Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { - var tryPart = new TypeScript.Try(null); - var tryMinChar = this.scanner.startPos; - this.pushStmt(tryPart, labelList); - this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - this.popStmt(); - var tc = null; - var tf = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { - var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - tc = new TypeScript.TryCatch(tryPart, catchPart); - tc.minChar = tryPart.minChar; - tc.limChar = catchPart.limChar; - } - if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { - if(tc == null) { - this.reportParseError("try with neither catch nor finally"); - if(this.errorRecovery) { - var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - etf.flags |= TypeScript.ASTFlags.Error; - etf.minChar = this.scanner.startPos; - etf.limChar = this.scanner.pos; - return etf; - } - return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - } else { - return tc; - } - } else { - if(tc) { - tryPart = tc; - } - var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); - tf = new TypeScript.TryFinally(tryPart, finallyPart); - tf.minChar = tryMinChar; - tf.limChar = finallyPart.limChar; - return tf; - } - }; - Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { - var ast = null; - var labelList = null; - var astList = null; - var temp; - var modifiers = TypeScript.Modifiers.None; - var minChar = this.scanner.startPos; - var forInOk = false; - var needTerminator = false; - var fnOrVar = null; - var preComments = this.parseComments(); - function isAmbient() { - return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); - } - function mayNotBeExported() { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportError("Statement may not be exported"); - } - } - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.EndOfFile: - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.pos; - break; - case TypeScript.TokenID.Function: - if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { - this.currentToken = this.scanner.scan(); - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false, true); - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - this.reportParseError("function keyword can only introduce function declaration"); - } else if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - ast = fnOrVar; - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported) || this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } else { - ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, false, modifiers, null, true); - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - if(this.ambientModule) { - this.reportParseError("function declaration not permitted within ambient module"); - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } - break; - case TypeScript.TokenID.Module: - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); - preComments = null; - } - break; - case TypeScript.TokenID.Import: - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportParseError("export keyword not permitted on import declaration"); - } - ast = this.parseImportDeclaration(errorRecoverySet, modifiers); - needTerminator = true; - } - break; - case TypeScript.TokenID.Export: - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("'export' statements are only allowed at the global and module levels"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } - modifiers |= TypeScript.Modifiers.Exported; - this.currentToken = this.scanner.scan(); - break; - case TypeScript.TokenID.Private: - modifiers |= TypeScript.Modifiers.Private; - this.currentToken = this.scanner.scan(); - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - minChar = this.scanner.pos; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - case TypeScript.TokenID.Public: - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.pos; - modifiers |= TypeScript.Modifiers.Public; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { - this.reportParseError("'property' statements are only allowed within classes"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - case TypeScript.TokenID.Declare: - if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { - this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); - } - if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); - } - modifiers |= TypeScript.Modifiers.Ambient; - this.currentToken = this.scanner.scan(); - break; - case TypeScript.TokenID.Class: - if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("class not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); - } - break; - case TypeScript.TokenID.Interface: - if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("interface not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); - } - break; - case TypeScript.TokenID.Var: - var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); - if(declAst.nodeType == TypeScript.NodeType.VarDecl) { - ast = declAst; - } else { - ast = new TypeScript.Block(declAst, false); - } - needTerminator = true; - break; - case TypeScript.TokenID.Static: - if(this.currentClassDecl == null) { - this.reportParseError("Statics may only be class members"); - } - mayNotBeExported(); - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - } - } - if(isAmbient()) { - modifiers |= TypeScript.Modifiers.Ambient; - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); - var staticsList = this.topStaticsList(); - if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - staticsList.append(fnOrVar); - } - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - break; - case TypeScript.TokenID.For: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("syntax error: for statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - forInOk = true; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Var: - temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); - break; - case TypeScript.TokenID.Semicolon: - temp = null; - break; - default: - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); - break; - } - if(this.currentToken.tokenId == TypeScript.TokenID.In) { - if((temp == null) || (!forInOk)) { - this.reportParseError("malformed for statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - ast.flags |= TypeScript.ASTFlags.Error; - } - } else { - this.currentToken = this.scanner.scan(); - var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); - forInStmt.limChar = this.scanner.pos; - forInStmt.statement.minChar = minChar; - forInStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); - this.pushStmt(forInStmt, labelList); - forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forInStmt.minChar = minChar; - ast = forInStmt; - } - } else { - var forStmt = new TypeScript.ForStatement(temp); - forStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - forStmt.cond = null; - } else { - forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = forStmt; - ast.flags |= TypeScript.ASTFlags.Error; - } - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - forStmt.incr = null; - } else { - forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - this.pushStmt(forStmt, labelList); - forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forStmt.limChar = forStmt.body.limChar; - ast = forStmt; - } - break; - case TypeScript.TokenID.With: - { - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); - } - if(this.strictMode) { - this.reportParseError("'with' statements are not available in strict mode"); - } - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'with' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var withStmt = new TypeScript.WithStatement(expr); - withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - withStmt.minChar = minChar; - withStmt.limChar = withStmt.body.limChar; - ast = withStmt; - } - break; - case TypeScript.TokenID.Switch: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'switch' statement does not take modifiers"); - } - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - switchStmt.statement.minChar = minChar; - switchStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var caseListMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); - switchStmt.defaultCase = null; - switchStmt.caseList = new TypeScript.ASTList(); - var caseStmt = null; - this.pushStmt(switchStmt, labelList); - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { - var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); - caseStmt = new TypeScript.CaseStatement(); - caseStmt.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(isDefault) { - switchStmt.defaultCase = caseStmt; - } else { - caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - caseStmt.colonSpan.minChar = this.scanner.startPos; - caseStmt.colonSpan.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - caseStmt.body = new TypeScript.ASTList(); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); - caseStmt.limChar = caseStmt.body.limChar; - switchStmt.caseList.append(caseStmt); - } else { - break; - } - } - switchStmt.caseList.minChar = caseListMinChar; - switchStmt.caseList.limChar = this.scanner.pos; - switchStmt.limChar = switchStmt.caseList.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - this.popStmt(); - ast = switchStmt; - break; - } - case TypeScript.TokenID.While: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'while' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); - var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - whileStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(whileStmt, labelList); - whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - whileStmt.limChar = whileStmt.body.limChar; - this.popStmt(); - ast = whileStmt; - break; - } - case TypeScript.TokenID.Do: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'do' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var doStmt = new TypeScript.DoWhileStatement(); - doStmt.minChar = minChar; - this.pushStmt(doStmt, labelList); - doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); - this.popStmt(); - doStmt.whileAST = new TypeScript.Identifier("while"); - doStmt.whileAST.minChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); - doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - doStmt.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast = doStmt; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - break; - } - case TypeScript.TokenID.If: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("if statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ifStmt.minChar = minChar; - ifStmt.statement.minChar = minChar; - ifStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(ifStmt, labelList); - ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.thenBod.limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Else) { - this.currentToken = this.scanner.scan(); - ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.elseBod.limChar; - } - this.popStmt(); - ast = ifStmt; - break; - } - case TypeScript.TokenID.Try: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("try statement does not take modifiers"); - } - minChar = this.scanner.startPos; - ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); - break; - } - case TypeScript.TokenID.OpenBrace: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("block does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var block = new TypeScript.Block(new TypeScript.ASTList(), true); - this.pushStmt(block, labelList); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); - this.popStmt(); - block.statements.minChar = minChar; - block.statements.limChar = this.scanner.pos; - block.minChar = block.statements.minChar; - block.limChar = block.statements.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = block; - break; - } - case TypeScript.TokenID.Semicolon: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifier can not appear here"); - } - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - this.currentToken = this.scanner.scan(); - break; - case TypeScript.TokenID.Break: - case TypeScript.TokenID.Continue: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before jump statement"); - } - var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { - jump.target = this.currentToken.getText(); - this.currentToken = this.scanner.scan(); - } - this.resolveJumpTarget(jump); - ast = jump; - needTerminator = true; - break; - } - case TypeScript.TokenID.Return: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before return statement"); - } - if(!this.inFunction) { - this.reportParseError("return statement outside of function body"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.minChar = minChar; - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - needTerminator = true; - retStmt.limChar = this.scanner.lastTokenLimChar(); - ast = retStmt; - break; - } - case TypeScript.TokenID.Throw: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before a throw statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } else { - this.reportParseError("throw with no target"); - temp = null; - } - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); - ast.limChar = this.scanner.lastTokenLimChar(); - needTerminator = true; - break; - case TypeScript.TokenID.Enum: - this.currentToken = this.scanner.scan(); - ast = this.parseEnumDecl(errorRecoverySet, modifiers); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - (ast).modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).modFlags |= TypeScript.ModuleFlags.Exported; - } - break; - case TypeScript.TokenID.Debugger: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before debugger statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var debuggerStmt = new TypeScript.DebuggerStatement(); - debuggerStmt.minChar = minChar; - needTerminator = true; - debuggerStmt.limChar = this.scanner.lastTokenLimChar(); - ast = debuggerStmt; - break; - default: - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before an expression statement or label"); - } - minChar = this.scanner.startPos; - var svPos = this.scanner.pos; - temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.scanner.pos == svPos) { - this.currentToken = this.scanner.scan(); - ast = temp; - } else if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { - if(labelList == null) { - labelList = new TypeScript.ASTList(); - } - labelList.append(new TypeScript.Label(temp)); - this.currentToken = this.scanner.scan(); - } else { - ast = temp; - needTerminator = true; - } - } - if(ast) { - break; - } - } - if(needTerminator) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Semicolon: - this.currentToken = this.scanner.scan(); - ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; - break; - case TypeScript.TokenID.EndOfFile: - ast.limChar = this.scanner.pos; - case TypeScript.TokenID.CloseBrace: - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - break; - default: - if(!this.scanner.lastTokenHadNewline()) { - this.reportParseError("Expected ';'"); - } else { - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - } - break; - } - } - if(labelList) { - ast = new TypeScript.LabeledStatement(labelList, ast); - } - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - if(preComments) { - ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; - } - if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { - this.reportParseError("statement not permitted within ambient module"); - } - ast.flags |= TypeScript.ASTFlags.IsStatement; - return ast; - }; - Parser.prototype.okAmbientModuleMember = function (ast) { - var nt = ast.nodeType; - return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).bod == null)); - }; - Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { - var directivePrologue = sourceElms; - statements.minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; - var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; - var oldStrictMode = this.strictMode; - this.nestingLevel++; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - statements.limChar = limChar; - if(statements.members.length == 0) { - statements.preComments = this.parseComments(); - } else { - statements.postComments = this.parseComments(); - } - this.strictMode = oldStrictMode; - this.nestingLevel--; - return; - } - var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); - if(stmt) { - stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - statements.append(stmt); - limChar = stmt.limChar; - if(directivePrologue) { - if(stmt.nodeType == TypeScript.NodeType.QString) { - var qstring = stmt; - if(qstring.text == "\"use strict\"") { - statements.flags |= TypeScript.ASTFlags.StrictMode; - this.strictMode = true; - } else { - directivePrologue = false; - } - } else { - directivePrologue = false; - } - } - } - } - }; - Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { - var svGenTarget = TypeScript.moduleGenTarget; - try { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; - var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); - return new QuickParseResult(script, this.scanner.lexState); - }finally { - TypeScript.moduleGenTarget = svGenTarget; - } - }; - Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { - if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } - var _this = this; - this.fname = filename; - this.currentUnitIndex = unitIndex; - this.currentToken = null; - this.needTerminator = false; - this.inFunction = false; - this.inInterfaceDecl = false; - this.inFncDecl = false; - this.ambientModule = false; - this.ambientClass = false; - this.topLevel = true; - this.allowImportDeclaration = true; - this.prevIDTok = null; - this.statementInfoStack = new Array(); - this.hasTopLevelImportOrExport = false; - this.strictMode = false; - this.nestingLevel = 0; - this.prevExpr = null; - this.currentClassDefinition = null; - this.parsingClassConstructorDefinition = false; - this.parsingDeclareFile = false; - this.amdDependencies = []; - this.inferPropertiesFromThisAssignment = false; - this.requiresExtendsBlock = false; - this.scanner.resetComments(); - this.scanner.setErrorHandler(function (message) { - return _this.reportParseError(message); - }); - this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var minChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.pushDeclLists(); - var bod = new TypeScript.ASTList(); - bod.minChar = minChar; - this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); - while(true) { - this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); - if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { - break; - } - var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; - this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); - this.currentToken = this.scanner.scan(); - } - bod.limChar = this.scanner.pos; - var topLevelMod = null; - if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { - var correctedFileName = TypeScript.switchToForwardSlashes(filename); - var id = new TypeScript.Identifier(correctedFileName); - topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), null); - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; - topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; - if(this.parsingDeclareFile) { - topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; - } - topLevelMod.minChar = minChar; - topLevelMod.limChar = this.scanner.pos; - topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); - topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; - topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - topLevelMod.amdDependencies = this.amdDependencies; - bod = new TypeScript.ASTList(); - bod.minChar = topLevelMod.minChar; - bod.limChar = topLevelMod.limChar; - bod.append(topLevelMod); - } - var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); - script.bod = bod; - this.popDeclLists(); - script.minChar = minChar; - script.limChar = this.scanner.pos; - script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); - script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - script.isDeclareFile = this.parsingDeclareFile; - script.topLevelMod = topLevelMod; - script.containsUnicodeChar = this.scanner.seenUnicodeChar; - script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - script.requiresExtendsBlock = this.requiresExtendsBlock; - return script; - }; - return Parser; - })(); - TypeScript.Parser = Parser; - function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { - var fragment = sourceText.getText(minChar, limChar); - logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); - var quickParser = new Parser(); - quickParser.setErrorRecovery(null); - quickParser.errorCallback = errorCapture; - var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); - quickParser.currentClassDecl = quickClassDecl; - var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); - return result; - } - TypeScript.quickParse = quickParse; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var PrintContext = (function () { - function PrintContext(outfile, parser) { - this.outfile = outfile; - this.parser = parser; - this.builder = ""; - this.indent1 = " "; - this.indentStrings = []; - this.indentAmt = 0; - } - PrintContext.prototype.increaseIndent = function () { - this.indentAmt++; - }; - PrintContext.prototype.decreaseIndent = function () { - this.indentAmt--; - }; - PrintContext.prototype.startLine = function () { - if(this.builder.length > 0) { - TypeScript.CompilerDiagnostics.Alert(this.builder); - } - var indentString = this.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i++) { - indentString += this.indent1; - } - this.indentStrings[this.indentAmt] = indentString; - } - this.builder += indentString; - }; - PrintContext.prototype.write = function (s) { - this.builder += s; - }; - PrintContext.prototype.writeLine = function (s) { - this.builder += s; - this.outfile.WriteLine(this.builder); - this.builder = ""; - }; - return PrintContext; - })(); - TypeScript.PrintContext = PrintContext; - function prePrintAST(ast, parent, walker) { - var pc = walker.state; - ast.print(pc); - pc.increaseIndent(); - return ast; - } - TypeScript.prePrintAST = prePrintAST; - function postPrintAST(ast, parent, walker) { - var pc = walker.state; - pc.decreaseIndent(); - return ast; - } - TypeScript.postPrintAST = postPrintAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - TypeScript.LexEOF = (-1); - TypeScript.LexCodeNWL = 0x0A; - TypeScript.LexCodeRET = 0x0D; - TypeScript.LexCodeLS = 0x2028; - TypeScript.LexCodePS = 0x2029; - TypeScript.LexCodeTAB = 0x09; - TypeScript.LexCodeVTAB = 0x0B; - TypeScript.LexCode_e = 'e'.charCodeAt(0); - TypeScript.LexCode_E = 'E'.charCodeAt(0); - TypeScript.LexCode_x = 'x'.charCodeAt(0); - TypeScript.LexCode_X = 'X'.charCodeAt(0); - TypeScript.LexCode_a = 'a'.charCodeAt(0); - TypeScript.LexCode_A = 'A'.charCodeAt(0); - TypeScript.LexCode_f = 'f'.charCodeAt(0); - TypeScript.LexCode_F = 'F'.charCodeAt(0); - TypeScript.LexCode_g = 'g'.charCodeAt(0); - TypeScript.LexCode_m = 'm'.charCodeAt(0); - TypeScript.LexCode_i = 'i'.charCodeAt(0); - TypeScript.LexCode_u = 'u'.charCodeAt(0); - TypeScript.LexCode_0 = '0'.charCodeAt(0); - TypeScript.LexCode_9 = '9'.charCodeAt(0); - TypeScript.LexCode_8 = '8'.charCodeAt(0); - TypeScript.LexCode_7 = '7'.charCodeAt(0); - TypeScript.LexCodeBSL = '\\'.charCodeAt(0); - TypeScript.LexCodeSHP = '#'.charCodeAt(0); - TypeScript.LexCodeBNG = '!'.charCodeAt(0); - TypeScript.LexCodeQUO = '"'.charCodeAt(0); - TypeScript.LexCodeAPO = '\''.charCodeAt(0); - TypeScript.LexCodePCT = '%'.charCodeAt(0); - TypeScript.LexCodeAMP = '&'.charCodeAt(0); - TypeScript.LexCodeLPR = '('.charCodeAt(0); - TypeScript.LexCodeRPR = ')'.charCodeAt(0); - TypeScript.LexCodePLS = '+'.charCodeAt(0); - TypeScript.LexCodeMIN = '-'.charCodeAt(0); - TypeScript.LexCodeMUL = '*'.charCodeAt(0); - TypeScript.LexCodeSLH = '/'.charCodeAt(0); - TypeScript.LexCodeXOR = '^'.charCodeAt(0); - TypeScript.LexCodeCMA = ','.charCodeAt(0); - TypeScript.LexCodeDOT = '.'.charCodeAt(0); - TypeScript.LexCodeLT = '<'.charCodeAt(0); - TypeScript.LexCodeEQ = '='.charCodeAt(0); - TypeScript.LexCodeGT = '>'.charCodeAt(0); - TypeScript.LexCodeQUE = '?'.charCodeAt(0); - TypeScript.LexCodeLBR = '['.charCodeAt(0); - TypeScript.LexCodeRBR = ']'.charCodeAt(0); - TypeScript.LexCodeUSC = '_'.charCodeAt(0); - TypeScript.LexCodeLC = '{'.charCodeAt(0); - TypeScript.LexCodeRC = '}'.charCodeAt(0); - TypeScript.LexCodeBAR = '|'.charCodeAt(0); - TypeScript.LexCodeTIL = '~'.charCodeAt(0); - TypeScript.LexCodeCOL = ':'.charCodeAt(0); - TypeScript.LexCodeSMC = ';'.charCodeAt(0); - TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); - TypeScript.LexCodeDollar = '$'.charCodeAt(0); - TypeScript.LexCodeSpace = 32; - TypeScript.LexCodeAtSign = '@'.charCodeAt(0); - TypeScript.LexCodeASCIIChars = 128; - TypeScript.LexKeywordTable = undefined; - var autoToken = new Array(TypeScript.LexCodeASCIIChars); - var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); - var unicodeES3IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 543, - 546, - 563, - 592, - 685, - 688, - 696, - 699, - 705, - 720, - 721, - 736, - 740, - 750, - 750, - 890, - 890, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 974, - 976, - 983, - 986, - 1011, - 1024, - 1153, - 1164, - 1220, - 1223, - 1224, - 1227, - 1228, - 1232, - 1269, - 1272, - 1273, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1569, - 1594, - 1600, - 1610, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1786, - 1788, - 1808, - 1808, - 1810, - 1836, - 1920, - 1957, - 2309, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2699, - 2701, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2784, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2870, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 2997, - 2999, - 3001, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3294, - 3294, - 3296, - 3297, - 3333, - 3340, - 3342, - 3344, - 3346, - 3368, - 3370, - 3385, - 3424, - 3425, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3805, - 3840, - 3840, - 3904, - 3911, - 3913, - 3946, - 3976, - 3979, - 4096, - 4129, - 4131, - 4135, - 4137, - 4138, - 4176, - 4181, - 4256, - 4293, - 4304, - 4342, - 4352, - 4441, - 4447, - 4514, - 4520, - 4601, - 4608, - 4614, - 4616, - 4678, - 4680, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4742, - 4744, - 4744, - 4746, - 4749, - 4752, - 4782, - 4784, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4814, - 4816, - 4822, - 4824, - 4846, - 4848, - 4878, - 4880, - 4880, - 4882, - 4885, - 4888, - 4894, - 4896, - 4934, - 4936, - 4954, - 5024, - 5108, - 5121, - 5740, - 5743, - 5750, - 5761, - 5786, - 5792, - 5866, - 6016, - 6067, - 6176, - 6263, - 6272, - 6312, - 7680, - 7835, - 7840, - 7929, - 7936, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8319, - 8319, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8497, - 8499, - 8505, - 8544, - 8579, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12346, - 12353, - 12436, - 12445, - 12446, - 12449, - 12538, - 12540, - 12542, - 12549, - 12588, - 12593, - 12686, - 12704, - 12727, - 13312, - 19893, - 19968, - 40869, - 40960, - 42124, - 44032, - 55203, - 63744, - 64045, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65138, - 65140, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500, - - ]; - var unicodeES3IdCont = [ - 768, - 846, - 864, - 866, - 1155, - 1158, - 1425, - 1441, - 1443, - 1465, - 1467, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1476, - 1611, - 1621, - 1632, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 2305, - 2307, - 2364, - 2364, - 2366, - 2381, - 2385, - 2388, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2562, - 2562, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2662, - 2673, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2883, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2918, - 2927, - 2946, - 2947, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3047, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3174, - 3183, - 3202, - 3203, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3302, - 3311, - 3330, - 3331, - 3390, - 3395, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3984, - 3991, - 3993, - 4028, - 4038, - 4038, - 4140, - 4146, - 4150, - 4153, - 4160, - 4169, - 4182, - 4185, - 4969, - 4977, - 6068, - 6099, - 6112, - 6121, - 6160, - 6169, - 6313, - 6313, - 8255, - 8256, - 8400, - 8412, - 8417, - 8417, - 12330, - 12335, - 12441, - 12442, - 12539, - 12539, - 64286, - 64286, - 65056, - 65059, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343, - 65381, - 65381, - - ]; - var unicodeES5IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 705, - 710, - 721, - 736, - 740, - 748, - 748, - 750, - 750, - 880, - 884, - 886, - 887, - 890, - 893, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 1013, - 1015, - 1153, - 1162, - 1319, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1568, - 1610, - 1646, - 1647, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1774, - 1775, - 1786, - 1788, - 1791, - 1791, - 1808, - 1808, - 1810, - 1839, - 1869, - 1957, - 1969, - 1969, - 1994, - 2026, - 2036, - 2037, - 2042, - 2042, - 2048, - 2069, - 2074, - 2074, - 2084, - 2084, - 2088, - 2088, - 2112, - 2136, - 2208, - 2208, - 2210, - 2220, - 2308, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2417, - 2423, - 2425, - 2431, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2493, - 2493, - 2510, - 2510, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2785, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2869, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2929, - 2929, - 2947, - 2947, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 3001, - 3024, - 3024, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3133, - 3133, - 3160, - 3161, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3261, - 3261, - 3294, - 3294, - 3296, - 3297, - 3313, - 3314, - 3333, - 3340, - 3342, - 3344, - 3346, - 3386, - 3389, - 3389, - 3406, - 3406, - 3424, - 3425, - 3450, - 3455, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3807, - 3840, - 3840, - 3904, - 3911, - 3913, - 3948, - 3976, - 3980, - 4096, - 4138, - 4159, - 4159, - 4176, - 4181, - 4186, - 4189, - 4193, - 4193, - 4197, - 4198, - 4206, - 4208, - 4213, - 4225, - 4238, - 4238, - 4256, - 4293, - 4295, - 4295, - 4301, - 4301, - 4304, - 4346, - 4348, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4744, - 4746, - 4749, - 4752, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4822, - 4824, - 4880, - 4882, - 4885, - 4888, - 4954, - 4992, - 5007, - 5024, - 5108, - 5121, - 5740, - 5743, - 5759, - 5761, - 5786, - 5792, - 5866, - 5870, - 5872, - 5888, - 5900, - 5902, - 5905, - 5920, - 5937, - 5952, - 5969, - 5984, - 5996, - 5998, - 6000, - 6016, - 6067, - 6103, - 6103, - 6108, - 6108, - 6176, - 6263, - 6272, - 6312, - 6314, - 6314, - 6320, - 6389, - 6400, - 6428, - 6480, - 6509, - 6512, - 6516, - 6528, - 6571, - 6593, - 6599, - 6656, - 6678, - 6688, - 6740, - 6823, - 6823, - 6917, - 6963, - 6981, - 6987, - 7043, - 7072, - 7086, - 7087, - 7098, - 7141, - 7168, - 7203, - 7245, - 7247, - 7258, - 7293, - 7401, - 7404, - 7406, - 7409, - 7413, - 7414, - 7424, - 7615, - 7680, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8305, - 8305, - 8319, - 8319, - 8336, - 8348, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8505, - 8508, - 8511, - 8517, - 8521, - 8526, - 8526, - 8544, - 8584, - 11264, - 11310, - 11312, - 11358, - 11360, - 11492, - 11499, - 11502, - 11506, - 11507, - 11520, - 11557, - 11559, - 11559, - 11565, - 11565, - 11568, - 11623, - 11631, - 11631, - 11648, - 11670, - 11680, - 11686, - 11688, - 11694, - 11696, - 11702, - 11704, - 11710, - 11712, - 11718, - 11720, - 11726, - 11728, - 11734, - 11736, - 11742, - 11823, - 11823, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12348, - 12353, - 12438, - 12445, - 12447, - 12449, - 12538, - 12540, - 12543, - 12549, - 12589, - 12593, - 12686, - 12704, - 12730, - 12784, - 12799, - 13312, - 19893, - 19968, - 40908, - 40960, - 42124, - 42192, - 42237, - 42240, - 42508, - 42512, - 42527, - 42538, - 42539, - 42560, - 42606, - 42623, - 42647, - 42656, - 42735, - 42775, - 42783, - 42786, - 42888, - 42891, - 42894, - 42896, - 42899, - 42912, - 42922, - 43000, - 43009, - 43011, - 43013, - 43015, - 43018, - 43020, - 43042, - 43072, - 43123, - 43138, - 43187, - 43250, - 43255, - 43259, - 43259, - 43274, - 43301, - 43312, - 43334, - 43360, - 43388, - 43396, - 43442, - 43471, - 43471, - 43520, - 43560, - 43584, - 43586, - 43588, - 43595, - 43616, - 43638, - 43642, - 43642, - 43648, - 43695, - 43697, - 43697, - 43701, - 43702, - 43705, - 43709, - 43712, - 43712, - 43714, - 43714, - 43739, - 43741, - 43744, - 43754, - 43762, - 43764, - 43777, - 43782, - 43785, - 43790, - 43793, - 43798, - 43808, - 43814, - 43816, - 43822, - 43968, - 44002, - 44032, - 55203, - 55216, - 55238, - 55243, - 55291, - 63744, - 64109, - 64112, - 64217, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500, - - ]; - var unicodeES5IdCont = [ - 768, - 879, - 1155, - 1159, - 1425, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1477, - 1479, - 1479, - 1552, - 1562, - 1611, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 1984, - 1993, - 2027, - 2035, - 2070, - 2073, - 2075, - 2083, - 2085, - 2087, - 2089, - 2093, - 2137, - 2139, - 2276, - 2302, - 2304, - 2307, - 2362, - 2364, - 2366, - 2383, - 2385, - 2391, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2561, - 2563, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2641, - 2641, - 2662, - 2673, - 2677, - 2677, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2786, - 2787, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2884, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2914, - 2915, - 2918, - 2927, - 2946, - 2946, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3046, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3170, - 3171, - 3174, - 3183, - 3202, - 3203, - 3260, - 3260, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3298, - 3299, - 3302, - 3311, - 3330, - 3331, - 3390, - 3396, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3426, - 3427, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3981, - 3991, - 3993, - 4028, - 4038, - 4038, - 4139, - 4158, - 4160, - 4169, - 4182, - 4185, - 4190, - 4192, - 4194, - 4196, - 4199, - 4205, - 4209, - 4212, - 4226, - 4237, - 4239, - 4253, - 4957, - 4959, - 5906, - 5908, - 5938, - 5940, - 5970, - 5971, - 6002, - 6003, - 6068, - 6099, - 6109, - 6109, - 6112, - 6121, - 6155, - 6157, - 6160, - 6169, - 6313, - 6313, - 6432, - 6443, - 6448, - 6459, - 6470, - 6479, - 6576, - 6592, - 6600, - 6601, - 6608, - 6617, - 6679, - 6683, - 6741, - 6750, - 6752, - 6780, - 6783, - 6793, - 6800, - 6809, - 6912, - 6916, - 6964, - 6980, - 6992, - 7001, - 7019, - 7027, - 7040, - 7042, - 7073, - 7085, - 7088, - 7097, - 7142, - 7155, - 7204, - 7223, - 7232, - 7241, - 7248, - 7257, - 7376, - 7378, - 7380, - 7400, - 7405, - 7405, - 7410, - 7412, - 7616, - 7654, - 7676, - 7679, - 8204, - 8205, - 8255, - 8256, - 8276, - 8276, - 8400, - 8412, - 8417, - 8417, - 8421, - 8432, - 11503, - 11505, - 11647, - 11647, - 11744, - 11775, - 12330, - 12335, - 12441, - 12442, - 42528, - 42537, - 42607, - 42607, - 42612, - 42621, - 42655, - 42655, - 42736, - 42737, - 43010, - 43010, - 43014, - 43014, - 43019, - 43019, - 43043, - 43047, - 43136, - 43137, - 43188, - 43204, - 43216, - 43225, - 43232, - 43249, - 43264, - 43273, - 43302, - 43309, - 43335, - 43347, - 43392, - 43395, - 43443, - 43456, - 43472, - 43481, - 43561, - 43574, - 43587, - 43587, - 43596, - 43597, - 43600, - 43609, - 43643, - 43643, - 43696, - 43696, - 43698, - 43700, - 43703, - 43704, - 43710, - 43711, - 43713, - 43713, - 43755, - 43759, - 43765, - 43766, - 44003, - 44010, - 44012, - 44013, - 44016, - 44025, - 64286, - 64286, - 65024, - 65039, - 65056, - 65062, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343, - - ]; - function LexLookUpUnicodeMap(code, map) { - var lo = 0; - var hi = map.length; - var mid; - while(lo + 1 < hi) { - mid = lo + (hi - lo) / 2; - mid -= mid % 2; - if(map[mid] <= code && code <= map[mid + 1]) { - return true; - } - if(code < map[mid]) { - hi = mid; - } else { - lo = mid + 2; - } - } - return false; - } - TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; - function LexIsUnicodeDigit(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdCont); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdCont); - } - } - TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; - function LexIsUnicodeIdStart(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdStart); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdStart); - } - } - TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; - function LexInitialize() { - TypeScript.initializeStaticTokens(); - autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; - autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; - autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; - autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; - autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; - autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; - autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; - autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; - autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; - autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; - TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); - for(var i in (TypeScript.TokenID)._map) { - if((i) <= TypeScript.TokenID.LimKeyword) { - TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); - } - } - for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { - if(LexIsIdentifierStartChar(j)) { - lexIdStartTable[j] = true; - } else { - lexIdStartTable[j] = false; - } - } - } - TypeScript.LexInitialize = LexInitialize; - function LexAdjustIndent(code, indentAmt) { - if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { - return indentAmt + 1; - } else if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { - return indentAmt - 1; - } else { - return indentAmt; - } - } - TypeScript.LexAdjustIndent = LexAdjustIndent; - function LexIsIdentifierStartChar(code) { - return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); - } - TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; - function LexIsDigit(code) { - return ((code >= 48) && (code <= 57)); - } - TypeScript.LexIsDigit = LexIsDigit; - function LexIsIdentifierChar(code) { - return lexIdStartTable[code] || LexIsDigit(code); - } - TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; - function LexMatchingOpen(code) { - if(code == TypeScript.LexCodeRBR) { - return TypeScript.LexCodeLBR; - } else if(code == TypeScript.LexCodeRC) { - return TypeScript.LexCodeLC; - } else if(code == TypeScript.LexCodeRPR) { - return TypeScript.LexCodeLPR; - } else { - return 0; - } - } - TypeScript.LexMatchingOpen = LexMatchingOpen; - (function (NumberScanState) { - NumberScanState._map = []; - NumberScanState._map[0] = "Start"; - NumberScanState.Start = 0; - NumberScanState._map[1] = "InFraction"; - NumberScanState.InFraction = 1; - NumberScanState._map[2] = "InEmptyFraction"; - NumberScanState.InEmptyFraction = 2; - NumberScanState._map[3] = "InExponent"; - NumberScanState.InExponent = 3; - })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); - var NumberScanState = TypeScript.NumberScanState; - (function (LexState) { - LexState._map = []; - LexState._map[0] = "Start"; - LexState.Start = 0; - LexState._map[1] = "InMultilineComment"; - LexState.InMultilineComment = 1; - LexState._map[2] = "InMultilineSingleQuoteString"; - LexState.InMultilineSingleQuoteString = 2; - LexState._map[3] = "InMultilineDoubleQuoteString"; - LexState.InMultilineDoubleQuoteString = 3; - })(TypeScript.LexState || (TypeScript.LexState = {})); - var LexState = TypeScript.LexState; - (function (LexMode) { - LexMode._map = []; - LexMode._map[0] = "Line"; - LexMode.Line = 0; - LexMode._map[1] = "File"; - LexMode.File = 1; - })(TypeScript.LexMode || (TypeScript.LexMode = {})); - var LexMode = TypeScript.LexMode; - (function (CommentStyle) { - CommentStyle._map = []; - CommentStyle._map[0] = "Line"; - CommentStyle.Line = 0; - CommentStyle._map[1] = "Block"; - CommentStyle.Block = 1; - })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); - var CommentStyle = TypeScript.CommentStyle; - var StringSourceText = (function () { - function StringSourceText(text) { - this.text = text; - } - StringSourceText.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringSourceText.prototype.getLength = function () { - return this.text.length; - }; - return StringSourceText; - })(); - TypeScript.StringSourceText = StringSourceText; - var SourceTextSegment = (function () { - function SourceTextSegment(segmentStart, segmentEnd, segment) { - this.segmentStart = segmentStart; - this.segmentEnd = segmentEnd; - this.segment = segment; - } - SourceTextSegment.prototype.charCodeAt = function (index) { - return this.segment.charCodeAt(index - this.segmentStart); - }; - SourceTextSegment.prototype.substring = function (start, end) { - return this.segment.substring(start - this.segmentStart, end - this.segmentStart); - }; - return SourceTextSegment; - })(); - TypeScript.SourceTextSegment = SourceTextSegment; - var AggerateSourceTextSegment = (function () { - function AggerateSourceTextSegment(seg1, seg2) { - this.seg1 = seg1; - this.seg2 = seg2; - } - AggerateSourceTextSegment.prototype.charCodeAt = function (index) { - if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { - return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); - } - return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); - }; - AggerateSourceTextSegment.prototype.substring = function (start, end) { - if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { - return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); - } - return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); - }; - return AggerateSourceTextSegment; - })(); - TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; - var ScannerTextStream = (function () { - function ScannerTextStream(sourceText) { - this.sourceText = sourceText; - this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); - this.len = this.sourceText.getLength(); - } - ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); - ScannerTextStream.prototype.max = function (a, b) { - return a >= b ? a : b; - }; - ScannerTextStream.prototype.min = function (a, b) { - return a <= b ? a : b; - }; - ScannerTextStream.prototype.fetchSegment = function (start, end) { - if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg.seg1; - } - if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg; - } - var prev = this.agg.seg1; - var s = prev.segmentEnd; - var e = TypeScript.max(s + 512, end); - e = TypeScript.min(e, this.len); - var src = this.sourceText.getText(s, e); - var newSeg = new SourceTextSegment(s, e, src); - this.agg.seg2 = prev; - this.agg.seg1 = newSeg; - return this.agg; - }; - ScannerTextStream.prototype.charCodeAt = function (index) { - return this.fetchSegment(index, index + 1).charCodeAt(index); - }; - ScannerTextStream.prototype.substring = function (start, end) { - return this.fetchSegment(start, end).substring(start, end); - }; - return ScannerTextStream; - })(); - TypeScript.ScannerTextStream = ScannerTextStream; - var SavedTokens = (function () { - function SavedTokens() { - this.prevToken = null; - this.curSavedToken = null; - this.prevSavedToken = null; - this.prevToken = null; - this.currentToken = 0; - this.tokens = new Array(); - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.lexState = LexState.Start; - this.commentStack = new Array(); - this.lineMap = []; - } - SavedTokens.prototype.previousToken = function () { - return this.prevToken; - }; - SavedTokens.prototype.addToken = function (tok, scanner) { - this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); - }; - SavedTokens.prototype.scan = function () { - this.startLine = this.line; - this.startPos = this.col; - if(this.currentTokenIndex == this.currentTokens.length) { - if(this.line < this.lineMap.length) { - this.line++; - this.col = 0; - this.currentTokenIndex = 0; - this.currentTokens = this.tokensByLine[this.line]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(this.currentTokenIndex < this.currentTokens.length) { - this.prevToken = this.curSavedToken.tok; - this.prevSavedToken = this.curSavedToken; - this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; - var curToken = this.curSavedToken.tok; - this.pos = this.curSavedToken.limChar; - this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); - this.startPos = this.curSavedToken.minChar; - this.prevLine = this.line; - return curToken; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - }; - SavedTokens.prototype.lastTokenLimChar = function () { - if(this.prevSavedToken !== null) { - return this.prevSavedToken.limChar; - } else { - return 0; - } - }; - SavedTokens.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - SavedTokens.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - SavedTokens.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - SavedTokens.prototype.resetComments = function () { - this.commentStack = []; - }; - SavedTokens.prototype.setSourceText = function (newSrc, textMode) { - }; - SavedTokens.prototype.setErrorHandler = function (reportError) { - }; - SavedTokens.prototype.getLookAheadToken = function () { - throw new Error("Invalid operation."); - }; - return SavedTokens; - })(); - TypeScript.SavedTokens = SavedTokens; - var Scanner = (function () { - function Scanner() { - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.pos = 0; - this.startPos = 0; - this.len = 0; - this.lineMap = []; - this.ch = TypeScript.LexEOF; - this.lexState = LexState.Start; - this.mode = LexMode.File; - this.scanComments = true; - this.interveningWhitespace = false; - this.interveningWhitespacePos = 0; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.commentStack = new Array(); - this.saveScan = null; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - this.startCol = this.col; - this.startLine = this.line; - this.lineMap[1] = 0; - if(!TypeScript.LexKeywordTable) { - LexInitialize(); - } - } - Scanner.prototype.previousToken = function () { - return this.prevTok; - }; - Scanner.prototype.setSourceText = function (newSrc, textMode) { - this.mode = textMode; - this.scanComments = (this.mode === LexMode.Line); - this.pos = 0; - this.interveningWhitespacePos = 0; - this.startPos = 0; - this.line = 1; - this.col = 0; - this.startCol = this.col; - this.startLine = this.line; - this.len = 0; - this.src = newSrc.getText(0, newSrc.getLength()); - this.len = this.src.length; - this.lineMap = []; - this.lineMap[1] = 0; - this.commentStack = []; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - }; - Scanner.prototype.setErrorHandler = function (reportError) { - this.reportError = reportError; - }; - Scanner.prototype.setText = function (newSrc, textMode) { - this.setSourceText(new StringSourceText(newSrc), textMode); - }; - Scanner.prototype.setScanComments = function (value) { - this.scanComments = value; - }; - Scanner.prototype.tokenStart = function () { - this.startPos = this.pos; - this.startLine = this.line; - this.startCol = this.col; - this.interveningWhitespace = false; - }; - Scanner.prototype.peekChar = function () { - if(this.pos < this.len) { - return this.src.charCodeAt(this.pos); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.peekCharAt = function (index) { - if(index < this.len) { - return this.src.charCodeAt(index); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.IsHexDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.IsOctalDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.scanHexDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseInt(text), text); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanOctalDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsOctalDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseInt(text), text); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanDecimalNumber = function (state) { - var atLeastOneDigit = false; - var svPos = this.pos; - var svCol = this.col; - for(; ; ) { - if(LexIsDigit(this.ch)) { - atLeastOneDigit = true; - if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { - state = NumberScanState.InFraction; - } - this.nextChar(); - } else if(this.ch == TypeScript.LexCodeDOT) { - if(state == NumberScanState.Start) { - this.nextChar(); - state = NumberScanState.InEmptyFraction; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } else if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { - if(state == NumberScanState.Start) { - if(atLeastOneDigit) { - atLeastOneDigit = false; - this.nextChar(); - state = NumberScanState.InExponent; - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { - this.nextChar(); - state = NumberScanState.InExponent; - atLeastOneDigit = false; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } else if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { - if(state == NumberScanState.InExponent) { - if(!atLeastOneDigit) { - this.nextChar(); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } - } - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } - } - } - }; - Scanner.prototype.scanNumber = function () { - if(this.peekChar() == TypeScript.LexCode_0) { - switch(this.peekCharAt(this.pos + 1)) { - case TypeScript.LexCode_x: - case TypeScript.LexCode_X: - this.advanceChar(2); - return this.scanHexDigits(); - case TypeScript.LexCode_8: - case TypeScript.LexCode_9: - case TypeScript.LexCodeDOT: - return this.scanDecimalNumber(NumberScanState.Start); - default: - return this.scanOctalDigits(); - } - } else { - return this.scanDecimalNumber(NumberScanState.Start); - } - }; - Scanner.prototype.scanFraction = function () { - return this.scanDecimalNumber(NumberScanState.InFraction); - }; - Scanner.prototype.newLine = function () { - this.col = 0; - if(this.mode == LexMode.File) { - this.line++; - this.lineMap[this.line] = this.pos + 1; - } - }; - Scanner.prototype.finishMultilineComment = function () { - var ch2; - this.lexState = LexState.InMultilineComment; - while(this.pos < this.len) { - if(this.ch == TypeScript.LexCodeMUL) { - ch2 = this.peekCharAt(this.pos + 1); - if(ch2 == TypeScript.LexCodeSLH) { - this.advanceChar(2); - if(this.mode == LexMode.File) { - this.tokenStart(); - } - this.lexState = LexState.Start; - return true; - } - } else if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - this.nextChar(); - return false; - } - } else if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - this.nextChar(); - } - return false; - }; - Scanner.prototype.pushComment = function (comment) { - this.commentStack.push(comment); - }; - Scanner.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - Scanner.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - Scanner.prototype.resetComments = function () { - this.commentStack = []; - }; - Scanner.prototype.endsLine = function (c) { - return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); - }; - Scanner.prototype.finishSinglelineComment = function () { - while(this.pos < this.len) { - if(this.endsLine(this.ch)) { - break; - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - this.nextChar(); - } - if(this.mode == LexMode.File) { - this.tokenStart(); - } - }; - Scanner.prototype.findClosingSLH = function () { - var index = this.pos; - var ch2 = this.src.charCodeAt(index); - var prevCh = 0; - var liveEsc = false; - while(!this.endsLine(ch2) && (index < this.len)) { - if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { - return index; - } - prevCh = ch2; - index++; - if(liveEsc) { - liveEsc = false; - } else { - liveEsc = (prevCh == TypeScript.LexCodeBSL); - } - ch2 = this.src.charCodeAt(index); - } - return -1; - }; - Scanner.prototype.speculateRegex = function () { - if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { - return null; - } - var svPos = this.pos; - var svCol = this.col; - var index = this.findClosingSLH(); - if(index > 0) { - var pattern = this.src.substring(svPos, index); - var flags = ""; - this.pos = index + 1; - this.ch = this.peekChar(); - var flagsStart = this.pos; - while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { - this.nextChar(); - } - if((this.pos - flagsStart) > 3) { - return null; - } else { - flags = this.src.substring(flagsStart, this.pos); - } - var regex = undefined; - try { - regex = new RegExp(pattern, flags); - } catch (regexException) { - } - if(regex) { - this.col = svCol + (this.pos - this.startPos); - return new TypeScript.RegularExpressionLiteralToken(this.src.substring(svPos - 1, this.pos)); - } - } - this.pos = svPos; - this.col = svCol; - return null; - }; - Scanner.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - Scanner.prototype.lastTokenLimChar = function () { - return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; - }; - Scanner.prototype.advanceChar = function (amt) { - this.pos += amt; - this.col += amt; - this.ch = this.peekChar(); - }; - Scanner.prototype.nextChar = function () { - this.pos++; - this.col++; - this.ch = this.peekChar(); - }; - Scanner.prototype.getLookAheadToken = function () { - var prevLine = this.prevLine; - var line = this.line; - var col = this.col; - var pos = this.pos; - var startPos = this.startPos; - var startCol = this.startCol; - var startLine = this.startLine; - var ch = this.ch; - var prevTok = this.prevTok; - var lexState = this.lexState; - var interveningWhitespace = this.interveningWhitespace; - var interveningWhitespacePos = this.interveningWhitespacePos; - var leftCurlyCount = this.leftCurlyCount; - var rightCurlyCount = this.rightCurlyCount; - var seenUnicodeChar = this.seenUnicodeChar; - var seenUnicodeCharInComment = this.seenUnicodeCharInComment; - var commentStackLength = this.commentStack.length; - var lookAheadToken = this.scan(); - this.prevLine = prevLine; - this.line = line; - this.col = col; - this.pos = pos; - this.startPos = startPos; - this.startCol = startCol; - this.startLine = startLine; - this.ch = ch; - this.prevTok = prevTok; - this.lexState = lexState; - this.interveningWhitespace = interveningWhitespace; - this.interveningWhitespacePos = interveningWhitespacePos; - this.leftCurlyCount = leftCurlyCount; - this.rightCurlyCount = rightCurlyCount; - this.seenUnicodeChar = seenUnicodeChar; - this.seenUnicodeCharInComment = seenUnicodeCharInComment; - this.commentStack.length = commentStackLength; - return lookAheadToken; - }; - Scanner.prototype.scanInLine = function () { - if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { - this.ch = this.peekChar(); - var commentLine = this.line; - this.finishMultilineComment(); - if(this.startPos < this.pos) { - var commentText = this.src.substring(this.startPos, this.pos); - this.tokenStart(); - return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } else if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { - this.ch = this.peekChar(); - this.lexState = LexState.Start; - return this.scanStringConstant(TypeScript.LexCodeAPO); - } else if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { - this.ch = this.peekChar(); - this.lexState = LexState.Start; - return this.scanStringConstant(TypeScript.LexCodeQUO); - } - this.prevLine = this.line; - var prevTok = this.innerScan(); - if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { - this.prevTok = prevTok; - } - return prevTok; - }; - Scanner.prototype.scan = function () { - this.prevLine = this.line; - this.prevTok = this.innerScan(); - if(this.saveScan) { - this.saveScan.addToken(this.prevTok, this); - } - return this.prevTok; - }; - Scanner.prototype.isValidUnicodeIdentifierChar = function () { - var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); - this.seenUnicodeChar = this.seenUnicodeChar || valid; - return valid; - }; - Scanner.prototype.scanStringConstant = function (endCode) { - scanStringConstantLoop: -for(; ; ) { - switch(this.ch) { - case TypeScript.LexEOF: - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - this.seenUnicodeChar = true; - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: - if(this.ch == endCode) { - this.nextChar(); - break scanStringConstantLoop; - } - break; - case TypeScript.LexCodeBSL: - this.nextChar(); - switch(this.ch) { - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: - case TypeScript.LexCodeBSL: - this.nextChar(); - continue scanStringConstantLoop; - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - this.seenUnicodeChar = true; - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: - if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { - this.nextChar(); - } - this.newLine(); - if(this.mode == LexMode.Line) { - this.nextChar(); - this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; - break scanStringConstantLoop; - } - break; - case TypeScript.LexCode_x: - case TypeScript.LexCode_u: - var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; - this.nextChar(); - for(var i = 0; i < expectedHexDigits; i++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - break; - } - } - continue scanStringConstantLoop; - } - break; - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeChar = true; - } - this.nextChar(); - } - return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); - }; - Scanner.prototype.scanIdentifier = function () { - var hasEscape = false; - var isFirstChar = (this.ch == TypeScript.LexCodeBSL); - var hasUnicode = false; - for(; ; ) { - while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { - this.nextChar(); - } - if(this.ch == TypeScript.LexCodeBSL) { - this.nextChar(); - if(this.ch == TypeScript.LexCode_u) { - this.nextChar(); - for(var h = 0; h < 4; h++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } - var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); - if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { - } else { - this.reportScannerError("Invalid identifier character"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - hasEscape = true; - isFirstChar = false; - continue; - } - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - break; - } - var id; - var text = this.src.substring(this.startPos, this.pos); - if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { - return TypeScript.staticTokens[id]; - } else { - return new TypeScript.IdentifierToken(text, hasEscape); - } - }; - Scanner.prototype.innerScan = function () { - var rtok; - this.tokenStart(); - this.ch = this.peekChar(); - start: -while(this.pos < this.len) { - if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { - return this.scanIdentifier(); - } else if(this.ch == TypeScript.LexCodeSpace) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - do { - this.nextChar(); - }while(this.ch == TypeScript.LexCodeSpace); - if(this.mode == LexMode.Line) { - var whitespaceText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); - } else { - this.tokenStart(); - this.interveningWhitespace = true; - } - } else if(this.ch == TypeScript.LexCodeSLH) { - this.nextChar(); - var commentText; - if(this.ch == TypeScript.LexCodeSLH) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.finishSinglelineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else if(this.ch == TypeScript.LexCodeMUL) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.nextChar(); - this.finishMultilineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var endsLine = this.endsLine(this.peekChar()); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else { - var regexTok = this.speculateRegex(); - if(regexTok) { - return regexTok; - } else { - if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Slash]; - } - } - } - } else if(this.ch == TypeScript.LexCodeSMC) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - } else if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { - var endCode = this.ch; - this.nextChar(); - return this.scanStringConstant(endCode); - } else if(autoToken[this.ch]) { - var atok = autoToken[this.ch]; - if(atok.tokenId == TypeScript.TokenID.OpenBrace) { - this.leftCurlyCount++; - } else if(atok.tokenId == TypeScript.TokenID.CloseBrace) { - this.rightCurlyCount++; - } - this.nextChar(); - return atok; - } else if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { - rtok = this.scanNumber(); - if(rtok) { - return rtok; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } else { - switch(this.ch) { - case TypeScript.LexCodeTAB: - case TypeScript.LexCodeVTAB: - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - if(this.mode == LexMode.Line) { - do { - this.nextChar(); - }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)); - var wsText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); - } else { - this.interveningWhitespace = true; - } - case 0xFF: - case 0xFE: - case 0xEF: - case 0xBB: - case 0xBF: - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - case TypeScript.LexCodeNWL: - case TypeScript.LexCodeRET: - if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - this.nextChar(); - this.tokenStart(); - this.interveningWhitespace = true; - break; - case TypeScript.LexCodeDOT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } else { - this.nextChar(); - rtok = this.scanFraction(); - if(rtok) { - return rtok; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } - } - case TypeScript.LexCodeEQ: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; - } - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Equals]; - } - case TypeScript.LexCodeBNG: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; - } - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; - } - case TypeScript.LexCodePLS: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Plus]; - } - case TypeScript.LexCodeMIN: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Minus]; - } - case TypeScript.LexCodeMUL: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; - } - case TypeScript.LexCodePCT: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Percent]; - } - case TypeScript.LexCodeLT: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; - } - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; - } - case TypeScript.LexCodeGT: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; - } else if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { - this.advanceChar(4); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; - } else { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; - } - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; - } - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; - } - case TypeScript.LexCodeXOR: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Caret]; - } - case TypeScript.LexCodeBAR: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Bar]; - } - case TypeScript.LexCodeAMP: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.And]; - } - default: - this.reportScannerError("Invalid character"); - this.nextChar(); - continue start; - } - } - } - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - }; - Scanner.prototype.reportScannerError = function (message) { - if(this.reportError) { - this.reportError(message); - } - }; - return Scanner; - })(); - TypeScript.Scanner = Scanner; - function convertTokToIDName(tok) { - return convertTokToIDBase(tok, true, false); - } - TypeScript.convertTokToIDName = convertTokToIDName; - function convertTokToID(tok, strictMode) { - return convertTokToIDBase(tok, false, strictMode); - } - TypeScript.convertTokToID = convertTokToID; - function convertTokToIDBase(tok, identifierName, strictMode) { - if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { - var tokInfo = TypeScript.lookupToken(tok.tokenId); - if(tokInfo != undefined) { - var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; - if(strictMode) { - resFlags |= TypeScript.Reservation.JavascriptFutureStrict; - } - if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { - return true; - } - } else { - return false; - } - } else { - return false; - } - } - function getLineNumberFromPosition(lineMap, position) { - if(position === -1) { - return 0; - } - var min = 0; - var max = lineMap.length - 1; - while(min < max) { - var med = (min + max) >> 1; - if(position < lineMap[med]) { - max = med - 1; - } else if(position < lineMap[med + 1]) { - min = max = med; - } else { - min = med + 1; - } - } - return min; - } - TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; - function getSourceLineColFromMap(lineCol, minChar, lineMap) { - var line = getLineNumberFromPosition(lineMap, minChar); - if(line > 0) { - lineCol.line = line; - lineCol.col = (minChar - lineMap[line]); - } - } - TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; - function getLineColumnFromPosition(script, position) { - var result = { - line: -1, - col: -1 - }; - getSourceLineColFromMap(result, position, script.locationInfo.lineMap); - if(result.col >= 0) { - result.col++; - } - return result; - } - TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; - function getPositionFromLineColumn(script, line, column) { - return script.locationInfo.lineMap[line] + (column - 1); - } - TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; - function isPrimitiveTypeToken(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.String: - return true; - } - return false; - } - TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; - function isModifier(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Public: - case TypeScript.TokenID.Private: - case TypeScript.TokenID.Static: - return true; - } - return false; - } - TypeScript.isModifier = isModifier; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AssignScopeContext = (function () { - function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { - this.scopeChain = scopeChain; - this.typeFlow = typeFlow; - this.modDeclChain = modDeclChain; - } - return AssignScopeContext; - })(); - TypeScript.AssignScopeContext = AssignScopeContext; - function pushAssignScope(scope, context, type, classType, fnc) { - var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); - chain.thisType = type; - chain.classType = classType; - chain.fnc = fnc; - context.scopeChain = chain; - } - TypeScript.pushAssignScope = pushAssignScope; - function popAssignScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popAssignScope = popAssignScope; - function instanceCompare(a, b) { - if(((a == null) || (!a.isInstanceProperty()))) { - return b; - } else { - return a; - } - } - TypeScript.instanceCompare = instanceCompare; - function instanceFilterStop(s) { - return s.isInstanceProperty(); - } - TypeScript.instanceFilterStop = instanceFilterStop; - var ScopeSearchFilter = (function () { - function ScopeSearchFilter(select, stop) { - this.select = select; - this.stop = stop; - this.result = null; - } - ScopeSearchFilter.prototype.reset = function () { - this.result = null; - }; - ScopeSearchFilter.prototype.update = function (b) { - this.result = this.select(this.result, b); - if(this.result) { - return this.stop(this.result); - } else { - return false; - } - }; - return ScopeSearchFilter; - })(); - TypeScript.ScopeSearchFilter = ScopeSearchFilter; - TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); - function preAssignModuleScopes(ast, context) { - var moduleDecl = ast; - var memberScope = null; - var aggScope = null; - if(moduleDecl.name && moduleDecl.mod) { - moduleDecl.name.sym = moduleDecl.mod.symbol; - } - var mod = moduleDecl.mod; - if(!mod) { - return; - } - memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); - mod.memberScope = memberScope; - context.modDeclChain.push(moduleDecl); - context.typeFlow.checker.currentModDecl = moduleDecl; - aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - mod.containedScope = aggScope; - if(mod.symbol) { - context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); - } - } - TypeScript.preAssignModuleScopes = preAssignModuleScopes; - function preAssignClassScopes(ast, context) { - var classDecl = ast; - var memberScope = null; - var aggScope = null; - if(classDecl.name && classDecl.type) { - classDecl.name.sym = classDecl.type.symbol; - } - var classType = ast.type; - if(classType) { - var classSym = classType.symbol; - memberScope = context.typeFlow.checker.scopeOf(classType); - aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - classType.containedScope = aggScope; - classType.memberScope = memberScope; - var instanceType = classType.instanceType; - memberScope = context.typeFlow.checker.scopeOf(instanceType); - instanceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, instanceType, classType, null); - instanceType.containedScope = aggScope; - } else { - ast.type = context.typeFlow.anyType; - } - } - TypeScript.preAssignClassScopes = preAssignClassScopes; - function preAssignInterfaceScopes(ast, context) { - var interfaceDecl = ast; - var memberScope = null; - var aggScope = null; - if(interfaceDecl.name && interfaceDecl.type) { - interfaceDecl.name.sym = interfaceDecl.type.symbol; - } - var interfaceType = ast.type; - memberScope = context.typeFlow.checker.scopeOf(interfaceType); - interfaceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - interfaceType.containedScope = aggScope; - } - TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; - function preAssignWithScopes(ast, context) { - var withStmt = ast; - var withType = withStmt.type; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var withType = new TypeScript.Type(); - var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); - withType.members = members; - withType.ambientMembers = ambientMembers; - withType.symbol = withSymbol; - withType.setHasImplementation(); - withStmt.type = withType; - var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); - pushAssignScope(withScope, context, null, null, null); - withType.containedScope = withScope; - } - TypeScript.preAssignWithScopes = preAssignWithScopes; - function preAssignFuncDeclScopes(ast, context) { - var funcDecl = ast; - var container = null; - var localContainer = null; - if(funcDecl.type) { - localContainer = ast.type.symbol; - } - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isInnerStatic = isStatic && context.scopeChain.fnc != null; - var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; - if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { - var instType = context.scopeChain.thisType; - if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(!funcDecl.isMethod() || isStatic) { - parentScope = instType.constructorScope; - } else { - parentScope = instType.containedScope; - } - } else { - if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { - parentScope = instType.constructorScope; - } else if(isStatic && context.scopeChain.classType) { - parentScope = context.scopeChain.classType.containedScope; - } else { - parentScope = instType.containedScope; - } - } - container = instType.symbol; - } else if(funcDecl.isConstructor && context.scopeChain.thisType) { - container = context.scopeChain.thisType.symbol; - } - if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { - if(context.scopeChain.fnc && context.scopeChain.fnc.type) { - container = context.scopeChain.fnc.type.symbol; - } - var funcScope = null; - var outerFnc = context.scopeChain.fnc; - var nameText = funcDecl.name ? funcDecl.name.actualText : null; - var fgSym = null; - if(isStatic) { - if(outerFnc.type.members == null && container.getType().memberScope) { - outerFnc.type.members = ((container).type.memberScope).valueMembers; - } - funcScope = context.scopeChain.fnc.type.memberScope; - outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; - } else { - funcScope = context.scopeChain.scope; - } - if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { - if(isStatic) { - fgSym = funcScope.findLocal(nameText, false, false); - } else { - fgSym = funcScope.findLocal(nameText, false, false); - } - } - context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); - if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); - } - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; - } - if(funcDecl.name && funcDecl.type) { - funcDecl.name.sym = funcDecl.type.symbol; - } - funcDecl.scopeType = funcDecl.type; - if(funcDecl.isOverload) { - return; - } - var funcTable = new TypeScript.StringHashTable(); - var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); - var ambientFuncTable = new TypeScript.StringHashTable(); - var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); - var funcStaticTable = new TypeScript.StringHashTable(); - var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); - var ambientFuncStaticTable = new TypeScript.StringHashTable(); - var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); - funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; - var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); - var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); - if(funcDecl.isConstructor && context.scopeChain.thisType) { - context.scopeChain.thisType.constructorScope = locals; - } - funcDecl.symbols = funcTable; - if(!funcDecl.isSpecialFn()) { - var group = funcDecl.type; - var signature = funcDecl.signature; - if(!funcDecl.isConstructor) { - group.containedScope = locals; - locals.container = group.symbol; - group.memberScope = statics; - statics.container = group.symbol; - } - funcDecl.enclosingFnc = context.scopeChain.fnc; - group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; - var fgSym = ast.type.symbol; - if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { - context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); - context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); - } - if(signature.parameters) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); - } - } - context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); - } - if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; - pushAssignScope(locals, context, thisType, null, funcDecl); - } - if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isAccessor()) { - if(funcDecl.name.sym) { - funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); - } - } - } - TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; - function preAssignCatchScopes(ast, context) { - var catchBlock = ast; - if(catchBlock.param) { - var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); - catchBlock.containedScope = catchLocals; - pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); - } - } - TypeScript.preAssignCatchScopes = preAssignCatchScopes; - function preAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - list.enclosingScope = context.scopeChain.scope; - } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - preAssignModuleScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - preAssignClassScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - preAssignInterfaceScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.With) { - preAssignWithScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - preAssignFuncDeclScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.Catch) { - preAssignCatchScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.TypeRef) { - go = false; - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preAssignScopes = preAssignScopes; - function postAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var prevModDecl = ast; - popAssignScope(context); - context.modDeclChain.pop(); - if(context.modDeclChain.length >= 1) { - context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; - } - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - popAssignScope(context); - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - popAssignScope(context); - } else if(ast.nodeType == TypeScript.NodeType.With) { - popAssignScope(context); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { - popAssignScope(context); - } - } else if(ast.nodeType == TypeScript.NodeType.Catch) { - var catchBlock = ast; - if(catchBlock.param) { - popAssignScope(context); - } - } else { - go = false; - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.postAssignScopes = postAssignScopes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var TypeCollectionContext = (function () { - function TypeCollectionContext(scopeChain, checker) { - this.scopeChain = scopeChain; - this.checker = checker; - this.script = null; - } - return TypeCollectionContext; - })(); - TypeScript.TypeCollectionContext = TypeCollectionContext; - var MemberScopeContext = (function () { - function MemberScopeContext(flow, pos, matchFlag) { - this.flow = flow; - this.pos = pos; - this.matchFlag = matchFlag; - this.type = null; - this.ast = null; - this.options = new TypeScript.AstWalkOptions(); - } - return MemberScopeContext; - })(); - TypeScript.MemberScopeContext = MemberScopeContext; - var EnclosingScopeContext = (function () { - function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { - this.logger = logger; - this.script = script; - this.text = text; - this.pos = pos; - this.isMemberCompletion = isMemberCompletion; - this.scopeGetter = null; - this.objectLiteralScopeGetter = null; - this.scopeStartAST = null; - this.skipNextFuncDeclForClass = false; - this.deepestModuleDecl = null; - this.enclosingClassDecl = null; - this.enclosingObjectLit = null; - this.publicsOnly = true; - this.useFullAst = false; - } - EnclosingScopeContext.prototype.getScope = function () { - return this.scopeGetter(); - }; - EnclosingScopeContext.prototype.getObjectLiteralScope = function () { - return this.objectLiteralScopeGetter(); - }; - EnclosingScopeContext.prototype.getScopeAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScopePosition = function () { - return this.scopeStartAST.minChar; - }; - EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { - return this.getScriptFragmentStartAST().minChar; - }; - EnclosingScopeContext.prototype.getScriptFragment = function () { - if(this.scriptFragment == null) { - var ast = this.getScriptFragmentStartAST(); - var minChar = ast.minChar; - var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); - this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; - } - return this.scriptFragment; - }; - return EnclosingScopeContext; - })(); - TypeScript.EnclosingScopeContext = EnclosingScopeContext; - function preFindMemberScope(ast, parent, walker) { - var memScope = walker.state; - if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { - memScope.ast = ast; - if((ast.type == null) && (memScope.pos >= 0)) { - memScope.flow.inScopeTypeCheck(ast, memScope.scope); - } - memScope.type = ast.type; - memScope.options.stopWalk(); - } - return ast; - } - TypeScript.preFindMemberScope = preFindMemberScope; - function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { - var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); - var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); - chain.thisType = thisType; - chain.classType = classType; - chain.moduleDecl = moduleDecl; - context.scopeChain = chain; - } - TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; - function popTypeCollectionScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popTypeCollectionScope = popTypeCollectionScope; - function preFindEnclosingScope(ast, parent, walker) { - var context = walker.state; - var minChar = ast.minChar; - var limChar = ast.limChar; - if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { - limChar = context.pos; - } - if((minChar <= context.pos) && (limChar >= context.pos)) { - switch(ast.nodeType) { - case TypeScript.NodeType.Script: - var script = ast; - context.scopeGetter = function () { - return script.bod === null ? null : script.bod.enclosingScope; - }; - context.scopeStartAST = script; - break; - case TypeScript.NodeType.ClassDeclaration: - context.scopeGetter = function () { - return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; - }; - context.scopeStartAST = ast; - context.enclosingClassDecl = ast; - break; - case TypeScript.NodeType.ObjectLit: - var objectLit = ast; - if(objectLit.targetType) { - context.scopeGetter = function () { - return objectLit.targetType.containedScope; - }; - context.objectLiteralScopeGetter = function () { - return objectLit.targetType.memberScope; - }; - context.enclosingObjectLit = objectLit; - } - break; - case TypeScript.NodeType.ModuleDeclaration: - context.deepestModuleDecl = ast; - context.scopeGetter = function () { - return ast.type === null ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - case TypeScript.NodeType.InterfaceDeclaration: - context.scopeGetter = function () { - return (ast.type === null) ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - case TypeScript.NodeType.FuncDecl: - { - var funcDecl = ast; - if(context.skipNextFuncDeclForClass) { - context.skipNextFuncDeclForClass = false; - } else { - context.scopeGetter = function () { - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(ast.type && ast.type.enclosingType) { - return ast.type.enclosingType.constructorScope; - } - } - if(funcDecl.scopeType) { - return funcDecl.scopeType.containedScope; - } - if(funcDecl.type) { - return funcDecl.type.containedScope; - } - return null; - }; - context.scopeStartAST = ast; - } - } - break; - } - walker.options.goChildren = true; - } else { - walker.options.goChildren = false; - } - return ast; - } - TypeScript.preFindEnclosingScope = preFindEnclosingScope; - function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { - var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); - TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); - if(context.scopeStartAST === null) { - return null; - } - return context; - } - TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Signature = (function () { - function Signature() { - this.hasVariableArgList = false; - this.parameters = null; - this.declAST = null; - this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - this.nonOptionalParameterCount = 0; - } - Signature.prototype.specializeType = function (pattern, replacement, checker) { - var result = new Signature(); - if(this.hasVariableArgList) { - result.hasVariableArgList = true; - } - result.returnType = new TypeScript.TypeLink(); - if(this.returnType.type) { - result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); - } else { - result.returnType.type = checker.anyType; - } - if(this.parameters) { - result.parameters = []; - for(var i = 0, len = this.parameters.length; i < len; i++) { - var oldSym = this.parameters[i]; - var paramDef = new TypeScript.ValueLocation(); - var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); - paramSym.declAST = this.declAST; - paramDef.symbol = paramSym; - paramDef.typeLink = new TypeScript.TypeLink(); - result.parameters[i] = paramSym; - var oldType = oldSym.getType(); - if(oldType) { - paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); - } else { - paramDef.typeLink.type = checker.anyType; - } - } - } - result.nonOptionalParameterCount = this.nonOptionalParameterCount; - result.declAST = this.declAST; - return result; - }; - Signature.prototype.toString = function () { - return this.toStringHelper(false, false, null); - }; - Signature.prototype.toStringHelper = function (shortform, brackets, scope) { - return this.toStringHelperEx(shortform, brackets, scope).toString(); - }; - Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { - if (typeof prefix === "undefined") { prefix = ""; } - var builder = new TypeScript.MemberNameArray(); - if(brackets) { - builder.prefix = prefix + "["; - } else { - builder.prefix = prefix + "("; - } - var paramLen = this.parameters.length; - var len = this.hasVariableArgList ? paramLen - 1 : paramLen; - for(var i = 0; i < len; i++) { - builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - if(i < paramLen - 1) { - builder.add(TypeScript.MemberName.create(", ")); - } - } - if(this.hasVariableArgList) { - builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - } - if(shortform) { - if(brackets) { - builder.add(TypeScript.MemberName.create("] => ")); - } else { - builder.add(TypeScript.MemberName.create(") => ")); - } - } else { - if(brackets) { - builder.add(TypeScript.MemberName.create("]: ")); - } else { - builder.add(TypeScript.MemberName.create("): ")); - } - } - if(this.returnType.type) { - builder.add(this.returnType.type.getScopedTypeNameEx(scope)); - } else { - builder.add(TypeScript.MemberName.create("any")); - } - return builder; - }; - return Signature; - })(); - TypeScript.Signature = Signature; - var SignatureGroup = (function () { - function SignatureGroup() { - this.signatures = []; - this.hasImplementation = true; - this.definitionSignature = null; - this.hasBeenTypechecked = false; - this.flags = TypeScript.SignatureFlags.None; - } - SignatureGroup.prototype.addSignature = function (signature) { - if(this.signatures == null) { - this.signatures = new Array(); - } - this.signatures[this.signatures.length] = signature; - if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Signature)) { - this.definitionSignature = signature; - } - }; - SignatureGroup.prototype.toString = function () { - return this.signatures.toString(); - }; - SignatureGroup.prototype.toStrings = function (prefix, shortform, scope, getPrettyTypeName, useSignature) { - var _this = this; - var result = []; - var len = this.signatures.length; - if(!getPrettyTypeName && len > 1) { - shortform = false; - } - var getMemberNameOfSignature = function (signature) { - if(_this.flags & TypeScript.SignatureFlags.IsIndexer) { - return signature.toStringHelperEx(shortform, true, scope); - } else { - return signature.toStringHelperEx(shortform, false, scope, prefix); - } - }; - if(useSignature) { - result.push(getMemberNameOfSignature(useSignature)); - } else { - for(var i = 0; i < len; i++) { - if(len > 1 && this.signatures[i] == this.definitionSignature) { - continue; - } - result.push(getMemberNameOfSignature(this.signatures[i])); - if(getPrettyTypeName) { - break; - } - } - } - if(getPrettyTypeName && len > 1) { - var lastMemberName = result[result.length - 1]; - var overloadString = " (+ " + ((this.definitionSignature != null) ? len - 2 : len - 1) + " overload(s))"; - lastMemberName.add(TypeScript.MemberName.create(overloadString)); - } - return result; - }; - SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { - var result = new SignatureGroup(); - if(this.signatures) { - for(var i = 0, len = this.signatures.length; i < len; i++) { - result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); - } - } - return result; - }; - SignatureGroup.prototype.verifySignatures = function (checker) { - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - for(var j = i + 1; j < len; j++) { - if(this.signatures[i].declAST && this.signatures[j].declAST && (TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Signature) && TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Signature)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); - } - } - if(this.definitionSignature) { - if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); - } - } - } - } - }; - SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { - if(this.hasBeenTypechecked) { - return; - } - this.hasBeenTypechecked = true; - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); - } - if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); - } - checker.typeFlow.typeCheck(this.signatures[i].declAST); - } - this.verifySignatures(checker); - } - }; - return SignatureGroup; - })(); - TypeScript.SignatureGroup = SignatureGroup; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeCheckStatus) { - TypeCheckStatus._map = []; - TypeCheckStatus._map[0] = "NotStarted"; - TypeCheckStatus.NotStarted = 0; - TypeCheckStatus._map[1] = "Started"; - TypeCheckStatus.Started = 1; - TypeCheckStatus._map[2] = "Finished"; - TypeCheckStatus.Finished = 2; - })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); - var TypeCheckStatus = TypeScript.TypeCheckStatus; - function aLexicallyEnclosesB(a, b) { - if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; - } else { - return false; - } - } - TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; - function aEnclosesB(a, b) { - while(a.container) { - if(a == b || aLexicallyEnclosesB(a.container, b)) { - return true; - } - a = a.container; - } - return false; - } - TypeScript.aEnclosesB = aEnclosesB; - var Symbol = (function () { - function Symbol(name, location, length, unitIndex) { - this.name = name; - this.location = location; - this.length = length; - this.unitIndex = unitIndex; - this.bound = false; - this.flags = TypeScript.SymbolFlags.None; - this.isObjectLitField = false; - this.declAST = null; - this.declModule = null; - this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; - } - Symbol.prototype.instanceScope = function () { - return null; - }; - Symbol.prototype.isVariable = function () { - return false; - }; - Symbol.prototype.isMember = function () { - return false; - }; - Symbol.prototype.isInferenceSymbol = function () { - return false; - }; - Symbol.prototype.isWith = function () { - return false; - }; - Symbol.prototype.writeable = function () { - return false; - }; - Symbol.prototype.isType = function () { - return false; - }; - Symbol.prototype.getType = function () { - return null; - }; - Symbol.prototype.isAccessor = function () { - return false; - }; - Symbol.prototype.isInstanceProperty = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); - }; - Symbol.prototype.getTypeName = function (scope) { - return this.getTypeNameEx(scope).toString(); - }; - Symbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.toString()); - }; - Symbol.prototype.getOptionalNameString = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; - }; - Symbol.prototype.pathToRoot = function () { - var path = new Array(); - var node = this; - while(node && (node.name != TypeScript.globalId)) { - path[path.length] = node; - node = node.container; - } - return path; - }; - Symbol.prototype.findCommonAncestorPath = function (b) { - if(this.container == null) { - return new Array(); - } - var aPath = this.container.pathToRoot(); - var bPath; - if(b) { - bPath = b.pathToRoot(); - } else { - bPath = new Array(); - } - var commonNodeIndex = -1; - for(var i = 0, aLen = aPath.length; i < aLen; i++) { - var aNode = aPath[i]; - for(var j = 0, bLen = bPath.length; j < bLen; j++) { - var bNode = bPath[j]; - if(aNode == bNode) { - commonNodeIndex = i; - break; - } - } - if(commonNodeIndex >= 0) { - break; - } - } - if(commonNodeIndex >= 0) { - return aPath.slice(0, commonNodeIndex); - } else { - return aPath; - } - }; - Symbol.prototype.getPrettyName = function (scopeSymbol) { - return this.name; - }; - Symbol.prototype.scopeRelativeName = function (scope) { - if(scope == null) { - return this.getPrettyName(null) + this.getOptionalNameString(); - } - var lca = this.findCommonAncestorPath(scope.container); - var builder = ""; - for(var i = 0, len = lca.length; i < len; i++) { - var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); - builder = prettyName + "." + builder; - } - builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); - return builder; - }; - Symbol.prototype.fullName = function (scope) { - var scopeSymbol = !scope ? null : scope.container; - var scopeRootPath = !scopeSymbol ? [] : scopeSymbol.pathToRoot(); - var dynamicModuleRoot = null; - if(scopeRootPath.length > 0 && scopeRootPath[scopeRootPath.length - 1].declAST && scopeRootPath[scopeRootPath.length - 1].declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (scopeRootPath[scopeRootPath.length - 1].declAST).isWholeFile()) { - dynamicModuleRoot = scopeRootPath[scopeRootPath.length - 1]; - } - var builder = this.getPrettyName(scopeSymbol); - var ancestor = this.container; - while(ancestor && (ancestor.name != TypeScript.globalId) && ancestor != dynamicModuleRoot) { - builder = ancestor.getPrettyName(scopeSymbol) + "." + builder; - ancestor = ancestor.container; - } - return builder; - }; - Symbol.prototype.isExternallyVisible = function (checker) { - if(this == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return false; - } - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - return this.container == checker.gloMod; - } - return this.container.isExternallyVisible(checker); - }; - Symbol.prototype.visible = function (scope, checker) { - if(checker == null || this.container == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return true; - } else { - return aEnclosesB(this, scope.container); - } - } else { - return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); - } - } else { - var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - var isMethod = isFunction && (this.declAST).isMethod(); - var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); - var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); - var isAlias = this.isType() && (this).aliasLink; - if(this.isMember() || isMethod || isStaticFunction || isAlias) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { - if(scope.container == null && this.container != scope.container) { - return false; - } else { - return this.container == null ? true : aEnclosesB(scope.container, this.container); - } - } else { - return true; - } - } else if(this.container) { - return aEnclosesB(this, scope.container); - } else { - return true; - } - } - }; - Symbol.prototype.addRef = function (identifier) { - if(!this.refs) { - this.refs = []; - } - this.refs[this.refs.length] = identifier; - }; - Symbol.prototype.toString = function () { - if(this.name) { - return this.name; - } else { - return "_anonymous"; - } - }; - Symbol.prototype.print = function (outfile) { - outfile.Write(this.toString()); - }; - Symbol.prototype.specializeType = function (pattern, replacement, checker) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.setType = function (type) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.kind = function () { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { - if(this.declAST != null) { - if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.declAST; - } else if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.container.declAST; - } - } - return null; - }; - Symbol.prototype.getVarDeclFromSymbol = function () { - if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { - return this.declAST; - } - return null; - }; - Symbol.prototype.getDocComments = function () { - if(this.declAST != null) { - return this.declAST.getDocComments(); - } - return []; - }; - Symbol.prototype.isStatic = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); - }; - return Symbol; - })(); - TypeScript.Symbol = Symbol; - var ValueLocation = (function () { - function ValueLocation() { } - return ValueLocation; - })(); - TypeScript.ValueLocation = ValueLocation; - var InferenceSymbol = (function (_super) { - __extends(InferenceSymbol, _super); - function InferenceSymbol(name, location, length, unitIndex) { - _super.call(this, name, location, length, unitIndex); - this.typeCheckStatus = TypeCheckStatus.NotStarted; - } - InferenceSymbol.prototype.isInferenceSymbol = function () { - return true; - }; - InferenceSymbol.prototype.transferVarFlags = function (varFlags) { - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { - this.flags |= TypeScript.SymbolFlags.Ambient; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { - this.flags |= TypeScript.SymbolFlags.Constant; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { - this.flags |= TypeScript.SymbolFlags.Static; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { - this.flags |= TypeScript.SymbolFlags.Property; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { - this.flags |= TypeScript.SymbolFlags.Private; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { - this.flags |= TypeScript.SymbolFlags.Public; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { - this.flags |= TypeScript.SymbolFlags.Readonly; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { - this.flags |= TypeScript.SymbolFlags.Exported; - } - }; - return InferenceSymbol; - })(Symbol); - TypeScript.InferenceSymbol = InferenceSymbol; - var TypeSymbol = (function (_super) { - __extends(TypeSymbol, _super); - function TypeSymbol(locName, location, length, unitIndex, type) { - _super.call(this, locName, location, length, unitIndex); - this.type = type; - this.expansions = []; - this.expansionsDeclAST = []; - this.isDynamic = false; - this.isMethod = false; - this.aliasLink = null; - this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; - this.prettyName = this.name; - } - TypeSymbol.prototype.addLocation = function (loc) { - if(this.additionalLocations == null) { - this.additionalLocations = []; - } - this.additionalLocations[this.additionalLocations.length] = loc; - }; - TypeSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Type; - }; - TypeSymbol.prototype.isType = function () { - return true; - }; - TypeSymbol.prototype.getType = function () { - return this.type; - }; - TypeSymbol.prototype.getTypeNameEx = function (scope) { - return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); - }; - TypeSymbol.prototype.instanceScope = function () { - if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { - return this.type.instanceType.constructorScope; - } else { - return this.type.containedScope; - } - }; - TypeSymbol.prototype.toString = function () { - var result = this.type.getTypeName(); - if(this.name) { - result = this.name + ":" + result; - } - return result; - }; - TypeSymbol.prototype.isClass = function () { - return this.instanceType != null; - }; - TypeSymbol.prototype.isFunction = function () { - return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - }; - TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { - if(this.type == pattern) { - return replacement.symbol; - } else { - var replType = this.type.specializeType(pattern, replacement, checker, false); - if(replType != this.type) { - var result = new TypeSymbol(this.name, -1, 0, -1, replType); - return result; - } else { - return this; - } - } - }; - TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { - if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { - var symbolPath = scopeSymbol.pathToRoot(); - var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); - if(prettyName != null) { - return prettyName.name; - } - } - return this.prettyName; - }; - TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { - var scopeSymbolPathLength = scopeSymbolPath.length; - var externalSymbol = null; - if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { - if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - if(externalSymbol == null) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - } - return externalSymbol; - }; - TypeSymbol.prototype.getDocComments = function () { - var comments = []; - if(this.declAST != null) { - comments = comments.concat(this.declAST.getDocComments()); - } - for(var i = 0; i < this.expansionsDeclAST.length; i++) { - comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); - } - return comments; - }; - return TypeSymbol; - })(InferenceSymbol); - TypeScript.TypeSymbol = TypeSymbol; - var WithSymbol = (function (_super) { - __extends(WithSymbol, _super); - function WithSymbol(location, unitIndex, withType) { - _super.call(this, "with", location, 4, unitIndex, withType); - } - WithSymbol.prototype.isWith = function () { - return true; - }; - return WithSymbol; - })(TypeSymbol); - TypeScript.WithSymbol = WithSymbol; - var FieldSymbol = (function (_super) { - __extends(FieldSymbol, _super); - function FieldSymbol(name, location, unitIndex, canWrite, field) { - _super.call(this, name, location, name.length, unitIndex); - this.canWrite = canWrite; - this.field = field; - this.getter = null; - this.setter = null; - this.hasBeenEmitted = false; - this.name = name; - this.location = location; - } - FieldSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Field; - }; - FieldSymbol.prototype.writeable = function () { - return this.isAccessor() ? this.setter != null : this.canWrite; - }; - FieldSymbol.prototype.getType = function () { - return this.field.typeLink.type; - }; - FieldSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.field.typeLink.type ? this.field.typeLink.type.getScopedTypeNameEx(scope) : TypeScript.MemberName.create("any"), this.name + this.getOptionalNameString() + ": ", ""); - }; - FieldSymbol.prototype.isMember = function () { - return true; - }; - FieldSymbol.prototype.setType = function (type) { - this.field.typeLink.type = type; - }; - FieldSymbol.prototype.isAccessor = function () { - return this.getter != null || this.setter != null; - }; - FieldSymbol.prototype.isVariable = function () { - return true; - }; - FieldSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); - if(rType != this.field.typeLink.type) { - var fieldDef = new ValueLocation(); - var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); - result.flags = this.flags; - fieldDef.symbol = result; - fieldDef.typeLink = new TypeScript.TypeLink(); - result.setType(rType); - result.typeCheckStatus = TypeCheckStatus.Finished; - return result; - } else { - return this; - } - }; - FieldSymbol.prototype.getDocComments = function () { - if(this.getter != null || this.setter != null) { - var comments = []; - if(this.getter != null) { - comments = comments.concat(this.getter.getDocComments()); - } - if(this.setter != null) { - comments = comments.concat(this.setter.getDocComments()); - } - return comments; - } else if(this.declAST != null) { - return this.declAST.getDocComments(); - } - return []; - }; - return FieldSymbol; - })(InferenceSymbol); - TypeScript.FieldSymbol = FieldSymbol; - var ParameterSymbol = (function (_super) { - __extends(ParameterSymbol, _super); - function ParameterSymbol(name, location, unitIndex, parameter) { - _super.call(this, name, location, name.length, unitIndex); - this.parameter = parameter; - this.paramDocComment = null; - this.funcDecl = null; - this.argsOffset = (-1); - this.name = name; - this.location = location; - } - ParameterSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Parameter; - }; - ParameterSymbol.prototype.writeable = function () { - return true; - }; - ParameterSymbol.prototype.getType = function () { - return this.parameter.typeLink.type; - }; - ParameterSymbol.prototype.setType = function (type) { - this.parameter.typeLink.type = type; - }; - ParameterSymbol.prototype.isVariable = function () { - return true; - }; - ParameterSymbol.prototype.isOptional = function () { - if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { - return (this.parameter.symbol.declAST).isOptional; - } else { - return false; - } - }; - ParameterSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); - }; - ParameterSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); - if(this.parameter.typeLink.type != rType) { - var paramDef = new ValueLocation(); - var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); - paramDef.symbol = result; - result.setType(rType); - return result; - } else { - return this; - } - }; - ParameterSymbol.prototype.getParameterDocComments = function () { - if(!this.paramDocComment) { - var parameterComments = []; - if(this.funcDecl) { - var fncDocComments = this.funcDecl.getDocComments(); - var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); - if(paramComment != "") { - parameterComments.push(paramComment); - } - } - var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); - if(docComments != "") { - parameterComments.push(docComments); - } - this.paramDocComment = parameterComments.join("\n"); - } - return this.paramDocComment; - }; - ParameterSymbol.prototype.fullName = function () { - return this.name; - }; - return ParameterSymbol; - })(InferenceSymbol); - TypeScript.ParameterSymbol = ParameterSymbol; - var VariableSymbol = (function (_super) { - __extends(VariableSymbol, _super); - function VariableSymbol(name, location, unitIndex, variable) { - _super.call(this, name, location, name.length, unitIndex); - this.variable = variable; - } - VariableSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Variable; - }; - VariableSymbol.prototype.writeable = function () { - return true; - }; - VariableSymbol.prototype.getType = function () { - return this.variable.typeLink.type; - }; - VariableSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); - }; - VariableSymbol.prototype.setType = function (type) { - this.variable.typeLink.type = type; - }; - VariableSymbol.prototype.isVariable = function () { - return true; - }; - return VariableSymbol; - })(InferenceSymbol); - TypeScript.VariableSymbol = VariableSymbol; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopedMembers = (function () { - function ScopedMembers(dualMembers) { - this.dualMembers = dualMembers; - this.allMembers = this.dualMembers; - this.publicMembers = this.dualMembers.primaryTable; - this.privateMembers = this.dualMembers.secondaryTable; - } - ScopedMembers.prototype.addPublicMember = function (key, data) { - return this.dualMembers.primaryTable.add(key, data); - }; - ScopedMembers.prototype.addPrivateMember = function (key, data) { - return this.dualMembers.secondaryTable.add(key, data); - }; - return ScopedMembers; - })(); - TypeScript.ScopedMembers = ScopedMembers; - (function (SymbolKind) { - SymbolKind._map = []; - SymbolKind._map[0] = "None"; - SymbolKind.None = 0; - SymbolKind._map[1] = "Type"; - SymbolKind.Type = 1; - SymbolKind._map[2] = "Field"; - SymbolKind.Field = 2; - SymbolKind._map[3] = "Parameter"; - SymbolKind.Parameter = 3; - SymbolKind._map[4] = "Variable"; - SymbolKind.Variable = 4; - })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); - var SymbolKind = TypeScript.SymbolKind; - var SymbolScope = (function () { - function SymbolScope(container) { - this.container = container; - } - SymbolScope.prototype.printLabel = function () { - return "base"; - }; - SymbolScope.prototype.getAllSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllTypeSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllValueSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.find = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.print = function (outfile) { - if(this.container) { - outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); - } else { - outfile.WriteLine(this.printLabel() + " scope..."); - } - }; - SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { - throw new Error("please implement in derived class"); - }; - SymbolScope.prototype.getTable = function () { - throw new Error("please implement in derived class"); - }; - return SymbolScope; - })(); - TypeScript.SymbolScope = SymbolScope; - function symbolCanBeUsed(sym, publicOnly) { - return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; - } - var SymbolAggregateScope = (function (_super) { - __extends(SymbolAggregateScope, _super); - function SymbolAggregateScope(container) { - _super.call(this, container); - this.valueCache = null; - this.valueImplCache = null; - this.valueAmbientCache = null; - this.typeCache = null; - this.typeImplCache = null; - this.typeAmbientCache = null; - this.parents = null; - this.container = container; - } - SymbolAggregateScope.prototype.printLabel = function () { - return "agg"; - }; - SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var sym = this.parents[i].search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - } - return filter.result; - }; - SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - this.parents[i].print(outfile); - } - } - }; - SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var implCache = this.valueImplCache; - if(typespace) { - implCache = this.typeImplCache; - } - if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findImplementation(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(implCache) { - if(typespace) { - this.typeImplCache = new TypeScript.StringHashTable(); - implCache = this.typeImplCache; - } else { - this.valueImplCache = new TypeScript.StringHashTable(); - implCache = this.valueImplCache; - } - } - implCache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueCache; - if(typespace) { - cache = this.typeCache; - } - if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].find(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeCache = new TypeScript.StringHashTable(); - cache = this.typeCache; - } else { - this.valueCache = new TypeScript.StringHashTable(); - cache = this.valueCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueAmbientCache; - if(typespace) { - cache = this.typeAmbientCache; - } - if(cache && ((sym = cache.lookup(name)) != null)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findAmbient(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeAmbientCache = new TypeScript.StringHashTable(); - cache = this.typeAmbientCache; - } else { - this.valueAmbientCache = new TypeScript.StringHashTable(); - cache = this.valueAmbientCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.addParentScope = function (parent) { - if(this.parents == null) { - this.parents = new Array(); - } - this.parents[this.parents.length] = parent; - }; - return SymbolAggregateScope; - })(SymbolScope); - TypeScript.SymbolAggregateScope = SymbolAggregateScope; - var SymbolTableScope = (function (_super) { - __extends(SymbolTableScope, _super); - function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.container = container; - } - SymbolTableScope.prototype.printLabel = function () { - return "table"; - }; - SymbolTableScope.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - filter.update(sym); - return filter.result; - }; - SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { - var table = null; - var ambientTable = null; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } else { - table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - if(table) { - var s = table.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - }; - SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - if(sym) { - if(sym.kind() == SymbolKind.Type) { - var typeSym = sym; - if(!typeSym.type.hasImplementation()) { - sym = null; - } - } else if(sym.container) { - if(sym.container.kind() == SymbolKind.Type) { - var ctypeSym = sym.container; - if(!ctypeSym.type.hasImplementation()) { - sym = null; - } - } - } - } - return sym; - }; - SymbolTableScope.prototype.getTable = function () { - return this.valueMembers.publicMembers; - }; - return SymbolTableScope; - })(SymbolScope); - TypeScript.SymbolTableScope = SymbolTableScope; - var SymbolScopeBuilder = (function (_super) { - __extends(SymbolScopeBuilder, _super); - function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.parent = parent; - this.container = container; - } - SymbolScopeBuilder.prototype.printLabel = function () { - return "builder"; - }; - SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(this.parent) { - sym = this.parent.search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - return filter.result; - }; - SymbolScopeBuilder.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.parent) { - this.parent.print(outfile); - } - }; - SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(table && ((sym = table.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.find(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.findAmbient(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - return null; - }; - SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { - var table = null; - if(ambient) { - if(typespace) { - table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; - } else { - table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; - } - } else { - if(typespace) { - table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; - } else { - table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; - } - } - if(table) { - if(!table.add(symbol.name, symbol)) { - errorReporter.duplicateIdentifier(ast, symbol.name); - } - } else { - TypeScript.CompilerDiagnostics.Alert("YYYYY"); - } - symbol.container = container; - }; - SymbolScopeBuilder.prototype.getTable = function () { - return this.valueMembers.allMembers; - }; - return SymbolScopeBuilder; - })(SymbolScope); - TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; - var FilteredSymbolScope = (function (_super) { - __extends(FilteredSymbolScope, _super); - function FilteredSymbolScope(scope, container, filter) { - _super.call(this, container); - this.scope = scope; - this.filter = filter; - } - FilteredSymbolScope.prototype.print = function (outfile) { - this.scope.print(outfile); - }; - FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { - this.filter.reset(); - return this.scope.search(this.filter, name, publicOnly, typespace); - }; - FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return this.scope.findLocal(name, publicOnly, typespace); - }; - return FilteredSymbolScope; - })(SymbolScope); - TypeScript.FilteredSymbolScope = FilteredSymbolScope; - var FilteredSymbolScopeBuilder = (function (_super) { - __extends(FilteredSymbolScopeBuilder, _super); - function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { - _super.call(this, valueMembers, null, null, null, parent, container); - this.filter = filter; - } - FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return sym; - }; - FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - throw new Error("please implement"); - }; - FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return _super.prototype.find.call(this, name, publicOnly, typespace); - }; - return FilteredSymbolScopeBuilder; - })(SymbolScopeBuilder); - TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TokenID) { - TokenID._map = []; - TokenID._map[0] = "Any"; - TokenID.Any = 0; - TokenID._map[1] = "Bool"; - TokenID.Bool = 1; - TokenID._map[2] = "Break"; - TokenID.Break = 2; - TokenID._map[3] = "Case"; - TokenID.Case = 3; - TokenID._map[4] = "Catch"; - TokenID.Catch = 4; - TokenID._map[5] = "Class"; - TokenID.Class = 5; - TokenID._map[6] = "Const"; - TokenID.Const = 6; - TokenID._map[7] = "Continue"; - TokenID.Continue = 7; - TokenID._map[8] = "Debugger"; - TokenID.Debugger = 8; - TokenID._map[9] = "Default"; - TokenID.Default = 9; - TokenID._map[10] = "Delete"; - TokenID.Delete = 10; - TokenID._map[11] = "Do"; - TokenID.Do = 11; - TokenID._map[12] = "Else"; - TokenID.Else = 12; - TokenID._map[13] = "Enum"; - TokenID.Enum = 13; - TokenID._map[14] = "Export"; - TokenID.Export = 14; - TokenID._map[15] = "Extends"; - TokenID.Extends = 15; - TokenID._map[16] = "Declare"; - TokenID.Declare = 16; - TokenID._map[17] = "False"; - TokenID.False = 17; - TokenID._map[18] = "Finally"; - TokenID.Finally = 18; - TokenID._map[19] = "For"; - TokenID.For = 19; - TokenID._map[20] = "Function"; - TokenID.Function = 20; - TokenID._map[21] = "Constructor"; - TokenID.Constructor = 21; - TokenID._map[22] = "Get"; - TokenID.Get = 22; - TokenID._map[23] = "If"; - TokenID.If = 23; - TokenID._map[24] = "Implements"; - TokenID.Implements = 24; - TokenID._map[25] = "Import"; - TokenID.Import = 25; - TokenID._map[26] = "In"; - TokenID.In = 26; - TokenID._map[27] = "InstanceOf"; - TokenID.InstanceOf = 27; - TokenID._map[28] = "Interface"; - TokenID.Interface = 28; - TokenID._map[29] = "Let"; - TokenID.Let = 29; - TokenID._map[30] = "Module"; - TokenID.Module = 30; - TokenID._map[31] = "New"; - TokenID.New = 31; - TokenID._map[32] = "Number"; - TokenID.Number = 32; - TokenID._map[33] = "Null"; - TokenID.Null = 33; - TokenID._map[34] = "Package"; - TokenID.Package = 34; - TokenID._map[35] = "Private"; - TokenID.Private = 35; - TokenID._map[36] = "Protected"; - TokenID.Protected = 36; - TokenID._map[37] = "Public"; - TokenID.Public = 37; - TokenID._map[38] = "Return"; - TokenID.Return = 38; - TokenID._map[39] = "Set"; - TokenID.Set = 39; - TokenID._map[40] = "Static"; - TokenID.Static = 40; - TokenID._map[41] = "String"; - TokenID.String = 41; - TokenID._map[42] = "Super"; - TokenID.Super = 42; - TokenID._map[43] = "Switch"; - TokenID.Switch = 43; - TokenID._map[44] = "This"; - TokenID.This = 44; - TokenID._map[45] = "Throw"; - TokenID.Throw = 45; - TokenID._map[46] = "True"; - TokenID.True = 46; - TokenID._map[47] = "Try"; - TokenID.Try = 47; - TokenID._map[48] = "TypeOf"; - TokenID.TypeOf = 48; - TokenID._map[49] = "Var"; - TokenID.Var = 49; - TokenID._map[50] = "Void"; - TokenID.Void = 50; - TokenID._map[51] = "With"; - TokenID.With = 51; - TokenID._map[52] = "While"; - TokenID.While = 52; - TokenID._map[53] = "Yield"; - TokenID.Yield = 53; - TokenID._map[54] = "Semicolon"; - TokenID.Semicolon = 54; - TokenID._map[55] = "OpenParen"; - TokenID.OpenParen = 55; - TokenID._map[56] = "CloseParen"; - TokenID.CloseParen = 56; - TokenID._map[57] = "OpenBracket"; - TokenID.OpenBracket = 57; - TokenID._map[58] = "CloseBracket"; - TokenID.CloseBracket = 58; - TokenID._map[59] = "OpenBrace"; - TokenID.OpenBrace = 59; - TokenID._map[60] = "CloseBrace"; - TokenID.CloseBrace = 60; - TokenID._map[61] = "Comma"; - TokenID.Comma = 61; - TokenID._map[62] = "Equals"; - TokenID.Equals = 62; - TokenID._map[63] = "PlusEquals"; - TokenID.PlusEquals = 63; - TokenID._map[64] = "MinusEquals"; - TokenID.MinusEquals = 64; - TokenID._map[65] = "AsteriskEquals"; - TokenID.AsteriskEquals = 65; - TokenID._map[66] = "SlashEquals"; - TokenID.SlashEquals = 66; - TokenID._map[67] = "PercentEquals"; - TokenID.PercentEquals = 67; - TokenID._map[68] = "AmpersandEquals"; - TokenID.AmpersandEquals = 68; - TokenID._map[69] = "CaretEquals"; - TokenID.CaretEquals = 69; - TokenID._map[70] = "BarEquals"; - TokenID.BarEquals = 70; - TokenID._map[71] = "LessThanLessThanEquals"; - TokenID.LessThanLessThanEquals = 71; - TokenID._map[72] = "GreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanEquals = 72; - TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; - TokenID._map[74] = "Question"; - TokenID.Question = 74; - TokenID._map[75] = "Colon"; - TokenID.Colon = 75; - TokenID._map[76] = "BarBar"; - TokenID.BarBar = 76; - TokenID._map[77] = "AmpersandAmpersand"; - TokenID.AmpersandAmpersand = 77; - TokenID._map[78] = "Bar"; - TokenID.Bar = 78; - TokenID._map[79] = "Caret"; - TokenID.Caret = 79; - TokenID._map[80] = "And"; - TokenID.And = 80; - TokenID._map[81] = "EqualsEquals"; - TokenID.EqualsEquals = 81; - TokenID._map[82] = "ExclamationEquals"; - TokenID.ExclamationEquals = 82; - TokenID._map[83] = "EqualsEqualsEquals"; - TokenID.EqualsEqualsEquals = 83; - TokenID._map[84] = "ExclamationEqualsEquals"; - TokenID.ExclamationEqualsEquals = 84; - TokenID._map[85] = "LessThan"; - TokenID.LessThan = 85; - TokenID._map[86] = "LessThanEquals"; - TokenID.LessThanEquals = 86; - TokenID._map[87] = "GreaterThan"; - TokenID.GreaterThan = 87; - TokenID._map[88] = "GreaterThanEquals"; - TokenID.GreaterThanEquals = 88; - TokenID._map[89] = "LessThanLessThan"; - TokenID.LessThanLessThan = 89; - TokenID._map[90] = "GreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThan = 90; - TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThanGreaterThan = 91; - TokenID._map[92] = "Plus"; - TokenID.Plus = 92; - TokenID._map[93] = "Minus"; - TokenID.Minus = 93; - TokenID._map[94] = "Asterisk"; - TokenID.Asterisk = 94; - TokenID._map[95] = "Slash"; - TokenID.Slash = 95; - TokenID._map[96] = "Percent"; - TokenID.Percent = 96; - TokenID._map[97] = "Tilde"; - TokenID.Tilde = 97; - TokenID._map[98] = "Exclamation"; - TokenID.Exclamation = 98; - TokenID._map[99] = "PlusPlus"; - TokenID.PlusPlus = 99; - TokenID._map[100] = "MinusMinus"; - TokenID.MinusMinus = 100; - TokenID._map[101] = "Dot"; - TokenID.Dot = 101; - TokenID._map[102] = "DotDotDot"; - TokenID.DotDotDot = 102; - TokenID._map[103] = "Error"; - TokenID.Error = 103; - TokenID._map[104] = "EndOfFile"; - TokenID.EndOfFile = 104; - TokenID._map[105] = "EqualsGreaterThan"; - TokenID.EqualsGreaterThan = 105; - TokenID._map[106] = "Identifier"; - TokenID.Identifier = 106; - TokenID._map[107] = "StringLiteral"; - TokenID.StringLiteral = 107; - TokenID._map[108] = "RegularExpressionLiteral"; - TokenID.RegularExpressionLiteral = 108; - TokenID._map[109] = "NumberLiteral"; - TokenID.NumberLiteral = 109; - TokenID._map[110] = "Whitespace"; - TokenID.Whitespace = 110; - TokenID._map[111] = "Comment"; - TokenID.Comment = 111; - TokenID._map[112] = "Lim"; - TokenID.Lim = 112; - TokenID.LimFixed = TokenID.EqualsGreaterThan; - TokenID.LimKeyword = TokenID.Yield; - })(TypeScript.TokenID || (TypeScript.TokenID = {})); - var TokenID = TypeScript.TokenID; - TypeScript.tokenTable = new Array(); - TypeScript.nodeTypeTable = new Array(); - TypeScript.nodeTypeToTokTable = new Array(); - TypeScript.noRegexTable = new Array(); - TypeScript.noRegexTable[TokenID.Identifier] = true; - TypeScript.noRegexTable[TokenID.StringLiteral] = true; - TypeScript.noRegexTable[TokenID.NumberLiteral] = true; - TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; - TypeScript.noRegexTable[TokenID.This] = true; - TypeScript.noRegexTable[TokenID.PlusPlus] = true; - TypeScript.noRegexTable[TokenID.MinusMinus] = true; - TypeScript.noRegexTable[TokenID.CloseParen] = true; - TypeScript.noRegexTable[TokenID.CloseBracket] = true; - TypeScript.noRegexTable[TokenID.CloseBrace] = true; - TypeScript.noRegexTable[TokenID.True] = true; - TypeScript.noRegexTable[TokenID.False] = true; - (function (OperatorPrecedence) { - OperatorPrecedence._map = []; - OperatorPrecedence._map[0] = "None"; - OperatorPrecedence.None = 0; - OperatorPrecedence._map[1] = "Comma"; - OperatorPrecedence.Comma = 1; - OperatorPrecedence._map[2] = "Assignment"; - OperatorPrecedence.Assignment = 2; - OperatorPrecedence._map[3] = "Conditional"; - OperatorPrecedence.Conditional = 3; - OperatorPrecedence._map[4] = "LogicalOr"; - OperatorPrecedence.LogicalOr = 4; - OperatorPrecedence._map[5] = "LogicalAnd"; - OperatorPrecedence.LogicalAnd = 5; - OperatorPrecedence._map[6] = "BitwiseOr"; - OperatorPrecedence.BitwiseOr = 6; - OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; - OperatorPrecedence.BitwiseExclusiveOr = 7; - OperatorPrecedence._map[8] = "BitwiseAnd"; - OperatorPrecedence.BitwiseAnd = 8; - OperatorPrecedence._map[9] = "Equality"; - OperatorPrecedence.Equality = 9; - OperatorPrecedence._map[10] = "Relational"; - OperatorPrecedence.Relational = 10; - OperatorPrecedence._map[11] = "Shift"; - OperatorPrecedence.Shift = 11; - OperatorPrecedence._map[12] = "Additive"; - OperatorPrecedence.Additive = 12; - OperatorPrecedence._map[13] = "Multiplicative"; - OperatorPrecedence.Multiplicative = 13; - OperatorPrecedence._map[14] = "Unary"; - OperatorPrecedence.Unary = 14; - OperatorPrecedence._map[15] = "Lim"; - OperatorPrecedence.Lim = 15; - })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); - var OperatorPrecedence = TypeScript.OperatorPrecedence; - (function (Reservation) { - Reservation._map = []; - Reservation.None = 0; - Reservation.Javascript = 1; - Reservation.JavascriptFuture = 2; - Reservation.TypeScript = 4; - Reservation.JavascriptFutureStrict = 8; - Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; - Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; - Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; - })(TypeScript.Reservation || (TypeScript.Reservation = {})); - var Reservation = TypeScript.Reservation; - var TokenInfo = (function () { - function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - this.tokenId = tokenId; - this.reservation = reservation; - this.binopPrecedence = binopPrecedence; - this.binopNodeType = binopNodeType; - this.unopPrecedence = unopPrecedence; - this.unopNodeType = unopNodeType; - this.text = text; - this.ers = ers; - } - return TokenInfo; - })(); - TypeScript.TokenInfo = TokenInfo; - function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - if(tokenId !== undefined) { - TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); - if(binopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[binopNodeType] = text; - TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; - } - if(unopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[unopNodeType] = text; - } - } - } - setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); - setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); - setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); - setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); - setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); - setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); - setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); - setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); - setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); - setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); - setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); - setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); - setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); - setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); - setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); - setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); - setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); - function lookupToken(tokenId) { - return TypeScript.tokenTable[tokenId]; - } - TypeScript.lookupToken = lookupToken; - (function (TokenClass) { - TokenClass._map = []; - TokenClass._map[0] = "Punctuation"; - TokenClass.Punctuation = 0; - TokenClass._map[1] = "Keyword"; - TokenClass.Keyword = 1; - TokenClass._map[2] = "Operator"; - TokenClass.Operator = 2; - TokenClass._map[3] = "Comment"; - TokenClass.Comment = 3; - TokenClass._map[4] = "Whitespace"; - TokenClass.Whitespace = 4; - TokenClass._map[5] = "Identifier"; - TokenClass.Identifier = 5; - TokenClass._map[6] = "NumberLiteral"; - TokenClass.NumberLiteral = 6; - TokenClass._map[7] = "StringLiteral"; - TokenClass.StringLiteral = 7; - TokenClass._map[8] = "RegExpLiteral"; - TokenClass.RegExpLiteral = 8; - })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); - var TokenClass = TypeScript.TokenClass; - var SavedToken = (function () { - function SavedToken(tok, minChar, limChar) { - this.tok = tok; - this.minChar = minChar; - this.limChar = limChar; - } - return SavedToken; - })(); - TypeScript.SavedToken = SavedToken; - var Token = (function () { - function Token(tokenId) { - this.tokenId = tokenId; - } - Token.prototype.toString = function () { - return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; - }; - Token.prototype.print = function (line, outfile) { - outfile.WriteLine(this.toString() + ",on line" + line); - }; - Token.prototype.getText = function () { - return TypeScript.tokenTable[this.tokenId].text; - }; - Token.prototype.classification = function () { - if(this.tokenId <= TokenID.LimKeyword) { - return TokenClass.Keyword; - } else { - var tokenInfo = lookupToken(this.tokenId); - if(tokenInfo != undefined) { - if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { - return TokenClass.Operator; - } - } - } - return TokenClass.Punctuation; - }; - return Token; - })(); - TypeScript.Token = Token; - var NumberLiteralToken = (function (_super) { - __extends(NumberLiteralToken, _super); - function NumberLiteralToken(value, text) { - _super.call(this, TokenID.NumberLiteral); - this.value = value; - this.text = text; - } - NumberLiteralToken.prototype.getText = function () { - return this.text; - }; - NumberLiteralToken.prototype.classification = function () { - return TokenClass.NumberLiteral; - }; - return NumberLiteralToken; - })(Token); - TypeScript.NumberLiteralToken = NumberLiteralToken; - var StringLiteralToken = (function (_super) { - __extends(StringLiteralToken, _super); - function StringLiteralToken(value) { - _super.call(this, TokenID.StringLiteral); - this.value = value; - } - StringLiteralToken.prototype.getText = function () { - return this.value; - }; - StringLiteralToken.prototype.classification = function () { - return TokenClass.StringLiteral; - }; - return StringLiteralToken; - })(Token); - TypeScript.StringLiteralToken = StringLiteralToken; - var IdentifierToken = (function (_super) { - __extends(IdentifierToken, _super); - function IdentifierToken(value, hasEscapeSequence) { - _super.call(this, TokenID.Identifier); - this.value = value; - this.hasEscapeSequence = hasEscapeSequence; - } - IdentifierToken.prototype.getText = function () { - return this.value; - }; - IdentifierToken.prototype.classification = function () { - return TokenClass.Identifier; - }; - return IdentifierToken; - })(Token); - TypeScript.IdentifierToken = IdentifierToken; - var WhitespaceToken = (function (_super) { - __extends(WhitespaceToken, _super); - function WhitespaceToken(tokenId, value) { - _super.call(this, tokenId); - this.value = value; - } - WhitespaceToken.prototype.getText = function () { - return this.value; - }; - WhitespaceToken.prototype.classification = function () { - return TokenClass.Whitespace; - }; - return WhitespaceToken; - })(Token); - TypeScript.WhitespaceToken = WhitespaceToken; - var CommentToken = (function (_super) { - __extends(CommentToken, _super); - function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { - _super.call(this, tokenID); - this.value = value; - this.isBlock = isBlock; - this.startPos = startPos; - this.line = line; - this.endsLine = endsLine; - } - CommentToken.prototype.getText = function () { - return this.value; - }; - CommentToken.prototype.classification = function () { - return TokenClass.Comment; - }; - return CommentToken; - })(Token); - TypeScript.CommentToken = CommentToken; - var RegularExpressionLiteralToken = (function (_super) { - __extends(RegularExpressionLiteralToken, _super); - function RegularExpressionLiteralToken(text) { - _super.call(this, TokenID.RegularExpressionLiteral); - this.text = text; - } - RegularExpressionLiteralToken.prototype.getText = function () { - return this.text; - }; - RegularExpressionLiteralToken.prototype.classification = function () { - return TokenClass.RegExpLiteral; - }; - return RegularExpressionLiteralToken; - })(Token); - TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; - TypeScript.staticTokens = new Array(); - function initializeStaticTokens() { - for(var i = 0; i <= TokenID.LimFixed; i++) { - TypeScript.staticTokens[i] = new Token(i); - } - } - TypeScript.initializeStaticTokens = initializeStaticTokens; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ArrayCache = (function () { - function ArrayCache() { - this.arrayBase = null; - } - ArrayCache.prototype.specialize = function (arrInstType, checker) { - if(this.arrayBase == null) { - this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); - } - return this.arrayBase; - }; - return ArrayCache; - })(); - TypeScript.ArrayCache = ArrayCache; - var TypeComparisonInfo = (function () { - function TypeComparisonInfo() { - this.onlyCaptureFirstError = false; - this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; - this.message = ""; - } - TypeComparisonInfo.prototype.addMessageToFront = function (message) { - if(!this.onlyCaptureFirstError) { - this.message = this.message ? message + ":\n\t" + this.message : message; - } else { - this.setMessage(message); - } - }; - TypeComparisonInfo.prototype.setMessage = function (message) { - this.message = message; - }; - return TypeComparisonInfo; - })(); - TypeScript.TypeComparisonInfo = TypeComparisonInfo; - (function (TypeCheckCollectionMode) { - TypeCheckCollectionMode._map = []; - TypeCheckCollectionMode._map[0] = "Resident"; - TypeCheckCollectionMode.Resident = 0; - TypeCheckCollectionMode._map[1] = "Transient"; - TypeCheckCollectionMode.Transient = 1; - })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); - var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; - var PersistentGlobalTypeState = (function () { - function PersistentGlobalTypeState(errorReporter) { - this.errorReporter = errorReporter; - this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.globals = null; - this.globalTypes = null; - this.ambientGlobals = null; - this.ambientGlobalTypes = null; - this.residentGlobalValues = new TypeScript.StringHashTable(); - this.residentGlobalTypes = new TypeScript.StringHashTable(); - this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); - this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); - this.residentTypeCheck = true; - this.mod = null; - this.gloMod = null; - this.wildElm = null; - this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); - this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); - this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); - this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); - this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); - var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); - this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); - this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); - this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); - this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); - this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); - this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); - this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); - this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); - this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); - this.setCollectionMode(TypeCheckCollectionMode.Resident); - this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); - this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); - this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); - this.mod.members = dualGlobalScopedMembers; - this.mod.ambientMembers = dualGlobalScopedAmbientMembers; - this.mod.containedScope = this.globalScope; - this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); - this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); - this.defineGlobalValue("undefined", this.undefinedType); - } - PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { - var primitive = new TypeScript.Type(); - primitive.primitiveTypeClass = flags; - var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); - symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - primitive.symbol = symbol; - this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); - return primitive; - }; - PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { - this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; - }; - PersistentGlobalTypeState.prototype.refreshPersistentState = function () { - this.globals = new TypeScript.StringHashTable(); - this.globalTypes = new TypeScript.StringHashTable(); - this.ambientGlobals = new TypeScript.StringHashTable(); - this.ambientGlobalTypes = new TypeScript.StringHashTable(); - this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); - this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); - this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); - this.globalTypes.add("number", this.doubleType.symbol); - this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); - this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); - this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); - this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); - this.dualGlobalValues.secondaryTable = this.globals; - this.dualGlobalTypes.secondaryTable = this.globalTypes; - this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; - this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; - }; - PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { - var valueLocation = new TypeScript.ValueLocation(); - valueLocation.typeLink = new TypeScript.TypeLink(); - var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); - sym.setType(type); - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - sym.container = this.gloMod; - this.importedGlobalsTable.addPublicMember(name, sym); - }; - return PersistentGlobalTypeState; - })(); - TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; - var ContextualTypeContext = (function () { - function ContextualTypeContext(contextualType, provisional, contextID) { - this.contextualType = contextualType; - this.provisional = provisional; - this.contextID = contextID; - this.targetSig = null; - this.targetThis = null; - this.targetAccessorType = null; - } - return ContextualTypeContext; - })(); - TypeScript.ContextualTypeContext = ContextualTypeContext; - var ContextualTypingContextStack = (function () { - function ContextualTypingContextStack(checker) { - this.checker = checker; - this.contextStack = []; - this.hadProvisionalErrors = false; - } - ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; - ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { - this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); - this.checker.errorReporter.pushToErrorSink = provisional; - }; - ContextualTypingContextStack.prototype.popContextualType = function () { - var tc = this.contextStack.pop(); - this.checker.errorReporter.pushToErrorSink = this.isProvisional(); - this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); - this.checker.errorReporter.freeCapturedErrors(); - return tc; - }; - ContextualTypingContextStack.prototype.getContextualType = function () { - return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); - }; - ContextualTypingContextStack.prototype.getContextID = function () { - return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); - }; - ContextualTypingContextStack.prototype.isProvisional = function () { - return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); - }; - return ContextualTypingContextStack; - })(); - TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; - var TypeChecker = (function () { - function TypeChecker(persistentState) { - this.persistentState = persistentState; - this.errorReporter = null; - this.checkControlFlow = false; - this.printControlFlowGraph = false; - this.checkControlFlowUseDef = false; - this.styleSettings = null; - this.units = null; - this.anon = "_anonymous"; - this.locationInfo = null; - this.typeFlow = null; - this.currentCompareA = null; - this.currentCompareB = null; - this.currentModDecl = null; - this.inBind = false; - this.inWith = false; - this.errorsOnWith = true; - this.currentContextualTypeContext = null; - this.resolvingBases = false; - this.canCallDefinitionSignature = false; - this.assignableCache = { - }; - this.subtypeCache = { - }; - this.identicalCache = { - }; - this.provisionalStartedTypecheckObjects = []; - this.mustCaptureGlobalThis = false; - this.voidType = this.persistentState.voidType; - this.booleanType = this.persistentState.booleanType; - this.numberType = this.persistentState.doubleType; - this.stringType = this.persistentState.stringType; - this.anyType = this.persistentState.anyType; - this.nullType = this.persistentState.nullType; - this.undefinedType = this.persistentState.undefinedType; - this.globals = this.persistentState.dualGlobalValues; - this.globalTypes = this.persistentState.dualGlobalTypes; - this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; - this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; - this.gloModType = this.persistentState.mod; - this.gloMod = this.persistentState.gloMod; - this.wildElm = this.persistentState.wildElm; - this.globalScope = this.persistentState.globalScope; - this.typingContextStack = new ContextualTypingContextStack(this); - } - TypeChecker.prototype.setStyleOptions = function (style) { - this.styleSettings = style; - }; - TypeChecker.prototype.setContextualType = function (type, provisional) { - this.typingContextStack.pushContextualType(type, provisional); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.unsetContextualType = function () { - var lastTC = this.typingContextStack.popContextualType(); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - return lastTC; - }; - TypeChecker.prototype.hadProvisionalErrors = function () { - return this.typingContextStack.hadProvisionalErrors; - }; - TypeChecker.prototype.resetProvisionalErrors = function () { - if(!this.typingContextStack.getContextualType()) { - this.typingContextStack.hadProvisionalErrors = false; - } - }; - TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { - if(condition) { - this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); - } - this.typeFlow.typeCheck(ast); - if(condition) { - this.unsetContextualType(); - } - }; - TypeChecker.prototype.resetTargetType = function () { - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.killCurrentContextualType = function () { - this.currentContextualTypeContext = null; - this.errorReporter.pushToErrorSink = false; - }; - TypeChecker.prototype.hasTargetType = function () { - return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; - }; - TypeChecker.prototype.getTargetTypeContext = function () { - return this.currentContextualTypeContext; - }; - TypeChecker.prototype.inProvisionalTypecheckMode = function () { - return this.typingContextStack.isProvisional(); - }; - TypeChecker.prototype.getTypeCheckFinishedStatus = function () { - if(this.inProvisionalTypecheckMode()) { - return this.typingContextStack.getContextID(); - } - return TypeScript.TypeCheckStatus.Finished; - }; - TypeChecker.prototype.typeStatusIsFinished = function (status) { - return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); - }; - TypeChecker.prototype.addStartedPTO = function (pto) { - if(this.inProvisionalTypecheckMode()) { - this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; - } - }; - TypeChecker.prototype.cleanStartedPTO = function () { - for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { - if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { - this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - } - } - this.provisionalStartedTypecheckObjects = []; - }; - TypeChecker.prototype.collectTypes = function (ast) { - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - this.locationInfo = script.locationInfo; - } - var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); - var context = new TypeScript.TypeCollectionContext(globalChain, this); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); - }; - TypeChecker.prototype.makeArrayType = function (type) { - if(type.arrayCache == null) { - type.arrayCache = new ArrayCache(); - type.arrayCache.arrayType = new TypeScript.Type(); - type.arrayCache.arrayType.elementType = type; - type.arrayCache.arrayType.symbol = type.symbol; - } - return type.arrayCache.arrayType; - }; - TypeChecker.prototype.getParameterList = function (funcDecl, container) { - var args = funcDecl.arguments; - var parameterTable = null; - var parameterBuilder = null; - var len = args.members.length; - var nonOptionalParams = 0; - var result = []; - if(len > 0) { - parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); - for(var i = 0; i < len; i++) { - var parameter = args.members[i]; - var paramDef = new TypeScript.ValueLocation(); - var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); - parameterSymbol.declAST = parameter; - parameterSymbol.funcDecl = funcDecl; - parameter.id.sym = parameterSymbol; - parameter.sym = parameterSymbol; - paramDef.symbol = parameterSymbol; - paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); - parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); - result[result.length] = parameterSymbol; - if(!parameter.isOptionalArg()) { - nonOptionalParams++; - } - } - } - return { - parameters: result, - nonOptionalParameterCount: nonOptionalParams - }; - }; - TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isDefinition = !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature); - var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var isGlobal = container == this.gloMod; - var signature = new TypeScript.Signature(); - var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; - if(funcDecl.returnTypeAnnotation || isDefinition) { - signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); - } else { - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = this.anyType; - } - signature.hasVariableArgList = funcDecl.variableArgList; - var sigData = this.getParameterList(funcDecl, container); - signature.parameters = sigData.parameters; - signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; - funcDecl.signature = signature; - signature.declAST = funcDecl; - var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); - if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); - } - var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); - if(isConstructor) { - if(groupType.construct == null) { - groupType.construct = new TypeScript.SignatureGroup(); - } - groupType.construct.addSignature(signature); - groupType.construct.hasImplementation = !(funcDecl.isSignature()); - if(groupType.construct.hasImplementation) { - groupType.setHasImplementation(); - } - } else if(funcDecl.isIndexerMember()) { - if(groupType.index == null) { - groupType.index = new TypeScript.SignatureGroup(); - groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; - } - groupType.index.addSignature(signature); - groupType.index.hasImplementation = !(funcDecl.isSignature()); - if(groupType.index.hasImplementation) { - groupType.setHasImplementation(); - } - } else { - if(groupType.call == null) { - groupType.call = new TypeScript.SignatureGroup(); - } - groupType.call.addSignature(signature); - groupType.call.hasImplementation = !(funcDecl.isSignature()); - if(groupType.call.hasImplementation) { - groupType.setHasImplementation(); - } - } - var instanceType = groupType.instanceType; - var funcName = null; - var usedHint = false; - if(funcDecl.name && !funcDecl.name.isMissing()) { - funcName = funcDecl.name.text; - } else if(funcDecl.hint) { - funcName = funcDecl.hint; - usedHint = true; - } - if(groupType.symbol == null) { - groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); - if(!useOverloadGroupSym) { - groupType.symbol.declAST = funcDecl; - } - } - if(isStatic) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Static; - } - if(isAmbient) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; - } - if(isPrivate) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Private; - } - groupType.symbol.isMethod = funcDecl.isMethod(); - if(groupType.symbol.isMethod) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Property; - } - funcDecl.type = groupType; - if(!isConstructor) { - if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { - if(addToScope) { - if(funcDecl.isMethod() && isStatic) { - if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { - this.errorReporter.duplicateIdentifier(funcDecl, funcName); - } - groupType.symbol.container = container; - } else if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { - scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); - } - } else if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } else if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } - if(useOverloadGroupSym) { - var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; - var classType = groupType; - if(classType != overloadGroupType) { - if(classType.construct == null) { - if(overloadGroupType && overloadGroupType.construct) { - classType.construct = overloadGroupType.construct; - } else { - classType.construct = new TypeScript.SignatureGroup(); - } - } else if(overloadGroupType) { - if(overloadGroupType.construct) { - classType.construct.signatures.concat(overloadGroupType.construct.signatures); - } - } - if(overloadGroupType) { - if(classType.call == null) { - classType.call = overloadGroupType.call; - } else if(overloadGroupType.call) { - classType.call.signatures.concat(overloadGroupType.call.signatures); - } - if(!isStatic) { - if(classType.instanceType == null) { - classType.instanceType = overloadGroupType.instanceType; - } - var instanceType = classType.instanceType; - if(instanceType) { - if(instanceType.call == null) { - instanceType.call = overloadGroupType.call; - } else if(overloadGroupType.call) { - instanceType.call.signatures.concat(overloadGroupType.call.signatures); - } - } - } - if(classType.index == null) { - classType.index = overloadGroupType.index; - } else if(overloadGroupType.index) { - classType.index.signatures.concat(overloadGroupType.index.signatures); - } - } - } - } - return signature; - }; - TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { - var accessorSym = null; - var sig = funcDecl.signature; - var nameText = funcDecl.name.text; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - if(fgSym == null) { - var field = new TypeScript.ValueLocation(); - accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); - field.symbol = accessorSym; - accessorSym.declAST = funcDecl; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = sig.declAST.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = sig.declAST.type.symbol; - } - field.typeLink = TypeScript.getTypeLink(null, this, false); - if(addToMembers) { - if(enclosingClass) { - if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { - this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); - } - accessorSym.container = enclosingClass.symbol; - } else { - this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); - } - } else { - scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); - } - if(isClassProperty) { - accessorSym.flags |= TypeScript.SymbolFlags.Property; - } - if(isStatic) { - accessorSym.flags |= TypeScript.SymbolFlags.Static; - } - if(isPrivate) { - accessorSym.flags |= TypeScript.SymbolFlags.Private; - } else { - accessorSym.flags |= TypeScript.SymbolFlags.Public; - } - } else { - accessorSym = (fgSym); - if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = funcDecl.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = funcDecl.type.symbol; - } - } - return accessorSym; - }; - TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { - resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); - var i = 0; - var parent; - if(type.extendsList) { - for(var len = type.extendsList.length; i < len; i++) { - parent = type.extendsList[i]; - if(baseContext.baseId == parent.typeID) { - this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); - parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - break; - } - this.addBases(resultScope, parent, baseContext); - } - } - }; - TypeChecker.prototype.scopeOf = function (type) { - var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); - var baseContext = { - base: type.symbol && type.symbol.name ? type.symbol.name : "{}", - baseId: type.typeID - }; - this.addBases(resultScope, type, baseContext); - return resultScope; - }; - TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { - var symbol = null; - if(containingType.containedScope) { - symbol = containingType.containedScope.find(name, false, true); - } else if(containingType.members) { - symbol = containingType.members.allMembers.lookup(name); - if(symbol == null && containingType.ambientMembers) { - symbol = containingType.ambientMembers.allMembers.lookup(name); - } - } - if(symbol == null || !symbol.isType()) { - var typeMembers = containingType.getAllEnclosedTypes(); - var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); - if(typeMembers) { - symbol = typeMembers.allMembers.lookup(name); - if(symbol == null && ambientTypeMembers) { - symbol = ambientTypeMembers.allMembers.lookup(name); - } - } - } - if(symbol && symbol.isType()) { - return symbol; - } else { - return null; - } - }; - TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { - var originalIdText = idText; - var symbol = search(idText); - if(symbol == null) { - if(!symbol) { - idText = TypeScript.swapQuotes(originalIdText); - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".str"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; - symbol = search(idText); - } - if(!symbol && !TypeScript.isRelative(originalIdText)) { - idText = originalIdText; - var strippedIdText = TypeScript.stripQuotes(idText); - var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); - while(symbol == null && path != "") { - idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); - symbol = search(idText); - if(symbol == null) { - idText = TypeScript.changePathToSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDTS(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - if(path === '/') { - path = ''; - } else { - path = TypeScript.normalizePath(path + ".."); - path = path && path != '/' ? path + '/' : path; - } - } - } - } - } - return symbol; - }; - TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { - var lhs = dotNode.operand1; - var rhs = dotNode.operand2; - var resultType = this.anyType; - var lhsType = this.anyType; - if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { - if(lhs.nodeType == TypeScript.NodeType.Dot) { - lhsType = this.resolveTypeMember(scope, lhs); - } else if(lhs.nodeType == TypeScript.NodeType.Name) { - var identifier = lhs; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else if(symbol.isType()) { - var typeSymbol = symbol; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(TypeScript.optimizeModuleCodeGen && symbol) { - var symType = symbol.getType(); - if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; - } - } - } - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - lhsType = symbol.getType(); - identifier.sym = symbol; - } else { - this.errorReporter.simpleError(lhs, "Expected type"); - } - } - if(!lhsType) { - lhsType = this.anyType; - } - if(lhsType != this.anyType) { - var rhsIdentifier = rhs; - var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); - if(resultSymbol == null) { - resultType = this.anyType; - this.errorReporter.simpleError(dotNode, "Expected type"); - } else { - resultType = resultSymbol.getType(); - if(!resultSymbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); - } - } - rhsIdentifier.sym = resultType.symbol; - } - } - if(resultType.isClass()) { - resultType = resultType.instanceType; - } - return resultType; - }; - TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { - var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; - var signatures; - if(funcDecl.isConstructMember()) { - signatures = functionGroupSymbol.type.construct.signatures; - } else if(funcDecl.isIndexerMember()) { - signatures = functionGroupSymbol.type.getInstanceType().index.signatures; - } else { - signatures = functionGroupSymbol.type.call.signatures; - } - var signature = signatures[signatures.length - 1]; - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); - } - if(len && funcDecl.variableArgList) { - if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { - this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); - signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); - } - } - this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); - return functionGroupSymbol; - }; - TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = varDecl; - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); - this.resolveTypeLink(scope, field.typeLink, true); - varDecl.sym = fieldSymbol; - varDecl.type = field.typeLink.type; - return fieldSymbol; - }; - TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { - var arrayCount = 0; - if(typeLink.type == null) { - var ast = typeLink.ast; - if(ast) { - while(typeLink.type == null) { - switch(ast.nodeType) { - case TypeScript.NodeType.Name: - var identifier = ast; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - typeLink.type = this.anyType; - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else if(symbol.isType()) { - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - identifier.sym = symbol; - typeLink.type = symbol.getType(); - if(typeLink.type) { - if(typeLink.type.isClass()) { - typeLink.type = typeLink.type.instanceType; - } - } else { - typeLink.type = this.anyType; - } - } else { - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - } - break; - case TypeScript.NodeType.Dot: - typeLink.type = this.resolveTypeMember(scope, ast); - break; - case TypeScript.NodeType.TypeRef: - var typeRef = ast; - arrayCount = typeRef.arrayCount; - ast = typeRef.term; - if(ast == null) { - typeLink.type = this.anyType; - } - break; - case TypeScript.NodeType.InterfaceDeclaration: - var interfaceDecl = ast; - var interfaceType = new TypeScript.Type(); - var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); - interfaceType.containedScope.container = interfaceSymbol; - interfaceType.memberScope = interfaceType.containedScope; - var memberList = interfaceDecl.members; - var props = memberList.members; - var propsLen = props.length; - for(var j = 0; j < propsLen; j++) { - var propDecl = props[j]; - var propSym = null; - var addMember = true; - var id = null; - if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = propDecl; - id = funcDecl.name; - propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); - addMember = (propSym == null); - if(funcDecl.isSpecialFn()) { - addMember = false; - propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); - } else { - propSym = this.resolveFuncDecl(funcDecl, scope, propSym); - } - funcDecl.type = (propSym).type; - } else { - id = (propDecl).id; - propSym = this.resolveVarDecl(propDecl, scope); - addMember = !id.isMissing(); - } - if(addMember) { - if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { - propSym.flags |= TypeScript.SymbolFlags.Optional; - } - if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { - this.errorReporter.duplicateIdentifier(ast, propSym.name); - } - } - } - ast.type = interfaceType; - typeLink.type = interfaceType; - break; - case TypeScript.NodeType.FuncDecl: - var tsym = this.resolveFuncDecl(ast, scope, null); - typeLink.type = tsym.type; - break; - default: - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - break; - } - } - } - for(var count = arrayCount; count > 0; count--) { - typeLink.type = this.makeArrayType(typeLink.type); - } - if(supplyVar && (typeLink.type == null)) { - typeLink.type = this.anyType; - } - if(typeLink.ast) { - typeLink.ast.type = typeLink.type; - } - } - }; - TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { - this.resolvingBases = true; - this.resolveTypeLink(scope, typeLink, true); - this.resolvingBases = false; - var extendsType = null; - if(typeLink.type.isClass()) { - extendsType = typeLink.type.instanceType; - } else { - extendsType = typeLink.type; - } - return extendsType; - }; - TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { - if(signatures.length == 1) { - return { - sig: signatures[0].signature, - ambiguous: false - }; - } - var best = signatures[0]; - var Q = null; - var AType = null; - var PType = null; - var QType = null; - var ambiguous = false; - for(var qSig = 1; qSig < signatures.length; qSig++) { - Q = signatures[qSig]; - var i = 0; - for(i = 0; args && i < args.members.length; i++) { - AType = args.members[i].type; - PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; - QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; - if(this.typesAreIdentical(PType, QType)) { - continue; - } else if(this.typesAreIdentical(AType, PType)) { - break; - } else if(this.typesAreIdentical(AType, QType)) { - best = Q; - break; - } else if(this.sourceIsSubtypeOfTarget(PType, QType)) { - break; - } else if(this.sourceIsSubtypeOfTarget(QType, PType)) { - best = Q; - break; - } else if(Q.hadProvisionalErrors) { - break; - } else if(best.hadProvisionalErrors) { - best = Q; - break; - } - } - if(!args || i == args.members.length) { - var collection = { - getLength: function () { - return 2; - }, - setTypeAtIndex: function (index, type) { - }, - getTypeAtIndex: function (index) { - return index ? Q.signature.returnType.type : best.signature.returnType.type; - } - }; - var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); - ambiguous = !bct; - } else { - ambiguous = false; - } - } - return { - sig: best.signature, - ambiguous: ambiguous - }; - }; - TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { - var applicableSigs = []; - var memberType = null; - var miss = false; - var cxt = null; - var hadProvisionalErrors = false; - for(var i = 0; i < signatures.length; i++) { - miss = false; - for(var j = 0; j < args.members.length; j++) { - if(j >= signatures[i].parameters.length) { - continue; - } - memberType = signatures[i].parameters[j].getType(); - if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { - memberType = memberType.elementType; - } - if(memberType == this.anyType) { - continue; - } else if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { - if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { - continue; - } - if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { - if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { - this.typeFlow.typeCheck(args.members[j]); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - break; - } - } else { - break; - } - } else { - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } else if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { - if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } else if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { - if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - break; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } - if(j == args.members.length) { - applicableSigs[applicableSigs.length] = { - signature: signatures[i], - hadProvisionalErrors: hadProvisionalErrors - }; - } - hadProvisionalErrors = false; - } - return applicableSigs; - }; - TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { - if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { - return false; - } - beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); - if(!beStringent) { - return true; - } - if(!funcDecl.signature) { - this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); - this.typeFlow.typeCheck(funcDecl); - } - var signature = funcDecl.signature; - var paramLen = signature.parameters.length; - for(var i = 0; i < paramLen; i++) { - var param = signature.parameters[i]; - var symbol = param; - var argDecl = symbol.declAST; - if(beStringent && argDecl.typeExpr) { - return false; - } - } - if(candidateType.construct && candidateType.call) { - return false; - } - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - if(!candidateSigs || candidateSigs.signatures.length > 1) { - return false; - } - return true; - }; - TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { - if(targetType == this.typeFlow.objectInterfaceType) { - return true; - } - var memberDecls = objectLit.operand; - if(!(memberDecls && targetType.memberScope)) { - return false; - } - var id = null; - var targetMember = null; - var text = ""; - var foundSyms = { - }; - for(var i = 0; i < memberDecls.members.length; i++) { - id = (memberDecls.members[i]).operand1; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - return false; - } - targetMember = targetType.memberScope.find(text, true, false); - if(!targetMember) { - return false; - } - foundSyms[text] = true; - } - var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); - for(var i = 0; i < targetMembers.length; i++) { - var memberName = targetMembers[i]; - var memberSym = targetType.memberScope.find(memberName, true, false); - if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.widenType = function (t) { - if(t == this.undefinedType || t == this.nullType) { - return this.anyType; - } - return t; - }; - TypeChecker.prototype.isNullOrUndefinedType = function (t) { - return t == this.undefinedType || t == this.nullType; - }; - TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { - var i = 0; - var len = collection.getLength(); - var nlastChecked = 0; - var bestCommonType = initialType; - if(targetType) { - bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; - } - var convergenceType = bestCommonType; - while(nlastChecked < len) { - for(i = 0; i < len; i++) { - if(i == nlastChecked) { - continue; - } - if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { - convergenceType = bestCommonType; - } - if(bestCommonType == this.anyType || bestCommonType == null) { - break; - } else if(targetType) { - collection.setTypeAtIndex(i, targetType); - } - } - if(convergenceType && bestCommonType) { - break; - } - nlastChecked++; - if(nlastChecked < len) { - convergenceType = collection.getTypeAtIndex(nlastChecked); - } - } - return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); - }; - TypeChecker.prototype.typesAreIdentical = function (t1, t2) { - if(t1 == t2) { - return true; - } - if(!t1 || !t2) { - return false; - } - if(t1.isClass() || t1.isClassInstance()) { - return false; - } - var comboId = (t2.typeID << 16) | t1.typeID; - if(this.identicalCache[comboId]) { - return true; - } - if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(t1.isArray() || t2.isArray()) { - if(!(t1.isArray() && t2.isArray())) { - return false; - } - this.identicalCache[comboId] = false; - var ret = this.typesAreIdentical(t1.elementType, t2.elementType); - if(ret) { - this.subtypeCache[comboId] = true; - } else { - this.subtypeCache[comboId] = undefined; - } - return ret; - } - if(t1.primitiveTypeClass != t2.primitiveTypeClass) { - return false; - } - this.identicalCache[comboId] = false; - if(t1.memberScope && t2.memberScope) { - var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); - var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); - if(t1MemberKeys.length != t2MemberKeys.length) { - this.identicalCache[comboId] = undefined; - return false; - } - var t1MemberSymbol = null; - var t2MemberSymbol = null; - var t1MemberType = null; - var t2MemberType = null; - for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { - if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); - t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); - if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberType = t1MemberSymbol.getType(); - t2MemberType = t2MemberSymbol.getType(); - if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { - continue; - } - if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { - this.identicalCache[comboId] = undefined; - return false; - } - } - } else if(t1.memberScope || t2.memberScope) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { - this.identicalCache[comboId] = undefined; - return false; - } - this.identicalCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { - if(sg1 == sg2) { - return true; - } - if(!sg1 || !sg2) { - return false; - } - if(sg1.signatures.length != sg2.signatures.length) { - return false; - } - var sig1 = null; - var sig2 = null; - var sigsMatch = false; - for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { - sig1 = sg1.signatures[iSig1]; - for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { - sig2 = sg2.signatures[iSig2]; - if(this.signaturesAreIdentical(sig1, sig2)) { - sigsMatch = true; - break; - } - } - if(sigsMatch) { - sigsMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { - if(s1.hasVariableArgList != s2.hasVariableArgList) { - return false; - } - if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { - return false; - } - if(s1.parameters.length != s2.parameters.length) { - return false; - } - if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { - return false; - } - for(var iParam = 0; iParam < s1.parameters.length; iParam++) { - if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { - if(source == target) { - return true; - } - if(!(source && target)) { - return true; - } - var comboId = (source.typeID << 16) | target.typeID; - if(comparisonCache[comboId] != undefined) { - return true; - } - if(assignableTo) { - if(source == this.anyType || target == this.anyType) { - return true; - } - } else { - if(target == this.anyType) { - return true; - } - } - if(source == this.undefinedType) { - return true; - } - if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { - return true; - } - if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(source.isArray() || target.isArray()) { - if(!(source.isArray() && target.isArray())) { - return false; - } - comparisonCache[comboId] = false; - var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); - if(ret) { - comparisonCache[comboId] = true; - } else { - comparisonCache[comboId] = undefined; - } - return ret; - } - if(source.primitiveTypeClass != target.primitiveTypeClass) { - if(target.primitiveTypeClass == TypeScript.Primitive.None) { - if(source == this.numberType && this.typeFlow.numberInterfaceType) { - source = this.typeFlow.numberInterfaceType; - } else if(source == this.stringType && this.typeFlow.stringInterfaceType) { - source = this.typeFlow.stringInterfaceType; - } else if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { - source = this.typeFlow.booleanInterfaceType; - } else { - return false; - } - } else { - return false; - } - } - comparisonCache[comboId] = false; - if(source.hasBase(target)) { - comparisonCache[comboId] = true; - return true; - } - if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { - return true; - } - if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { - return true; - } - if(target.isClass() || target.isClassInstance()) { - comparisonCache[comboId] = undefined; - return false; - } - if(target.memberScope && source.memberScope) { - var mPropKeys = target.memberScope.getAllValueSymbolNames(true); - var mProp = null; - var nProp = null; - var mPropType = null; - var nPropType = null; - var inferenceSymbol = null; - for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { - mProp = target.memberScope.find(mPropKeys[iMProp], false, false); - nProp = source.memberScope.find(mPropKeys[iMProp], false, false); - if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { - continue; - } - if(mProp.isInferenceSymbol()) { - inferenceSymbol = mProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(mProp.declAST); - } - } - mPropType = mProp.getType(); - if(!nProp) { - if(this.typeFlow.objectInterfaceType) { - nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { - nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; - comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); - } - return false; - } else { - continue; - } - } - } - } - if(nProp.isInferenceSymbol()) { - inferenceSymbol = nProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(nProp.declAST); - } - } - nPropType = nProp.getType(); - if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { - continue; - } - if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; - comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } - return false; - } - } - } - if(source.call || target.call) { - if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.call && target.call) { - comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.call ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(source.construct || target.construct) { - if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.construct && target.construct) { - comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(target.index) { - var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; - var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; - if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - comparisonCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { - if(sourceSG == targetSG) { - return true; - } - if(!(sourceSG && targetSG)) { - return false; - } - var mSig = null; - var nSig = null; - var foundMatch = false; - for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { - mSig = targetSG.signatures[iMSig]; - for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { - nSig = sourceSG.signatures[iNSig]; - if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { - foundMatch = true; - break; - } - } - if(foundMatch) { - foundMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { - if(!sourceSig.parameters || !targetSig.parameters) { - return false; - } - var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; - var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; - if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; - comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); - } - return false; - } - var sourceReturnType = sourceSig.returnType.type; - var targetReturnType = targetSig.returnType.type; - if(targetReturnType != this.voidType) { - if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; - } - return false; - } - } - var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; - var sourceParamType = null; - var targetParamType = null; - var sourceParamName = ""; - var targetParamName = ""; - for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { - if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } else if(iSource == sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - if(sourceParamType.elementType) { - sourceParamType = sourceParamType.elementType; - } - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } - if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } else if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - if(targetParamType.elementType) { - targetParamType = targetParamType.elementType; - } - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } - if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; - } - return false; - } - } - return true; - }; - return TypeChecker; - })(); - TypeScript.TypeChecker = TypeChecker; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Continuation = (function () { - function Continuation(normalBlock) { - this.normalBlock = normalBlock; - this.exceptionBlock = -1; - } - return Continuation; - })(); - TypeScript.Continuation = Continuation; - function getBaseTypeLinks(bases, baseTypeLinks) { - if(bases) { - var len = bases.members.length; - if(baseTypeLinks == null) { - baseTypeLinks = new Array(); - } - for(var i = 0; i < len; i++) { - var baseExpr = bases.members[i]; - var name = baseExpr; - var typeLink = new TypeScript.TypeLink(); - typeLink.ast = name; - baseTypeLinks[baseTypeLinks.length] = typeLink; - } - } - return baseTypeLinks; - } - function getBases(type, typeDecl) { - type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); - type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); - } - function addPrototypeField(classType, ast, context) { - var field = new TypeScript.ValueLocation(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.ast = ast; - field.typeLink.type = classType.instanceType; - var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - classType.members.addPublicMember("prototype", fieldSymbol); - } - function createNewConstructGroupForType(type) { - var signature = new TypeScript.Signature(); - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = type.instanceType; - signature.parameters = []; - type.construct = new TypeScript.SignatureGroup(); - type.construct.addSignature(signature); - } - TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; - function cloneParentConstructGroupForChildType(child, parent) { - child.construct = new TypeScript.SignatureGroup(); - var sig = null; - if(!parent.construct) { - createNewConstructGroupForType(parent); - } - for(var i = 0; i < parent.construct.signatures.length; i++) { - sig = new TypeScript.Signature(); - sig.parameters = parent.construct.signatures[i].parameters; - sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; - sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; - sig.declAST = parent.construct.signatures[i].declAST; - sig.returnType = new TypeScript.TypeLink(); - sig.returnType.type = child.instanceType; - child.construct.addSignature(sig); - } - } - TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; - TypeScript.globalId = "__GLO"; - function findTypeSymbolInScopeChain(name, scopeChain) { - var symbol = scopeChain.scope.find(name, false, true); - if(symbol == null && scopeChain.previous) { - symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); - } - return symbol; - } - function findSymbolFromAlias(alias, context) { - var symbol = null; - switch(alias.nodeType) { - case TypeScript.NodeType.Name: - var name = (alias).text; - var isDynamic = TypeScript.isQuoted(name); - var findSym = function (id) { - if(context.members) { - return context.members.lookup(name); - } else { - return findTypeSymbolInScopeChain(name, context.topLevelScope); - } - }; - if(isDynamic) { - symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); - } else { - symbol = findSym(name); - } - break; - case TypeScript.NodeType.Dot: - var dottedExpr = alias; - var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); - if(op1Sym && op1Sym.getType()) { - symbol = findSymbolFromAlias(dottedExpr.operand2, context); - } - break; - default: - break; - } - if(symbol) { - var symType = symbol.getType(); - if(symType) { - var members = symType.members; - if(members) { - context.members = members.publicMembers; - } - } - } - return symbol; - } - function preCollectImportTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var typeSymbol = null; - var modType = null; - var importDecl = ast; - var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { - topLevelScope: scopeChain, - members: null, - tcContext: context - }); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - if(aliasedModSymbol) { - var aliasedModType = aliasedModSymbol.getType(); - if(aliasedModType) { - modType = aliasedModType; - } - } - typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); - typeSymbol.aliasLink = importDecl; - if(context.scopeChain.moduleDecl) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = importDecl; - importDecl.id.sym = typeSymbol; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); - return true; - } - TypeScript.preCollectImportTypes = preCollectImportTypes; - function preCollectModuleTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var moduleDecl = ast; - var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); - var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - var modName = (moduleDecl.name).text; - var isDynamic = TypeScript.isQuoted(modName); - var symbol = scopeChain.scope.findLocal(modName, false, false); - var typeSymbol = null; - var modType = null; - if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { - context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); - symbol = null; - modName = ""; - } - if(symbol) { - var modDeclAST = symbol.declAST; - var modDeclASTIsExported = TypeScript.hasFlag(modDeclAST.modFlags, TypeScript.ModuleFlags.Exported); - if((modDeclASTIsExported && !isExported) || (!modDeclASTIsExported && isExported)) { - context.checker.errorReporter.simpleError(moduleDecl, 'All contributions to a module must be "export" or none'); - } - } - if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { - if(modType == null) { - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.setHasImplementation(); - } - typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); - typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); - if(context.scopeChain.moduleDecl) { - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = moduleDecl; - typeSymbol.prettyName = moduleDecl.prettyName; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - modType.symbol = typeSymbol; - } else { - typeSymbol = symbol; - var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; - var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; - var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicMembers = typeSymbol.type.members.publicMembers; - var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); - var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; - var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = members; - modType.ambientMembers = ambientMembers; - modType.setHasImplementation(); - modType.symbol = typeSymbol; - typeSymbol.addLocation(moduleDecl.minChar); - typeSymbol.expansions.push(modType); - typeSymbol.expansionsDeclAST.push(moduleDecl); - } - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - moduleDecl.mod = modType; - TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); - return true; - } - TypeScript.preCollectModuleTypes = preCollectModuleTypes; - function preCollectClassTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var classDecl = ast; - var classType; - var instanceType; - var typeSymbol = null; - var className = (classDecl.name).text; - var alreadyInScope = false; - var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var containerMod = scopeChain.container; - var foundValSymbol = false; - typeSymbol = scopeChain.scope.findLocal(className, false, true); - if(!typeSymbol) { - var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); - if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { - typeSymbol = valTypeSymbol; - foundValSymbol = true; - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - } - } - if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { - typeSymbol = null; - } - if(typeSymbol == null) { - var valueSymbol = scopeChain.scope.findLocal(className, false, false); - classType = new TypeScript.Type(); - classType.setHasImplementation(); - instanceType = new TypeScript.Type(); - instanceType.setHasImplementation(); - classType.instanceType = instanceType; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - addPrototypeField(classType, classDecl, context); - instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); - typeSymbol.declAST = classDecl; - typeSymbol.instanceType = instanceType; - classType.symbol = typeSymbol; - instanceType.symbol = typeSymbol; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - typeSymbol.declModule = context.scopeChain.moduleDecl; - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - ast.type = classType; - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - if(valueSymbol == null) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - } - } else { - classType = typeSymbol.type; - if(classType.instanceType == null) { - classType.instanceType = new TypeScript.Type(); - classType.instanceType.setHasImplementation(); - classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.instanceType.symbol = classType.symbol; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - } - instanceType = classType.instanceType; - ast.type = classType; - } - if(!classDecl.constructorDecl) { - if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { - context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); - } - createNewConstructGroupForType(classDecl.type); - } - classType.typeFlags |= TypeScript.TypeFlags.IsClass; - instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; - getBases(instanceType, classDecl); - TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); - return true; - } - TypeScript.preCollectClassTypes = preCollectClassTypes; - function preCollectInterfaceTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var interfaceDecl = ast; - var interfaceSymbol = null; - var interfaceType = null; - var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var alreadyInScope = true; - alreadyInScope = false; - var interfaceName = (interfaceDecl.name).text; - interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); - if(interfaceSymbol == null) { - interfaceType = new TypeScript.Type(); - interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceSymbol.declAST = interfaceDecl; - interfaceSymbol.declModule = context.scopeChain.moduleDecl; - } else { - alreadyInScope = true; - interfaceType = interfaceSymbol.type; - } - if(!interfaceType) { - interfaceType = context.checker.anyType; - } - ast.type = interfaceType; - getBases(interfaceType, interfaceDecl); - if(isExported) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(context.scopeChain.moduleDecl) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(!alreadyInScope) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); - } - TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); - return true; - } - TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; - function preCollectArgDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var argDecl = ast; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { - var field = new TypeScript.ValueLocation(); - var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); - var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); - fieldSymbol.transferVarFlags(argDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - argDecl.parameterPropertySym = fieldSymbol; - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); - field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); - argDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; - function preCollectVarDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var varDecl = ast; - var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); - var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); - var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); - var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { - if(isAmbient) { - var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); - if(existingSym) { - varDecl.sym = existingSym; - return false; - } - } - if(varDecl.id == null) { - context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); - return false; - } - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - if(isOptional) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; - } - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - fieldSymbol.declModule = context.scopeChain.moduleDecl; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { - if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { - context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); - } - fieldSymbol.container = context.scopeChain.classType.symbol; - } else { - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); - varDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; - function preCollectFuncDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - var funcDecl = ast; - var fgSym = null; - var nameText = funcDecl.getNameText(); - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); - var containerScope = context.scopeChain.scope; - var isGlobal = containerSym == context.checker.gloMod; - var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); - var go = false; - var foundSymbol = false; - if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - containerSym = containerSym.container; - containerScope = scopeChain.previous.scope; - } - funcDecl.unitIndex = context.checker.locationInfo.unitIndex; - if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { - return go; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { - var instType = context.scopeChain.thisType; - if(nameText && nameText != "__missing") { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - fgSym = containerScope.findLocal(nameText, false, false); - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, true); - } - } - if(fgSym) { - foundSymbol = true; - if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { - fgSym = null; - } - } - } - if(fgSym == null) { - if(!(funcDecl.isSpecialFn())) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; - } else { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; - } - if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { - fgSym.declAST = ast; - } - } else { - if((fgSym.kind() == TypeScript.SymbolKind.Type)) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; - } else { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - } - } - if(funcDecl.isSpecialFn() && !isStatic) { - funcDecl.type = instType ? instType : fgSym.type; - } else { - funcDecl.type = fgSym.type; - } - } else { - if(nameText) { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - if(funcDecl.isConstructor && context.scopeChain.previous) { - fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); - } - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, false); - } - } - if(fgSym) { - foundSymbol = true; - if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { - fgSym = null; - foundSymbol = false; - } - } - } - if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); - } - if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - fgSym.type = context.checker.anyType; - } - if(fgSym && !fgSym.isAccessor() && funcDecl.isAccessor()) { - fgSym = null; - } - var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); - if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); - } - funcDecl.type.symbol.declAST = ast; - if(funcDecl.isConstructor) { - go = true; - } - ; - } - if(isExported) { - if(funcDecl.type.call) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { - fgSym.flags |= TypeScript.SymbolFlags.Exported; - } - } - if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; - funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; - } - if(fgSym && isOptional) { - fgSym.flags |= TypeScript.SymbolFlags.Optional; - } - return go; - } - TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; - function preCollectTypes(ast, parent, walker) { - var context = walker.state; - var go = false; - var scopeChain = context.scopeChain; - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - context.script = script; - go = true; - } else if(ast.nodeType == TypeScript.NodeType.List) { - go = true; - } else if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { - go = preCollectImportTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.With) { - go = false; - } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - go = preCollectModuleTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - go = preCollectClassTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.Block) { - go = true; - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - go = preCollectInterfaceTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - go = preCollectArgDeclTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.VarDecl) { - go = preCollectVarDeclTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - go = preCollectFuncDeclTypes(ast, parent, context); - } else { - if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preCollectTypes = preCollectTypes; - function postCollectTypes(ast, parent, walker) { - var context = walker.state; - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - TypeScript.popTypeCollectionScope(context); - } - return ast; - } - TypeScript.postCollectTypes = postCollectTypes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopeChain = (function () { - function ScopeChain(container, previous, scope) { - this.container = container; - this.previous = previous; - this.scope = scope; - } - return ScopeChain; - })(); - TypeScript.ScopeChain = ScopeChain; - var BBUseDefInfo = (function () { - function BBUseDefInfo(bb) { - this.bb = bb; - this.defsBySymbol = new Array(); - this.useIndexBySymbol = new Array(); - } - BBUseDefInfo.prototype.updateTop = function () { - var temp = new BitVector(this.top.bitCount); - for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { - var succ = this.bb.successors[i]; - if(succ.useDef) { - temp.union(succ.useDef.top); - } - } - temp.difference(this.kill); - temp.union(this.gen); - var changed = temp.notEq(this.top); - this.top = temp; - return changed; - }; - BBUseDefInfo.prototype.initialize = function (useDefContext) { - var _this = this; - var defSym = function (sym, context) { - if(context.isLocalSym(sym)) { - var index = context.getSymbolIndex(sym); - _this.useIndexBySymbol[index] = new Array(); - _this.defsBySymbol[index] = true; - } - }; - var useSym = function (sym, context, ast) { - if(context.isLocalSym(sym)) { - var symIndex = context.getSymbolIndex(sym); - if(_this.useIndexBySymbol[symIndex] == undefined) { - _this.useIndexBySymbol[symIndex] = new Array(); - } - var symUses = _this.useIndexBySymbol[symIndex]; - var astIndex = context.getUseIndex(ast); - context.addUse(symIndex, astIndex); - symUses.push(astIndex); - } - }; - function initUseDefPre(cur, parent, walker) { - var context = walker.state; - if(cur == null) { - cur = null; - } - if(cur.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = cur; - if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { - defSym(varDecl.sym, context); - } - } else if(cur.nodeType == TypeScript.NodeType.Name) { - if(parent) { - if(parent.nodeType == TypeScript.NodeType.Asg) { - var asg = parent; - if(asg.operand1 == cur) { - return cur; - } - } else if(parent.nodeType == TypeScript.NodeType.VarDecl) { - var parentDecl = parent; - if(parentDecl.id == cur) { - return cur; - } - } - } - var id = cur; - useSym(id.sym, context, cur); - } else if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { - var asg = cur; - if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { - var id = asg.operand1; - defSym(id.sym, context); - } - } else if(cur.nodeType == TypeScript.NodeType.FuncDecl) { - walker.options.goChildren = false; - } - return cur; - } - var options = new TypeScript.AstWalkOptions(); - options.reverseSiblings = true; - TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); - }; - BBUseDefInfo.prototype.initializeGen = function (useDefContext) { - var symbolLen = this.useIndexBySymbol.length; - var bitCount = useDefContext.uses.length; - this.gen = new BitVector(bitCount); - for(var s = 0; s < symbolLen; s++) { - var symUses = this.useIndexBySymbol[s]; - if((symUses != undefined) && (symUses.length > 0)) { - for(var u = 0, uLen = symUses.length; u < uLen; u++) { - this.gen.set(symUses[u], true); - } - } - } - this.top = this.gen; - }; - BBUseDefInfo.prototype.initializeKill = function (useDefContext) { - this.kill = new BitVector(this.gen.bitCount); - for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { - if(this.defsBySymbol[s]) { - var globalSymUses = useDefContext.useIndexBySymbol[s]; - if(globalSymUses) { - for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { - this.kill.set(globalSymUses[u], true); - } - } - } - } - }; - return BBUseDefInfo; - })(); - TypeScript.BBUseDefInfo = BBUseDefInfo; - var UseDefContext = (function () { - function UseDefContext() { - this.useIndexBySymbol = new Array(); - this.uses = new Array(); - this.symbols = new Array(); - this.symbolMap = new TypeScript.StringHashTable(); - this.symbolCount = 0; - } - UseDefContext.prototype.getSymbolIndex = function (sym) { - var name = sym.name; - var index = (this.symbolMap.lookup(name)); - if(index == null) { - index = this.symbolCount++; - this.symbols[index] = sym; - this.symbolMap.add(name, index); - } - return index; - }; - UseDefContext.prototype.addUse = function (symIndex, astIndex) { - var useBySym = this.useIndexBySymbol[symIndex]; - if(useBySym == undefined) { - useBySym = new Array(); - this.useIndexBySymbol[symIndex] = useBySym; - } - useBySym[useBySym.length] = astIndex; - }; - UseDefContext.prototype.getUseIndex = function (ast) { - this.uses[this.uses.length] = ast; - return this.uses.length - 1; - }; - UseDefContext.prototype.isLocalSym = function (sym) { - return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); - }; - UseDefContext.prototype.killSymbol = function (sym, bbUses) { - var index = this.symbolMap.lookup(sym.name); - var usesOfSym = this.useIndexBySymbol[index]; - for(var k = 0, len = usesOfSym.length; k < len; k++) { - bbUses.set(usesOfSym[k], true); - } - }; - return UseDefContext; - })(); - TypeScript.UseDefContext = UseDefContext; - var BitVector = (function () { - function BitVector(bitCount) { - this.bitCount = bitCount; - this.firstBits = 0; - this.restOfBits = null; - if(this.bitCount > BitVector.packBits) { - this.restOfBits = new Array(); - var len = Math.floor(this.bitCount / BitVector.packBits); - for(var i = 0; i < len; i++) { - this.restOfBits[i] = 0; - } - } - } - BitVector.packBits = 30; - BitVector.prototype.set = function (bitIndex, value) { - if(bitIndex < BitVector.packBits) { - if(value) { - this.firstBits |= (1 << bitIndex); - } else { - this.firstBits &= (~(1 << bitIndex)); - } - } else { - var offset = Math.floor(bitIndex / BitVector.packBits) - 1; - var localIndex = bitIndex % BitVector.packBits; - if(value) { - this.restOfBits[offset] |= (1 << localIndex); - } else { - this.restOfBits[offset] &= (~(1 << localIndex)); - } - } - }; - BitVector.prototype.map = function (fn) { - var k; - for(k = 0; k < BitVector.packBits; k++) { - if(k == this.bitCount) { - return; - } - if(((1 << k) & this.firstBits) != 0) { - fn(k); - } - } - if(this.restOfBits) { - var len; - var cumu = BitVector.packBits; - for(k = 0 , len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - for(var j = 0; j < BitVector.packBits; j++) { - if(((1 << j) & myBits) != 0) { - fn(cumu); - } - cumu++; - if(cumu == this.bitCount) { - return; - } - } - } - } - }; - BitVector.prototype.union = function (b) { - this.firstBits |= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits | bBits; - } - } - }; - BitVector.prototype.intersection = function (b) { - this.firstBits &= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits & bBits; - } - } - }; - BitVector.prototype.notEq = function (b) { - if(this.firstBits != b.firstBits) { - return true; - } - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - if(myBits != bBits) { - return true; - } - } - } - return false; - }; - BitVector.prototype.difference = function (b) { - var oldFirstBits = this.firstBits; - this.firstBits &= (~b.firstBits); - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] &= (~bBits); - } - } - }; - return BitVector; - })(); - TypeScript.BitVector = BitVector; - var BasicBlock = (function () { - function BasicBlock() { - this.predecessors = new Array(); - this.index = -1; - this.markValue = 0; - this.successors = new Array(); - this.useDef = null; - this.content = new TypeScript.ASTList(); - } - BasicBlock.prototype.marked = function (markBase) { - return this.markValue > markBase; - }; - BasicBlock.prototype.mark = function () { - this.markValue++; - }; - BasicBlock.prototype.addSuccessor = function (successor) { - this.successors[this.successors.length] = successor; - successor.predecessors[successor.predecessors.length] = this; - }; - return BasicBlock; - })(); - TypeScript.BasicBlock = BasicBlock; - var ControlFlowContext = (function () { - function ControlFlowContext(current, exit) { - this.current = current; - this.exit = exit; - this.entry = null; - this.unreachable = null; - this.noContinuation = false; - this.statementStack = new Array(); - this.currentSwitch = new Array(); - this.markBase = 0; - this.linearBBs = new Array(); - this.entry = this.current; - } - ControlFlowContext.prototype.walk = function (ast, parent) { - return this.walker.walk(ast, parent); - }; - ControlFlowContext.prototype.pushSwitch = function (bb) { - this.currentSwitch.push(bb); - }; - ControlFlowContext.prototype.popSwitch = function () { - return this.currentSwitch.pop(); - }; - ControlFlowContext.prototype.reportUnreachable = function (er) { - if(this.unreachable && (this.unreachable.length > 0)) { - var len = this.unreachable.length; - for(var i = 0; i < len; i++) { - var unreachableAST = this.unreachable[i]; - if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { - er.simpleError(unreachableAST, "unreachable code"); - } - } - } - }; - ControlFlowContext.prototype.printAST = function (ast, outfile) { - var printContext = new TypeScript.PrintContext(outfile, null); - printContext.increaseIndent(); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); - printContext.decreaseIndent(); - }; - ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { - var content = bb.content; - for(var i = 0, len = content.members.length; i < len; i++) { - var ast = content.members[i]; - this.printAST(ast, outfile); - } - }; - ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { - var markValue = this.markBase++; - var q = new Array(); - q[q.length] = this.entry; - while(q.length > 0) { - var bb = q.pop(); - if(!(bb.marked(markValue))) { - bb.mark(); - if(nodeFunc) { - nodeFunc(bb); - } - var succLen = bb.successors.length; - if(succLen > 0) { - if(preEdges) { - preEdges(); - } - for(var j = succLen - 1; j >= 0; j--) { - var successor = bb.successors[j]; - if(!(successor.marked(this.markBase))) { - if(edgeFunc) { - edgeFunc(bb, successor); - } - q[q.length] = successor; - } - } - if(postEdges) { - postEdges(); - } - } - } - } - }; - ControlFlowContext.prototype.useDef = function (er, funcSym) { - var _this = this; - var useDefContext = new UseDefContext(); - useDefContext.func = funcSym; - var useDefInit = function (bb) { - bb.useDef = new BBUseDefInfo(bb); - bb.useDef.initialize(useDefContext); - _this.linearBBs[_this.linearBBs.length] = bb; - }; - this.bfs(useDefInit, null, null, null); - var i, bbLen; - for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { - this.linearBBs[i].useDef.initializeGen(useDefContext); - this.linearBBs[i].useDef.initializeKill(useDefContext); - } - var changed = true; - while(changed) { - changed = false; - for(i = 0; i < bbLen; i++) { - changed = this.linearBBs[i].useDef.updateTop() || changed; - } - } - var top = this.entry.useDef.top; - top.map(function (index) { - var ast = useDefContext.uses[index]; - er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); - }); - }; - ControlFlowContext.prototype.print = function (outfile) { - var _this = this; - var index = 0; - var node = function (bb) { - if(bb.index < 0) { - bb.index = index++; - } - if(bb == _this.exit) { - outfile.WriteLine("Exit block with index " + bb.index); - } else { - outfile.WriteLine("Basic block with index " + bb.index); - _this.printBlockContent(bb, outfile); - } - }; - function preEdges() { - outfile.Write(" Branches to "); - } - function postEdges() { - outfile.WriteLine(""); - } - function edge(node1, node2) { - if(node2.index < 0) { - node2.index = index++; - } - outfile.Write(node2.index + " "); - } - this.bfs(node, edge, preEdges, postEdges); - if(this.unreachable != null) { - for(var i = 0, len = this.unreachable.length; i < len; i++) { - outfile.WriteLine("Unreachable basic block ..."); - this.printAST(this.unreachable[i], outfile); - } - } - }; - ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { - this.statementStack.push({ - stmt: stmt, - continueBB: continueBB, - breakBB: breakBB - }); - }; - ControlFlowContext.prototype.popStatement = function () { - return this.statementStack.pop(); - }; - ControlFlowContext.prototype.returnStmt = function () { - this.current.addSuccessor(this.exit); - this.setUnreachable(); - }; - ControlFlowContext.prototype.setUnreachable = function () { - this.current = null; - this.noContinuation = true; - }; - ControlFlowContext.prototype.addUnreachable = function (ast) { - if(this.unreachable === null) { - this.unreachable = new Array(); - } - this.unreachable[this.unreachable.length] = ast; - }; - ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { - var targetBB = null; - for(var i = 0, len = this.statementStack.length; i < len; i++) { - var targetInfo = this.statementStack[i]; - if(targetInfo.stmt == target) { - if(isContinue) { - targetBB = targetInfo.continueBB; - } else { - targetBB = targetInfo.breakBB; - } - break; - } - } - if(targetBB) { - this.current.addSuccessor(targetBB); - } - this.setUnreachable(); - }; - ControlFlowContext.prototype.addContent = function (ast) { - if(this.current) { - this.current.content.append(ast); - } - }; - return ControlFlowContext; - })(); - TypeScript.ControlFlowContext = ControlFlowContext; - var ResolutionDataCache = (function () { - function ResolutionDataCache() { - this.cacheSize = 16; - this.rdCache = []; - this.nextUp = 0; - for(var i = 0; i < this.cacheSize; i++) { - this.rdCache[i] = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: i - }; - } - } - ResolutionDataCache.prototype.getResolutionData = function () { - var rd = null; - if(this.nextUp < this.cacheSize) { - rd = this.rdCache[this.nextUp]; - } - if(rd == null) { - this.cacheSize++; - rd = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: this.cacheSize - }; - this.rdCache[this.cacheSize] = rd; - } - this.nextUp++; - return rd; - }; - ResolutionDataCache.prototype.returnResolutionData = function (rd) { - rd.actuals.length = 0; - rd.exactCandidates.length = 0; - rd.conversionCandidates.length = 0; - this.nextUp = rd.id; - }; - return ResolutionDataCache; - })(); - TypeScript.ResolutionDataCache = ResolutionDataCache; - var TypeFlow = (function () { - function TypeFlow(logger, initScope, parser, checker) { - this.logger = logger; - this.initScope = initScope; - this.parser = parser; - this.checker = checker; - this.thisFnc = null; - this.thisClassNode = null; - this.enclosingFncIsMethod = false; - this.arrayInterfaceType = null; - this.stringInterfaceType = null; - this.objectInterfaceType = null; - this.functionInterfaceType = null; - this.numberInterfaceType = null; - this.booleanInterfaceType = null; - this.iargumentsInterfaceType = null; - this.currentScript = null; - this.inImportTypeCheck = false; - this.inTypeRefTypeCheck = false; - this.inArrayElementTypeCheck = false; - this.resolutionDataCache = new ResolutionDataCache(); - this.nestingLevel = 0; - this.inSuperCall = false; - this.checker.typeFlow = this; - this.scope = this.initScope; - this.globalScope = this.initScope; - this.doubleType = this.checker.numberType; - this.booleanType = this.checker.booleanType; - this.stringType = this.checker.stringType; - this.anyType = this.checker.anyType; - this.regexType = this.anyType; - this.nullType = this.checker.nullType; - this.voidType = this.checker.voidType; - this.arrayAnyType = this.checker.makeArrayType(this.anyType); - } - TypeFlow.prototype.initLibs = function () { - var arraySym = this.globalScope.find("Array", false, true); - if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { - this.arrayInterfaceType = (arraySym).type; - } - var stringSym = this.globalScope.find("String", false, true); - if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { - this.stringInterfaceType = (stringSym).type; - } - var objectSym = this.globalScope.find("Object", false, true); - if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { - this.objectInterfaceType = (objectSym).type; - } - var fnSym = this.globalScope.find("Function", false, true); - if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { - this.functionInterfaceType = (fnSym).type; - } - var numberSym = this.globalScope.find("Number", false, true); - if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { - this.numberInterfaceType = (numberSym).type; - } - var booleanSym = this.globalScope.find("Boolean", false, true); - if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { - this.booleanInterfaceType = (booleanSym).type; - } - var regexSym = this.globalScope.find("RegExp", false, true); - if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { - this.regexType = (regexSym).type; - } - }; - TypeFlow.prototype.cast = function (ast, type) { - return this.castWithCoercion(ast, type, true, false); - }; - TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { - if(applyCoercion) { - if(type == null) { - ast.type = this.anyType; - } else if(type.isClass()) { - ast.type = type.instanceType; - } else { - ast.type = type; - } - } - return ast; - } else { - this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); - return ast; - } - }; - TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { - var prevScope = this.scope; - this.scope = enclosingScope; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var svThisClassNode = this.thisClassNode; - var svCurrentModDecl = this.checker.currentModDecl; - var prevMethodStatus = this.enclosingFncIsMethod; - var container = this.scope.container; - var fnc = null; - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - if(fnc == null) { - this.enclosingFncIsMethod = typeSym.isMethod; - fnc = container.declAST; - } - } - if(type.isClass()) { - this.thisType = type.instanceType; - if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { - this.thisClassNode = typeSym.declAST; - } - break; - } - if(type.isModuleType()) { - this.checker.currentModDecl = typeSym.declAST; - break; - } - } - container = container.container; - } - this.thisFnc = fnc; - var updated = this.typeCheck(ast); - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.thisClassNode = svThisClassNode; - this.checker.currentModDecl = svCurrentModDecl; - this.enclosingFncIsMethod = prevMethodStatus; - this.scope = prevScope; - return updated; - }; - TypeFlow.prototype.typeCheck = function (ast) { - if(ast) { - return ast.typeCheck(this); - } else { - return null; - } - }; - TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { - if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { - this.inScopeTypeCheckBoundDecl(ast); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if(funcDecl.isAccessor()) { - this.typeCheckFunction(funcDecl); - } - } - }; - TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { - var sym = varDecl.sym; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevLocationInfo = this.checker.locationInfo; - if(sym && sym.container) { - var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - this.thisFnc = sym.container.declAST; - } - if(instanceScope) { - var prevScope = this.scope; - this.scope = instanceScope; - var container = sym.container; - var svCurrentModDecl = this.checker.currentModDecl; - if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[sym.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - this.enclosingFncIsMethod = typeSym.isMethod; - } - if(type.isClass()) { - this.thisType = type.instanceType; - } - if(type.isModuleType()) { - this.checker.currentModDecl = container.declAST; - break; - } - } - container = container.container; - } - this.typeCheckBoundDecl(varDecl); - this.checker.currentModDecl = svCurrentModDecl; - this.scope = prevScope; - } - } - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.checker.locationInfo = prevLocationInfo; - this.enclosingFncIsMethod = prevMethodStatus; - }; - TypeFlow.prototype.resolveBoundDecl = function (varDecl) { - if(varDecl.typeExpr) { - if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { - this.typeCheck(varDecl.typeExpr); - } - varDecl.type = varDecl.typeExpr.type; - if(varDecl.sym) { - varDecl.sym.setType(varDecl.type); - } - } else if(varDecl.init == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - if(varDecl.sym) { - if(varDecl.sym.isType()) { - var tsym = varDecl.sym; - if(tsym.isMethod) { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); - return; - } else { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); - return; - } - } - varDecl.sym.setType(varDecl.type); - } - } - }; - TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { - var _this = this; - var infSym = varDecl.sym; - if(infSym == null) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = this.checker.widenType(varDecl.init.type); - } else { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - } - } else { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - infSym.setType(this.anyType); - } else if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(infSym); - var resolved = false; - if(varDecl.type == null) { - if(varDecl.typeExpr) { - this.resolveBoundDecl(varDecl); - resolved = true; - varDecl.type = varDecl.typeExpr.type; - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } - } - if(varDecl.init) { - var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); - var prevScope = this.scope; - var applyTargetType = !varDecl.init.isParenthesized; - if(isLocalStatic) { - this.scope = varDecl.sym.container.getType().memberScope; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { - TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { - if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; - } - walker.options.goChildren = false; - } - return ast; - }); - } - this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); - this.scope = prevScope; - if(varDecl.type) { - var preserveScope = false; - var preservedContainedScope = null; - if(varDecl.init.type) { - preservedContainedScope = varDecl.init.type.containedScope; - preserveScope = true; - if(varDecl.init.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - } - } - varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && varDecl.init.type.containedScope == null) { - varDecl.init.type.containedScope = preservedContainedScope; - } - } else { - varDecl.type = this.checker.widenType(varDecl.init.type); - if(varDecl.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - varDecl.type = this.anyType; - } - } - infSym.setType(varDecl.type); - } else { - if(!resolved) { - this.resolveBoundDecl(varDecl); - } - } - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = infSym.getType(); - varDecl.init = this.cast(varDecl.init, varDecl.type); - } - } - } - if(varDecl.id && varDecl.sym) { - varDecl.id.sym = varDecl.sym; - } - if(varDecl.sym && varDecl.sym.container) { - this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { - return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); - }); - } - return varDecl; - }; - TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); - } else { - this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); - } - } else { - this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); - } - }; - TypeFlow.prototype.typeCheckSuper = function (ast) { - if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { - ast.type = this.thisType.baseClass(); - } else { - if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - var enclosingFnc = this.thisFnc.enclosingFnc; - while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - enclosingFnc = enclosingFnc.enclosingFnc; - } - if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { - ast.type = this.thisType.baseClass(); - enclosingFnc.setHasSuperReferenceInFatArrowFunction(); - return ast; - } - } - ast.type = this.anyType; - this.checker.errorReporter.invalidSuperReference(ast); - } - return ast; - }; - TypeFlow.prototype.typeCheckThis = function (ast) { - ast.type = this.anyType; - var illegalThisRef = false; - if(this.thisFnc == null) { - if(this.thisType) { - if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { - illegalThisRef = true; - } else { - ast.type = this.thisType; - } - } else if(this.checker.currentModDecl) { - this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); - } - } else { - if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { - illegalThisRef = true; - } - if(this.thisFnc.isMethod() || this.thisFnc.isConstructor) { - if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - if(this.thisFnc.boundToProperty) { - var container = this.thisFnc.boundToProperty.sym.container; - if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - (container.declAST).setHasSelfReference(); - } - } else { - var encFnc = this.thisFnc.enclosingFnc; - var firstEncFnc = encFnc; - while(encFnc) { - if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { - illegalThisRef = true; - } - if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { - encFnc.setHasSelfReference(); - break; - } - encFnc = encFnc.enclosingFnc; - } - if(!encFnc && firstEncFnc) { - encFnc = firstEncFnc; - encFnc.setHasSelfReference(); - } else if(!encFnc) { - if(this.thisClassNode) { - (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; - } else if(this.checker.currentModDecl) { - this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; - } else { - this.checker.mustCaptureGlobalThis = true; - } - } - if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(illegalThisRef) { - this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); - } - return ast; - }; - TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - infSym.declAST.type = this.anyType; - infSym.setType(this.anyType); - } else { - this.inScopeTypeCheckDecl(infSym.declAST); - } - } - if(!this.checker.styleSettings.innerScopeDeclEscape) { - if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { - if(this.nestingLevel < (infSym.declAST).nestingLevel) { - this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); - } - } - } - } - ast.type = symbol.getType(); - if(!symbol.writeable()) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } - } else if(symbol.isType()) { - ast.type = symbol.getType(); - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } else { - ast.type = this.anyType; - this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); - } - }; - TypeFlow.prototype.typeCheckName = function (ast) { - var _this = this; - var identifier = ast; - if(this.checker.inWith) { - identifier.type = this.anyType; - } else { - var typespace = this.inTypeRefTypeCheck; - var idText = identifier.text; - var originalIdText = idText; - var isDynamicModuleName = TypeScript.isQuoted(identifier.text); - var symbol = this.scope.find(idText, false, typespace); - if(symbol == null && isDynamicModuleName) { - symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { - return _this.scope.find(id, false, typespace); - }); - } - if(!symbol) { - if(!identifier.isMissing()) { - this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); - } - identifier.type = this.anyType; - } else { - if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { - var symType = symbol.getType(); - if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; - } - } - } - if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - (symbol.declAST).signature.returnType.type = this.anyType; - } - this.setTypeFromSymbol(ast, symbol); - identifier.sym = symbol; - if(this.thisFnc) { - if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { - this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; - } - } - } - } - return ast; - }; - TypeFlow.prototype.typeCheckScript = function (script) { - this.checker.locationInfo = script.locationInfo; - this.scope = this.checker.globalScope; - if(!script.topLevelMod) { - this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); - } - this.currentScript = script; - script.bod = this.typeCheck(script.bod); - this.currentScript = null; - return script; - }; - TypeFlow.prototype.typeCheckBitNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return unex; - }; - TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return ast; - }; - TypeFlow.prototype.typeCheckLogNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.booleanType; - return unex; - }; - TypeFlow.prototype.astIsWriteable = function (ast) { - return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); - }; - TypeFlow.prototype.typeCheckIncOrDec = function (ast) { - var unex = ast; - var lval = unex.operand; - if(!this.astIsWriteable(unex)) { - this.checker.errorReporter.valueCannotBeModified(unex); - unex.type = this.doubleType; - } else { - unex = this.typeCheckUnaryNumberOperator(ast); - if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { - this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); - } - } - return unex; - }; - TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { - var binex = ast; - var resultType = null; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { - resultType = this.doubleType; - } else if((leftType == this.booleanType) && (rightType == this.booleanType)) { - resultType = this.booleanType; - } else if(leftType == this.anyType) { - if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { - resultType = this.anyType; - } - } else if(rightType == this.anyType) { - if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { - resultType = this.anyType; - } - } - if(resultType == null) { - resultType = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = resultType; - return binex; - }; - TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - var nodeType = binex.nodeType; - if(this.checker.isNullOrUndefinedType(leftType)) { - leftType = rightType; - } - if(this.checker.isNullOrUndefinedType(rightType)) { - rightType = leftType; - } - leftType = this.checker.widenType(leftType); - rightType = this.checker.widenType(rightType); - if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { - if(leftType == this.checker.stringType || rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } else { - if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } - return binex; - }; - TypeFlow.prototype.typeCheckDotOperator = function (ast) { - var binex = ast; - var leftIsFnc = false; - binex.operand1 = this.typeCheck(binex.operand1); - var leftType = binex.operand1.type; - var leftScope = null; - if(leftType) { - if(leftType == this.anyType) { - binex.type = this.anyType; - return binex; - } else if(leftType == this.stringType) { - if(this.stringInterfaceType) { - leftScope = this.stringInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if(leftType == this.doubleType) { - if(this.numberInterfaceType) { - leftScope = this.numberInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if(leftType == this.booleanType) { - if(this.booleanInterfaceType) { - leftScope = this.booleanInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if((leftType.call || leftType.construct) && leftType.members == null) { - if(this.functionInterfaceType) { - leftScope = this.functionInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if(leftType.elementType) { - if(this.arrayInterfaceType) { - var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); - leftScope = arrInstType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - leftScope = leftType.memberScope; - } - } - if(leftScope == null) { - this.checker.errorReporter.expectedClassOrInterface(binex); - binex.type = this.anyType; - } else { - var propertyName = binex.operand2; - var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; - var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); - if(!symbol) { - if(this.objectInterfaceType && leftType) { - if(leftType.isReferenceType()) { - symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - if(!symbol) { - if(this.functionInterfaceType && (leftType.call || leftType.construct)) { - symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - } - } - } - if(!symbol || (!symbol.visible(leftScope, this.checker))) { - binex.type = this.anyType; - if(symbol == null) { - this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); - } else if(!this.inTypeRefTypeCheck) { - this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); - } - } else { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - this.inScopeTypeCheckDecl(infSym.declAST); - } - } - } - propertyName.sym = symbol; - binex.type = symbol.getType(); - } - } - if(binex.type == null) { - binex.type = this.anyType; - } - return binex; - }; - TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckAsgOperator = function (ast) { - var binex = ast; - var applyTargetType = !binex.operand2.isParenthesized; - binex.operand1 = this.typeCheck(binex.operand1); - this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(!(this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(binex.operand1.nodeType == TypeScript.NodeType.Call) { - var callEx = binex.operand1; - } - var preserveScope = false; - var preservedContainedScope = null; - if(binex.operand2.type) { - preservedContainedScope = binex.operand2.type.containedScope; - preserveScope = true; - } - binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && binex.operand2.type.containedScope == null) { - binex.operand2.type.containedScope = preservedContainedScope; - } - binex.type = rightType; - return binex; - }; - TypeFlow.prototype.typeCheckIndex = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!this.checker.styleSettings.literalSubscript) { - if(binex.operand2.nodeType == TypeScript.NodeType.QString) { - this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); - } - } - var objExprType = binex.operand1.type; - var indexExprType = binex.operand2.type; - if(objExprType.elementType) { - if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { - binex.type = objExprType.elementType; - } else if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } else if(objExprType.index) { - if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - var sig = this.resolveOverload(ast, objExprType.index); - if(sig) { - binex.type = sig.returnType.type; - } else { - binex.type = this.checker.anyType; - } - } else if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } else if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - return binex; - }; - TypeFlow.prototype.typeCheckInOperator = function (binex) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { - this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckShift = function (binex, assignment) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); - binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); - if(assignment && (!(this.astIsWriteable(binex.operand1)))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - binex.type = this.doubleType; - return binex; - }; - TypeFlow.prototype.typeCheckQMark = function (trinex) { - trinex.operand1 = this.typeCheck(trinex.operand1); - trinex.operand2 = this.typeCheck(trinex.operand2); - trinex.operand3 = this.typeCheck(trinex.operand3); - var leftType = trinex.operand2.type; - var rightType = trinex.operand3.type; - if(leftType == rightType) { - trinex.type = leftType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - trinex.type = rightType; - } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - trinex.type = leftType; - } else { - trinex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); - } - } - return trinex; - }; - TypeFlow.prototype.addFormals = function (container, signature, table) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var symbol = signature.parameters[i]; - symbol.container = container; - table.add(symbol.name, symbol); - } - }; - TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { - var len = vars.members.length; - var hasArgsDef = false; - for(var i = 0; i < len; i++) { - var local = vars.members[i]; - if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = null; - if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { - local.varFlags |= TypeScript.VarFlags.LocalStatic; - varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); - } else { - varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - } - varSym.transferVarFlags(local.varFlags); - localVar.symbol = varSym; - varSym.declAST = local; - localVar.typeLink.ast = local.typeExpr; - this.checker.resolveTypeLink(scope, localVar.typeLink, false); - if((local.type == null) && (local.init == null)) { - local.type = this.anyType; - } - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - if(local.id.text == "arguments") { - hasArgsDef = true; - } - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - if(!isModContainer) { - if(!hasArgsDef) { - var argLoc = new TypeScript.ValueLocation(); - argLoc.typeLink = new TypeScript.TypeLink(); - var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); - if(!this.iargumentsInterfaceType) { - var argumentsSym = scope.find("IArguments", false, true); - if(argumentsSym) { - argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; - this.iargumentsInterfaceType = argumentsSym.getType(); - } else { - this.iargumentsInterfaceType = this.anyType; - } - } - argLoc.typeLink.type = this.iargumentsInterfaceType; - table.add("arguments", theArgSym); - } - } - }; - TypeFlow.prototype.addConstructorLocalArgs = function (constructorDecl, table, isClass) { - var container = constructorDecl.type.symbol; - var args = constructorDecl.arguments; - if(args) { - var len = args.members.length; - for(var i = 0; i < len; i++) { - var local = args.members[i]; - if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - this.resolveBoundDecl(local); - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - varSym.funcDecl = constructorDecl; - varSym.declAST = local; - localVar.symbol = varSym; - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - } - }; - TypeFlow.prototype.checkInitSelf = function (funcDecl) { - if(!funcDecl.isMethod()) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if(sym.isInstanceProperty()) { - return true; - } - } - } - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - for(var j = 0; j < fnsLen; j++) { - var fn = fns.members[j]; - if(this.checkInitSelf(fn)) { - return true; - } - } - return false; - }; - TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { - TypeScript.instanceFilter.reset(); - if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); - } - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); - } - } - }; - TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { - var allReturnsAreVoid = true; - if(funcDecl.signature.returnType.type == null) { - var preFindReturnExpressionTypes = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: - go = false; - break; - case TypeScript.NodeType.Return: - var returnStmt = ast; - if(returnStmt.returnExpression) { - allReturnsAreVoid = false; - go = false; - } - default: - break; - } - walker.options.goChildren = go; - walker.options.goNextSibling = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); - } - return allReturnsAreVoid; - }; - TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { - var foundSuper = false; - var preFindSuperCall = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: - go = false; - break; - case TypeScript.NodeType.Call: - var call = ast; - if(call.target.nodeType == TypeScript.NodeType.Super) { - go = false; - foundSuper = true; - break; - } - break; - default: - break; - } - walker.options.goChildren = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); - return foundSuper; - }; - TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { - var baseSymbol = bases.members[i].type.symbol; - var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var baseListTypeString = extendsList ? "extends" : "implements"; - var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module "; - baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; - } else { - baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; - } - this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); - }; - TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { - var _this = this; - if(bases) { - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { - continue; - } - this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { - return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); - }); - } - } - }; - TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { - var externalModuleSymbol = null; - var declSymbolPath = null; - if(typeSymbol.isExternallyVisible(this.checker)) { - var typeSymbolPath = typeSymbol.pathToRoot(); - declSymbolPath = declSymbol.pathToRoot(); - var typeSymbolLength = typeSymbolPath.length; - var declSymbolPathLength = declSymbolPath.length; - if(typeSymbolLength > 0) { - if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; - } else if(typeSymbolLength > 1) { - if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; - } - } - } - if(externalModuleSymbol == null) { - return; - } - } - var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); - if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { - return; - } - var checkVisibilitySymbol = declSymbol; - var varDecl = declSymbol.getVarDeclFromSymbol(); - if(varDecl) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { - return; - } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - checkVisibilitySymbol = declSymbol.container; - } - } - if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { - var privateSymbolName = typeSymbol.name; - if(externalModuleSymbol != null) { - var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); - if(prettyName != null) { - this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); - return; - } else { - privateSymbolName = externalModuleSymbol.prettyName; - } - } - errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); - } - }; - TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { - var _this = this; - if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { - return; - } - if(type.isArray()) { - return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); - } - if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { - return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); - } - if(type.members) { - type.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); - } - }, null); - } - this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); - }; - TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { - if(sgroup) { - var len = sgroup.signatures.length; - for(var i = 0; i < sgroup.signatures.length; i++) { - var signature = sgroup.signatures[i]; - if(len > 1 && signature == sgroup.definitionSignature) { - continue; - } - if(signature.returnType) { - this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - var param = signature.parameters[j]; - this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); - } - } - } - }; - TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(funcDecl.isConstructor) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else if(isSetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); - } else if(!isGetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); - } else if(!funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); - } - } - }; - TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(isGetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); - } else if(!isSetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); - } else if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); - } else if(funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); - } else { - this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); - } - } - }; - TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { - var reportOnFuncDecl = false; - if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); - } - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); - } else { - reportOnFuncDecl = true; - } - } - if(reportOnFuncDecl) { - this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); - } - }; - TypeFlow.prototype.typeCheckFunction = function (funcDecl) { - var _this = this; - this.nestingLevel = 0; - var fnType = funcDecl.type; - var fgSym = fnType.symbol; - var signature = funcDecl.signature; - if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { - return funcDecl; - } else if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { - signature.returnType.type = this.voidType; - return funcDecl; - } else { - if(funcDecl.returnTypeAnnotation == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - } - return funcDecl; - } - } - signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(signature); - var prevScope = this.scope; - var prevFnc = this.thisFnc; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevClassNode = this.thisClassNode; - this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; - this.thisFnc = funcDecl; - var container = funcDecl.type.symbol; - var prevThisType = this.thisType; - var prevLocationInfo = this.checker.locationInfo; - var funcTable = null; - var acceptedContextualType = false; - var targetParams = null; - var targetReturnType = null; - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; - var prevModDecl = this.checker.currentModDecl; - if(funcDecl.isConstructor && !funcDecl.isOverload) { - if(fnType.instanceType == null) { - this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); - return funcDecl; - } - if(funcDecl.classDecl.type.construct == null) { - this.checker.errorReporter.simpleError(funcDecl, "Malformed constructor (is this a class named the same as an existing class?)"); - return funcDecl; - } - this.scope = fnType.instanceType.constructorScope; - var ssb = this.scope; - funcTable = ssb.valueMembers.allMembers; - } else if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { - funcTable = funcDecl.symbols; - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { - this.scope = fnType.containedScope; - } - } else { - if(funcDecl.bod) { - this.scope = fnType.containedScope; - } - var ssb = this.scope; - if(ssb && ssb.valueMembers) { - funcTable = ssb.valueMembers.allMembers; - } - } - if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); - var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); - } else if(hasBaseType) { - if(superCallMustBeFirst) { - if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { - this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); - } - } else if(!this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); - } - } - } - if(funcDecl.isMethod() && funcDecl.type.enclosingType) { - var enclosingClassNode = null; - if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; - } else if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { - enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; - } - if(enclosingClassNode) { - this.thisClassNode = enclosingClassNode; - } - } - if(fnType.enclosingType) { - ; - var enclosingSym = fnType.symbol.container; - if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { - enclosingSym = enclosingSym.container; - } - if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { - this.checker.currentModDecl = enclosingSym.declAST; - } - } - if(funcDecl.unitIndex > 0) { - if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - } - if(fnType.enclosingType) { - this.thisType = fnType.enclosingType; - } else { - this.thisType = prevThisType; - } - var paramLen = signature.parameters.length; - if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { - var tmpParamScope = this.scope; - var ssb = this.scope; - if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { - if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { - var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); - if(considerSym && considerSym.declAST && considerSym.declAST.type) { - this.checker.setContextualType(considerSym.declAST.type, false); - } - } - if(this.checker.hasTargetType()) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var candidateType = candidateTypeContext.contextualType; - if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - candidateTypeContext.targetSig = candidateSigs.signatures[0]; - var candidateParams = candidateTypeContext.targetSig.parameters; - targetParams = candidateParams; - targetReturnType = candidateTypeContext.targetSig.returnType.type; - fgSym.type = candidateTypeContext.contextualType; - acceptedContextualType = true; - } else if(candidateType && funcDecl.isAccessor()) { - accessorType = candidateType; - candidateTypeContext.targetAccessorType = accessorType; - } else { - this.checker.killCurrentContextualType(); - } - } - } - var paramTable = ssb.valueMembers; - this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); - for(var p = 0; p < paramLen; p++) { - var symbol = signature.parameters[p]; - var ast = symbol.declAST; - if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; - ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); - ast.sym.setType(ast.type); - (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else { - this.typeCheck(ast); - } - if(isSetter && accessorType) { - ast = this.cast(ast, accessorType); - } - symbol.container = container; - this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); - }); - paramTable.publicMembers.add(symbol.name, symbol); - } - this.scope = tmpParamScope; - } else { - this.typeCheck(funcDecl.arguments); - for(var p = 0; p < paramLen; p++) { - signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; - this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); - }); - if((funcDecl.arguments.members[p]).parameterPropertySym) { - (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); - } - } - if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { - if(!paramLen || paramLen > 1) { - this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); - } else if(funcDecl.arguments.members[0].type == this.checker.numberType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; - } else if(funcDecl.arguments.members[0].type == this.checker.stringType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; - } else { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); - } - } - } - if(funcDecl.bod && (!funcDecl.isSignature())) { - if(!(funcDecl.isConstructor)) { - this.addFormals(container, signature, funcTable); - } else { - this.addConstructorLocalArgs(funcDecl, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); - if(this.thisClassNode && this.thisClassNode.extendsList) { - var tmpScope = this.scope; - var funcMembers = new TypeScript.ScopedMembers(funcTable); - this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { - return sym.kind() == TypeScript.SymbolKind.Parameter; - }); - this.typeCheckBaseCalls(this.thisClassNode.extendsList); - this.scope = tmpScope; - } - } - var prevMod = this.checker.currentModDecl; - if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { - this.checker.currentModDecl = funcDecl.type.symbol.declModule; - } - if(acceptedContextualType) { - this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); - } - this.typeCheck(funcDecl.bod); - if(acceptedContextualType) { - this.checker.unsetContextualType(); - } - this.checker.currentModDecl = prevMod; - if(this.checker.checkControlFlow) { - var cfg = funcDecl.buildControlFlow(); - if(this.checker.printControlFlowGraph) { - cfg.print(this.checker.errorReporter.outfile); - } - cfg.reportUnreachable(this.checker.errorReporter); - if(this.checker.checkControlFlowUseDef) { - cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); - } - } - if(funcDecl.isConstructor) { - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - var freeVars; - var sym; - var j = 0; - for(; j < fnsLen; j++) { - var fn = fns.members[j]; - if(!fn.isSignature()) { - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { - this.checkPromoteFreeVars(fn, funcDecl.type.symbol); - } - } - } - } - } - this.scope = prevScope; - this.thisFnc = prevFnc; - this.thisClassNode = prevClassNode; - this.enclosingFncIsMethod = prevMethodStatus; - this.thisType = prevThisType; - this.checker.locationInfo = prevLocationInfo; - this.checker.currentModDecl = prevModDecl; - signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - if(funcDecl.returnTypeAnnotation) { - this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); - if(signature.returnType.type == null) { - this.checker.resolveTypeLink(this.scope, signature.returnType, false); - } - } else if(targetReturnType) { - signature.returnType.type = targetReturnType; - } - if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { - var collection = { - getLength: function () { - return funcDecl.returnStatementsWithExpressions.length; - }, - setTypeAtIndex: function (index, type) { - funcDecl.returnStatementsWithExpressions[index].type = type; - }, - getTypeAtIndex: function (index) { - return funcDecl.returnStatementsWithExpressions[index].type; - } - }; - var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; - bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); - if(bestCommonReturnType) { - signature.returnType.type = this.checker.widenType(bestCommonReturnType); - } else { - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); - } - signature.returnType.type = this.anyType; - } - } - var onlyHasThrow = false; - if(signature.returnType.type == null) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - } else { - signature.returnType.type = this.voidType; - } - } else if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { - signature.returnType.type = this.anyType; - } else if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { - if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); - if(!onlyHasThrow) { - this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); - } - } - this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { - return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); - }); - } - if(funcDecl.accessorSymbol) { - var accessorType = funcDecl.accessorSymbol.getType(); - if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); - } - if(accessorType) { - if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { - this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); - } - } else { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - funcDecl.accessorSymbol.setType(signature.returnType.type); - } else { - if(funcDecl.arguments.members.length != 1) { - this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); - } else { - funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); - } - } - } - } - this.typeCheckOverloadSignatures(fnType, funcDecl); - return funcDecl; - }; - TypeFlow.prototype.typeCheckBases = function (type) { - var seenInterface = false; - var bases = type.extendsList; - var baseLinks = type.extendsTypeLinks; - if(bases) { - var len = bases.length; - if(len > 0) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseType; - } - for(var i = 0; i < len; i++) { - if(bases[i] == this.checker.anyType) { - baseLinks[i].type = null; - var oldErrors = this.checker.errorReporter.getCapturedErrors(); - TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); - this.checker.errorReporter.pushToErrorSink = true; - bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); - this.checker.errorReporter.pushToErrorSink = false; - this.checker.errorReporter.freeCapturedErrors(); - } - var base = bases[i]; - var baseRef = baseLinks[i].ast; - var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; - if(baseTypeOfObject) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; - } - if(base.isClassInstance()) { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - if(seenInterface) { - this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); - } - } - } else if(base.isModuleType()) { - this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); - } else if(base.members) { - if(!seenInterface) { - seenInterface = true; - } - } else { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); - } - break; - } - } - } - }; - TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { - var instanceType = implementingType.getInstanceType(); - if(instanceType.implementsList) { - var len = instanceType.implementsList.length; - for(var i = 0; i < len; i++) { - var interfaceType = instanceType.implementsList[i]; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { - var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); - } else { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); - } - } - } - } - }; - TypeFlow.prototype.typeCheckBaseCalls = function (bases) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.typeCheckNew(baseExpr); - } - } - }; - TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { - var _this = this; - if(type) { - if(type.members) { - type.members.publicMembers.map(function (key, s, c) { - var sym = s; - var dup = names.lookup(sym.name); - if(dup) { - if(checkUnique) { - _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); - } - } else { - names.add(sym.name, sym); - } - }, null); - } - if(type.extendsList) { - var len = type.extendsList.length; - for(var i = 0; i < len; i++) { - if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { - this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); - } - } - } - } - }; - TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { - var _this = this; - var instanceType = derivedType.getInstanceType(); - if(instanceType.extendsList == null) { - return; - } - var len = instanceType.extendsList.length; - if(len > 0) { - var names = new TypeScript.StringHashTable(); - if(instanceType.isClassInstance()) { - for(var i = 0; i < len; i++) { - this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); - } - } - if(instanceType.members) { - instanceType.members.publicMembers.map(function (key, s, c) { - var sym = s; - for(var j = 0; j < len; j++) { - var base = instanceType.extendsList[j]; - if(base.memberScope == null) { - _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); - } else { - var bSym = base.memberScope.find(sym.name, false, false); - if(bSym) { - var aType = sym.getType(); - var bType = bSym.getType(); - if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); - } else if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); - } - } - } - } - }, null); - } - } - }; - TypeFlow.prototype.typeCheckClass = function (classDecl) { - var typeSymbol = classDecl.type.symbol; - if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { - return classDecl; - } else if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - return classDecl; - } else { - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(typeSymbol); - } - var prevScope = this.scope; - var svClassNode = this.thisClassNode; - this.thisClassNode = classDecl; - var classType = classDecl.type; - this.typeCheckBases(classType.instanceType); - this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); - this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); - var prevThisType = this.thisType; - this.thisType = classType.instanceType; - this.scope = classType.instanceType.containedScope; - if(classDecl.constructorDecl) { - this.scope = classType.instanceType.constructorScope; - var ssb = this.scope; - var funcTable = ssb.valueMembers.allMembers; - this.addConstructorLocalArgs(classDecl.constructorDecl, funcTable, true); - } - this.typeCheck(classDecl.members); - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - this.checkBaseTypeMemberInheritance(classType, classDecl); - this.checkMembersImplementInterfaces(classType); - this.typeCheckOverloadSignatures(classType, classDecl); - this.typeCheckOverloadSignatures(classType.instanceType, classDecl); - if(!classDecl.constructorDecl) { - if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { - TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); - } - } - this.thisType = prevThisType; - this.thisClassNode = svClassNode; - this.scope = prevScope; - return classDecl; - }; - TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { - if(type.call) { - type.call.typeCheck(this.checker, ast, type.construct != null); - } - if(type.construct) { - type.construct.typeCheck(this.checker, ast, false); - } - if(type.index) { - type.index.typeCheck(this.checker, ast, false); - } - }; - TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { - this.typeCheckBases(interfaceDecl.type); - this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); - this.typeCheck(interfaceDecl.members); - this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); - if(interfaceDecl.extendsList) { - for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { - if(interfaceDecl.extendsList.members[i].type.call) { - if(interfaceDecl.type.call) { - interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); - } else { - interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; - } - } - if(interfaceDecl.extendsList.members[i].type.construct) { - if(interfaceDecl.type.construct) { - interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); - } else { - interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; - } - } - if(interfaceDecl.extendsList.members[i].type.index) { - if(interfaceDecl.type.index) { - interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); - } else { - interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; - } - } - } - } - return interfaceDecl; - }; - TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { - var mod = importDecl.alias.type; - var sym = null; - var prevInImportTC = this.inImportTypeCheck; - this.inImportTypeCheck = true; - this.typeCheck(importDecl.alias); - mod = importDecl.alias.type; - if(mod == null) { - this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); - mod = this.checker.anyType; - (importDecl.id.sym).type = mod; - } - importDecl.id.type = mod; - sym = mod.symbol; - if(!mod.isModuleType()) { - this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); - } else { - sym.type = mod; - if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { - this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); - } - (importDecl.id.sym).type = mod; - if(mod.symbol && mod.symbol.declAST) { - (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - } - } - this.inImportTypeCheck = prevInImportTC; - return importDecl; - }; - TypeFlow.prototype.typeCheckModule = function (moduleDecl) { - if(!moduleDecl.mod) { - return moduleDecl; - } - if(this.currentScript) { - this.currentScript.requiresGlobal = true; - } - var mod = moduleDecl.mod; - var sym = null; - var prevScope = this.scope; - var prevThisType = this.thisType; - var prevCurrentModDecl = this.checker.currentModDecl; - this.checker.currentModDecl = moduleDecl; - this.thisType = null; - this.scope = mod.containedScope; - this.typeCheck(moduleDecl.members); - sym = mod.symbol; - this.checker.currentModDecl = prevCurrentModDecl; - this.thisType = prevThisType; - this.scope = prevScope; - moduleDecl.type = mod; - if(sym) { - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - } - return moduleDecl; - }; - TypeFlow.prototype.typeCheckFor = function (forStmt) { - forStmt.init = this.typeCheck(forStmt.init); - this.nestingLevel++; - forStmt.cond = this.typeCheck(forStmt.cond); - this.typeCheckCondExpr(forStmt.cond); - forStmt.incr = this.typeCheck(forStmt.incr); - this.nestingLevel--; - forStmt.body = this.typeCheck(forStmt.body); - this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); - forStmt.type = this.voidType; - return forStmt; - }; - TypeFlow.prototype.typeCheckWith = function (withStmt) { - if(this.checker.errorsOnWith) { - this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); - } - withStmt.expr = this.typeCheck(withStmt.expr); - this.checker.inWith = true; - withStmt.body = this.typeCheck(withStmt.body); - this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); - this.checker.inWith = false; - return withStmt; - }; - TypeFlow.prototype.typeCheckForIn = function (forInStmt) { - forInStmt.obj = this.typeCheck(forInStmt.obj); - forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); - if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = forInStmt.lval; - if(varDecl.typeExpr) { - this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); - } - if(varDecl.sym) { - varDecl.sym.setType(this.checker.stringType); - } - } - forInStmt.body = this.typeCheck(forInStmt.body); - this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); - return forInStmt; - }; - TypeFlow.prototype.typeCheckWhile = function (whileStmt) { - whileStmt.cond = this.typeCheck(whileStmt.cond); - this.typeCheckCondExpr(whileStmt.cond); - whileStmt.body = this.typeCheck(whileStmt.body); - this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); - whileStmt.type = this.voidType; - return whileStmt; - }; - TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { - doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); - this.typeCheckCondExpr(doWhileStmt.cond); - doWhileStmt.body = this.typeCheck(doWhileStmt.body); - this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); - doWhileStmt.type = this.voidType; - return doWhileStmt; - }; - TypeFlow.prototype.typeCheckCondExpr = function (cond) { - if(this.checker.styleSettings.assignmentInCond) { - if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { - this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); - } - } - }; - TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { - if(this.checker.styleSettings.blockInCompoundStmt && stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); - } - } - }; - TypeFlow.prototype.typeCheckIf = function (ifStmt) { - ifStmt.cond = this.typeCheck(ifStmt.cond); - this.typeCheckCondExpr(ifStmt.cond); - ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); - ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); - this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); - this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); - ifStmt.type = this.voidType; - return ifStmt; - }; - TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { - if(!funcDecl.isAccessor()) { - return null; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - return funcDecl.type.call.signatures[0].returnType.type; - } else { - return funcDecl.type.call.signatures[0].parameters[0].getType(); - } - }; - TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { - var resultType = new TypeScript.Type(); - resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); - resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); - var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); - aggScope.addParentScope(resultType.memberScope); - aggScope.addParentScope(this.scope); - resultType.containedScope = aggScope; - var memberDecls = objectLit.operand; - var prevThisType = this.thisType; - var acceptTargetType = false; - var targetType = null; - if(this.checker.hasTargetType()) { - targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { - if(targetType.symbol.declAST) { - this.typeCheck(targetType.symbol.declAST); - } - } - acceptTargetType = true; - } - if(memberDecls) { - for(var i = 0, len = memberDecls.members.length; i < len; i++) { - var binex = memberDecls.members[i]; - var id = binex.operand1; - var text; - var targetMember = null; - var fieldSymbol = null; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); - resultType = this.anyType; - break; - } - if(acceptTargetType && targetType.memberScope) { - targetMember = targetType.memberScope.find(text, false, false); - } - if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { - var funcDecl = binex.operand2; - var accessorSym = resultType.members.publicMembers.lookup(text); - accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); - funcDecl.accessorSymbol = accessorSym; - fieldSymbol = accessorSym; - if(id.nodeType == TypeScript.NodeType.Name) { - (id).sym = accessorSym; - } - } - this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); - if(acceptTargetType && targetMember) { - if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { - binex.operand1.type = targetMember.getType(); - } - } else { - binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; - } - if(fieldSymbol == null) { - var memberType = binex.operand2.type; - var field = new TypeScript.ValueLocation(); - fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= TypeScript.SymbolFlags.Property; - field.symbol = fieldSymbol; - fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.type = memberType; - resultType.members.publicMembers.add(text, fieldSymbol); - } - fieldSymbol.isObjectLitField = true; - } - } - this.thisType = prevThisType; - objectLit.type = resultType; - if(targetType) { - objectLit.targetType = targetType; - } - }; - TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { - var elements = arrayLit.operand; - var elementType = this.anyType; - var targetElementType = null; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - comparisonInfo.onlyCaptureFirstError = true; - if(this.checker.hasTargetType()) { - var targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType.elementType) { - targetElementType = targetType.elementType; - } - } - if(elements) { - var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; - this.inArrayElementTypeCheck = true; - this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); - this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; - elementType = elements.members[0].type; - var collection = { - getLength: function () { - return elements.members.length; - }, - setTypeAtIndex: function (index, type) { - elements.members[index].type = type; - }, - getTypeAtIndex: function (index) { - return elements.members[index].type; - } - }; - elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); - if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { - elementType = this.anyType; - } - } - if(!elementType) { - var emsg = "Incompatible types in array literal expression"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleError(arrayLit, emsg); - } else { - this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); - } - elementType = this.anyType; - } else if(targetElementType) { - if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { - elementType = targetElementType; - } - } - arrayLit.type = this.checker.makeArrayType(elementType); - }; - TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { - if(type && type.construct && type.construct.signatures.length > 0) { - for(var i = 0; i < type.construct.signatures.length; i++) { - if(type.construct.signatures[i].returnType.type == this.checker.voidType) { - this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); - break; - } - } - } - }; - TypeFlow.prototype.typeCheckReturn = function (returnStmt) { - if(this.thisFnc) { - var targetType = null; - if(this.checker.hasTargetType()) { - var tcContext = this.checker.getTargetTypeContext(); - var accessorType = tcContext.targetAccessorType; - if(accessorType) { - targetType = accessorType; - } else { - var targetSig = this.checker.getTargetTypeContext().targetSig; - if(targetSig && targetSig.returnType.type != this.voidType) { - targetType = targetSig.returnType.type; - } - } - } - if(returnStmt.returnExpression) { - this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; - if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { - targetType = this.thisFnc.returnTypeAnnotation.type; - } - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); - var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; - if(expectedReturnType) { - if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { - this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); - returnStmt.type = returnStmt.returnExpression.type; - } else { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); - returnStmt.type = expectedReturnType; - } - } else { - if(targetType) { - if(returnStmt.returnExpression.type != this.voidType) { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); - } else { - returnStmt.returnExpression.type = targetType; - } - } - returnStmt.type = returnStmt.returnExpression.type; - } - this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; - } else { - returnStmt.type = targetType == null ? this.checker.voidType : targetType; - } - } - return returnStmt; - }; - TypeFlow.prototype.typeCheckInstOf = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { - this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckCommaOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.typeCheckLogOr = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else if(leftType == this.checker.booleanType) { - if(rightType == this.checker.booleanType) { - binex.type = this.checker.booleanType; - } else { - binex.type = this.checker.anyType; - } - } else if(leftType == this.checker.numberType) { - if(rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.checker.anyType; - } - } else if(leftType == this.checker.stringType) { - if(rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - binex.type = rightType; - } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - binex.type = leftType; - } else { - binex.type = this.checker.anyType; - } - } - return binex; - }; - TypeFlow.prototype.typeCheckLogAnd = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { - var lowerBound = signature.nonOptionalParameterCount; - var upperBound = signature.parameters.length; - var formalLen = lowerBound; - var acceptable = false; - if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { - formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); - acceptable = true; - } - var repeatType = null; - if(acceptable || signature.hasVariableArgList) { - if(signature.hasVariableArgList) { - formalLen -= 1; - repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; - repeatType = repeatType.elementType; - acceptable = actuals.length >= formalLen; - } - var len = actuals.length; - var exact = acceptable; - var convert = acceptable; - for(var i = 0; i < len; i++) { - var typeA; - if(i < formalLen) { - typeA = (signature.parameters[i]).parameter.typeLink.type; - } else { - typeA = repeatType; - } - var typeB = actuals[i]; - if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { - exact = false; - } - if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { - convert = false; - } - if(!(exact || convert)) { - break; - } - } - if(exact) { - exactCandidates[exactCandidates.length] = signature; - } else if(convert && (exactCandidates.length == 0)) { - conversionCandidates[conversionCandidates.length] = signature; - } - } - }; - TypeFlow.prototype.resolveOverload = function (application, group) { - var rd = this.resolutionDataCache.getResolutionData(); - var actuals = rd.actuals; - var exactCandidates = rd.exactCandidates; - var conversionCandidates = rd.conversionCandidates; - var candidate = null; - var hasOverloads = group.signatures.length > 1; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - var args = null; - var target = null; - if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { - var callEx = application; - args = callEx.arguments; - target = callEx.target; - if(callEx.arguments) { - var len = callEx.arguments.members.length; - for(var i = 0; i < len; i++) { - actuals[i] = callEx.arguments.members[i].type; - } - } - } else if(application.nodeType == TypeScript.NodeType.Index) { - var binExp = application; - target = binExp.operand1; - args = new TypeScript.ASTList(); - args.members[0] = binExp.operand2; - actuals[0] = binExp.operand2.type; - } - for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { - var signature = group.signatures[j]; - if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { - continue; - } - if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { - this.typeCheckFunction(signature.declAST); - } - this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); - } - var apparentTarget = target.nodeType == TypeScript.NodeType.Dot ? (target).operand2 : target; - if(exactCandidates.length == 0) { - var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); - if(applicableCandidates.length > 0) { - var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - var emsg = "Supplied parameters do not match any signature of call target"; - if(comparisonInfo.message) { - this.checker.errorReporter.simpleError(apparentTarget, emsg + ":\n\t" + comparisonInfo.message); - } else { - this.checker.errorReporter.simpleError(apparentTarget, emsg); - } - } - } else { - if(exactCandidates.length > 1) { - var applicableSigs = []; - for(var i = 0; i < exactCandidates.length; i++) { - applicableSigs[i] = { - signature: exactCandidates[i], - hadProvisionalErrors: false - }; - } - var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - candidate = exactCandidates[0]; - } - } - this.resolutionDataCache.returnResolutionData(rd); - return candidate; - }; - TypeFlow.prototype.typeCheckNew = function (ast) { - var callEx = ast; - callEx.target = this.typeCheck(callEx.target); - var target = callEx.target; - if(target.type.construct || target.type.call) { - this.preTypeCheckCallArgs(callEx.arguments); - } else { - callEx.arguments = this.typeCheck(callEx.arguments); - } - if(target.type == this.anyType) { - callEx.type = this.anyType; - callEx.arguments = this.typeCheck(callEx.arguments); - } else { - if(target.type.construct) { - var signature = this.resolveOverload(callEx, target.type.construct); - if(signature == null) { - callEx.type = this.anyType; - } else if(signature.returnType.type == this.voidType) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else if(target.type.call) { - var signature = this.resolveOverload(callEx, target.type.call); - if(signature == null) { - callEx.type = this.anyType; - } else if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); - } - } else if(target.type.elementType) { - callEx.type = target.type; - } else { - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - callEx.type = this.anyType; - } - } - this.postTypeCheckCallArgs(callEx); - return callEx; - }; - TypeFlow.prototype.preTypeCheckCallArgs = function (args) { - if(!args) { - return; - } - for(var i = 0; i < args.members.length; i++) { - switch(args.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - continue; - default: - this.typeCheck(args.members[i]); - break; - } - } - }; - TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { - var acceptedTargetType = false; - var i = 0; - if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { - var sig = callEx.signature; - if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { - acceptedTargetType = true; - var targetType = null; - var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; - var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; - for(i = 0; i < nonVarArgActualParamLength; i++) { - targetType = sig.parameters[i].getType(); - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); - break; - } - } - if(sig.hasVariableArgList) { - var varArgParamIndex = sig.nonOptionalParameterCount - 1; - targetType = sig.parameters[varArgParamIndex].getType(); - if(targetType) { - targetType = targetType.elementType; - } - var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; - for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); - break; - } - } - } - } - } - if(!acceptedTargetType && callEx.arguments) { - this.checker.killCurrentContextualType(); - for(i = 0; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - this.typeCheck(callEx.arguments.members[i]); - break; - default: - continue; - } - } - } - }; - TypeFlow.prototype.typeCheckCall = function (ast) { - var callEx = ast; - if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { - this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); - } - } else if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { - if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { - this.checker.errorReporter.styleError(callEx, "eval not permitted"); - } - } - if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { - (callEx.target).isInlineCallLiteral = true; - } - var prevInSuperCall = this.inSuperCall; - if(callEx.target.nodeType == TypeScript.NodeType.Super) { - this.inSuperCall = true; - } - callEx.target = this.typeCheck(callEx.target); - this.preTypeCheckCallArgs(callEx.arguments); - var target = callEx.target; - if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { - callEx.type = this.anyType; - } else { - var fnType = target.type; - if(fnType.call) { - var signature = this.resolveOverload(callEx, fnType.call); - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - callEx.type = this.anyType; - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - } - } - } - this.postTypeCheckCallArgs(callEx); - this.inSuperCall = prevInSuperCall; - return callEx; - }; - TypeFlow.prototype.assignScopes = function (ast) { - var script = ast; - this.checker.locationInfo = script.locationInfo; - var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); - var context = new TypeScript.AssignScopeContext(globalChain, this, [ - this.checker.currentModDecl - ]); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); - }; - TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { - var enclosingScope = enclosingScopeContext.getScope(); - var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); - var scriptFragment = enclosingScopeContext.getScriptFragment(); - var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); - memContext.scope = enclosingScope; - if(scriptFragment.nodeType == TypeScript.NodeType.Name) { - return scriptFragment.type.getMemberScope(this); - } else { - TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); - if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(memContext.type) { - return memContext.type.getMemberScope(this); - } else { - return null; - } - } - }; - TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { - return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); - }; - TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { - var matchFlag = TypeScript.ASTFlags.DotLHS; - var pos = enclosingScopeContext.pos; - var astResult = null; - var preFindMemberScopeFullAst = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { - astResult = ast; - walker.options.stopWalk(); - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { - astResult = ast; - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); - if(astResult == null) { - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); - } - if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(astResult && astResult.type) { - return astResult.type.getMemberScope(this); - } else { - return null; - } - }; - return TypeFlow; - })(); - TypeScript.TypeFlow = TypeFlow; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (Primitive) { - Primitive._map = []; - Primitive.None = 0; - Primitive.Void = 1; - Primitive.Double = 2; - Primitive.String = 4; - Primitive.Boolean = 8; - Primitive.Any = 16; - Primitive.Null = 32; - Primitive.Undefined = 64; - })(TypeScript.Primitive || (TypeScript.Primitive = {})); - var Primitive = TypeScript.Primitive; - var MemberName = (function () { - function MemberName() { - this.prefix = ""; - this.suffix = ""; - } - MemberName.prototype.isString = function () { - return false; - }; - MemberName.prototype.isArray = function () { - return false; - }; - MemberName.prototype.toString = function () { - return MemberName.memberNameToString(this); - }; - MemberName.memberNameToString = function memberNameToString(memberName) { - var result = memberName.prefix; - if(memberName.isString()) { - result += (memberName).text; - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - result += MemberName.memberNameToString(ar.entries[index]); - result += ar.delim; - } - } - result += memberName.suffix; - return result; - }; - MemberName.create = function create(arg1, arg2, arg3) { - if(typeof arg1 == "string") { - return new MemberNameString(arg1); - } else { - var result = new MemberNameArray(); - if(arg2) { - result.prefix = arg2; - } - if(arg3) { - result.suffix = arg3; - } - result.entries.push(arg1); - return result; - } - }; - return MemberName; - })(); - TypeScript.MemberName = MemberName; - var MemberNameString = (function (_super) { - __extends(MemberNameString, _super); - function MemberNameString(text) { - _super.call(this); - this.text = text; - } - MemberNameString.prototype.isString = function () { - return true; - }; - return MemberNameString; - })(MemberName); - TypeScript.MemberNameString = MemberNameString; - var MemberNameArray = (function (_super) { - __extends(MemberNameArray, _super); - function MemberNameArray() { - _super.apply(this, arguments); - - this.delim = ""; - this.entries = []; - } - MemberNameArray.prototype.isArray = function () { - return true; - }; - MemberNameArray.prototype.add = function (entry) { - this.entries.push(entry); - }; - MemberNameArray.prototype.addAll = function (entries) { - for(var i = 0; i < entries.length; i++) { - this.entries.push(entries[i]); - } - }; - return MemberNameArray; - })(MemberName); - TypeScript.MemberNameArray = MemberNameArray; - var currentTypeID = -1; - var Type = (function () { - function Type() { - this.typeID = currentTypeID++; - this.construct = null; - this.call = null; - this.index = null; - this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.primitiveTypeClass = Primitive.None; - this.typeFlags = TypeScript.TypeFlags.None; - } - Type.prototype.baseClass = function () { - if(this.extendsList && (this.extendsList.length > 0)) { - return this.extendsList[0]; - } else { - return null; - } - }; - Type.prototype.getArrayBase = function (arrInstType, checker) { - return this.arrayCache.specialize(arrInstType, checker); - }; - Type.prototype.isClass = function () { - return this.instanceType != null; - }; - Type.prototype.isArray = function () { - return this.elementType != null; - }; - Type.prototype.isClassInstance = function () { - return this.symbol && !this.elementType && (this.symbol).type.isClass(); - }; - Type.prototype.getInstanceType = function () { - if(this.isClass()) { - return this.instanceType; - } else { - return this; - } - }; - Type.prototype.hasImplementation = function () { - return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); - }; - Type.prototype.setHasImplementation = function () { - this.typeFlags |= TypeScript.TypeFlags.HasImplementation; - }; - Type.prototype.isDouble = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); - }; - Type.prototype.isString = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); - }; - Type.prototype.isBoolean = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); - }; - Type.prototype.isNull = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); - }; - Type.prototype.getTypeName = function () { - return this.getMemberTypeName("", true, false, null); - }; - Type.prototype.getScopedTypeName = function (scope, getPrettyTypeName) { - return this.getMemberTypeName("", true, false, scope, getPrettyTypeName); - }; - Type.prototype.getScopedTypeNameEx = function (scope, getPrettyTypeName) { - return this.getMemberTypeNameEx("", true, false, scope, getPrettyTypeName); - }; - Type.prototype.callCount = function () { - var total = 0; - if(this.call) { - total += this.call.signatures.length; - } - if(this.construct) { - total += this.construct.signatures.length; - } - if(this.index) { - total += this.index.signatures.length; - } - return total; - }; - Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { - var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope, getPrettyTypeName); - return memberName.toString(); - }; - Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { - if(this.elementType) { - return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); - } else if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { - var tn = this.symbol.scopeRelativeName(scope); - return MemberName.create(tn == "null" ? "any" : tn); - } else { - if(this.members || this.call || this.construct) { - if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { - return MemberName.create("this"); - } - this.typeFlags |= TypeScript.TypeFlags.BuildingName; - var builder = ""; - var allMemberNames = new MemberNameArray(); - var curlies = isElementType || this.index != null; - var memCount = 0; - var delim = "; "; - if(this.members) { - this.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - var typeNameMember = sym.getTypeNameEx(scope); - if(typeNameMember.isArray() && (typeNameMember).delim == delim) { - allMemberNames.addAll((typeNameMember).entries); - } else { - allMemberNames.add(typeNameMember); - } - memCount++; - curlies = true; - } - }, null); - } - var signatureCount = this.callCount(); - var j; - var len = 0; - var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.call && this.call.signatures.length > 1 && !this.members && !this.construct; - var shortform = !curlies && (signatureCount == 1 || getPrettyFunctionOverload) && topLevel; - if(this.call) { - allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope, getPrettyFunctionOverload)); - } - if(this.construct) { - allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); - } - if(this.index) { - allMemberNames.addAll(this.index.toStrings("", shortform, scope)); - } - if((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { - allMemberNames.prefix = "{ "; - allMemberNames.suffix = "}"; - allMemberNames.delim = delim; - } else if(allMemberNames.entries.length > 1) { - allMemberNames.delim = delim; - } - this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); - if((signatureCount == 0) && (memCount == 0)) { - return MemberName.create("{}"); - } else { - return allMemberNames; - } - } else { - return MemberName.create("{}"); - } - } - }; - Type.prototype.checkDecl = function (checker) { - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST) { - checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); - } - } - }; - Type.prototype.getMemberScope = function (flow) { - if(this == flow.anyType) { - return null; - } else if(this.isDouble()) { - if(flow.numberInterfaceType) { - return flow.numberInterfaceType.memberScope; - } else { - return null; - } - } else if(this.isBoolean()) { - if(flow.booleanInterfaceType) { - return flow.booleanInterfaceType.memberScope; - } else { - return null; - } - } else if(this == flow.stringType) { - if(flow.stringInterfaceType) { - return flow.stringInterfaceType.memberScope; - } else { - return null; - } - } else if(this.elementType) { - if(flow.arrayInterfaceType) { - var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); - return arrInstType.memberScope; - } else { - return null; - } - } else { - return this.memberScope; - } - }; - Type.prototype.isReferenceType = function () { - return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; - }; - Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { - if(pattern == this) { - return replacement; - } - var result = this; - if(membersOnly) { - if(this.isReferenceType()) { - result = new Type(); - if(this.members) { - result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.members.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPublicMember(bSym.name, bSym); - }, null); - this.members.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPrivateMember(bSym.name, bSym); - }, null); - } - if(this.ambientMembers) { - result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.ambientMembers.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPublicMember(bSym.name, bSym); - }, null); - this.ambientMembers.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPrivateMember(bSym.name, bSym); - }, null); - } - result.containedScope = checker.scopeOf(result); - result.memberScope = result.containedScope; - } - } else { - if(this.elementType) { - if(this.elementType == pattern) { - result = checker.makeArrayType(replacement); - } else { - if(this.elementType.elementType == pattern) { - result = checker.makeArrayType(checker.makeArrayType(replacement)); - } - } - } else if(this.call) { - result = new Type(); - result.call = this.call.specializeType(pattern, replacement, checker); - } - } - return result; - }; - Type.prototype.hasBase = function (baseType) { - if(baseType == this) { - return true; - } else { - if(this.extendsList) { - for(var i = 0, len = this.extendsList.length; i < len; i++) { - if(this.extendsList[i].hasBase(baseType)) { - return true; - } - } - } - } - return false; - }; - Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { - if((this == checker.anyType) || (b == checker.anyType)) { - return checker.anyType; - } else if(this == b) { - return this; - } else if((b == checker.nullType) && this != checker.nullType) { - return this; - } else if((this == checker.nullType) && (b != checker.nullType)) { - return b; - } else if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { - return this; - } else if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { - return b; - } else if((b == checker.undefinedType) && this != checker.undefinedType) { - return this; - } else if((this == checker.undefinedType) && (b != checker.undefinedType)) { - return b; - } else if(this.elementType && b.elementType) { - if(this.elementType == b.elementType) { - return this; - } else { - var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); - if(mergedET == null) { - return checker.makeArrayType(checker.anyType); - } else { - return checker.makeArrayType(mergedET); - } - } - } else if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { - return b; - } else if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { - return this; - } else { - return null; - } - }; - Type.prototype.isModuleType = function () { - return false; - }; - Type.prototype.hasMembers = function () { - return this.members != null; - }; - Type.prototype.getAllEnclosedTypes = function () { - return null; - }; - Type.prototype.getAllAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getPublicEnclosedTypes = function () { - return null; - }; - Type.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getDocComments = function () { - if(this.elementType || !this.symbol) { - return []; - } - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return (this.symbol.declAST).classDecl.getDocComments(); - } else { - return this.symbol.getDocComments(); - } - } - if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { - return this.symbol.getDocComments(); - } - return []; - }; - return Type; - })(); - TypeScript.Type = Type; - var ModuleType = (function (_super) { - __extends(ModuleType, _super); - function ModuleType(enclosedTypes, ambientEnclosedTypes) { - _super.call(this); - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.importedModules = []; - } - ModuleType.prototype.isModuleType = function () { - return true; - }; - ModuleType.prototype.hasMembers = function () { - return this.members != null || this.enclosedTypes != null; - }; - ModuleType.prototype.getAllEnclosedTypes = function () { - return this.enclosedTypes; - }; - ModuleType.prototype.getAllAmbientEnclosedTypes = function () { - return this.ambientEnclosedTypes; - }; - ModuleType.prototype.getPublicEnclosedTypes = function () { - return null; - }; - ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { - var moduleName = null; - members.map(function (key, s, c) { - if(moduleName == null && !TypeScript.isQuoted(key)) { - var symbol = s; - var type = symbol.getType(); - if(type == moduleType) { - moduleName = { - name: key, - symbol: symbol - }; - } - } - }, null); - return moduleName; - }; - ModuleType.prototype.findDynamicModuleName = function (moduleType) { - var moduleName = null; - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); - if(moduleName == null) { - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); - } - return moduleName; - }; - return ModuleType; - })(Type); - TypeScript.ModuleType = ModuleType; - var TypeLink = (function () { - function TypeLink() { - this.type = null; - this.ast = null; - } - return TypeLink; - })(); - TypeScript.TypeLink = TypeLink; - function getTypeLink(ast, checker, autoVar) { - var result = new TypeLink(); - result.ast = ast; - if((ast == null) && (autoVar)) { - result.type = checker.anyType; - } else { - result.type = null; - } - return result; - } - TypeScript.getTypeLink = getTypeLink; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function stripQuotes(str) { - return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); - } - TypeScript.stripQuotes = stripQuotes; - function isSingleQuoted(str) { - return str.indexOf("'") != -1; - } - TypeScript.isSingleQuoted = isSingleQuoted; - function isQuoted(str) { - return str.indexOf("\"") != -1 || isSingleQuoted(str); - } - TypeScript.isQuoted = isQuoted; - function quoteStr(str) { - return "\"" + str + "\""; - } - TypeScript.quoteStr = quoteStr; - function swapQuotes(str) { - if(str.indexOf("\"") != -1) { - str = str.replace("\"", "'"); - str = str.replace("\"", "'"); - } else { - str = str.replace("'", "\""); - str = str.replace("'", "\""); - } - return str; - } - TypeScript.swapQuotes = swapQuotes; - function changeToSingleQuote(str) { - if(str.indexOf("\"") != -1) { - str = str.replace("\"", "'"); - str = str.replace("\"", "'"); - } - return str; - } - TypeScript.changeToSingleQuote = changeToSingleQuote; - function switchToForwardSlashes(path) { - return path.replace(/\\/g, "/"); - } - TypeScript.switchToForwardSlashes = switchToForwardSlashes; - function trimModName(modName) { - if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { - return modName.substring(0, modName.length - 6); - } - if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { - return modName.substring(0, modName.length - 4); - } - if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { - return modName.substring(0, modName.length - 5); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { - return modName.substring(0, modName.length - 3); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { - return modName.substring(0, modName.length - 3); - } - return modName; - } - TypeScript.trimModName = trimModName; - function getDeclareFilePath(fname) { - return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); - } - TypeScript.getDeclareFilePath = getDeclareFilePath; - function isFileOfExtension(fname, ext) { - var invariantFname = fname.toLocaleUpperCase(); - var invariantExt = ext.toLocaleUpperCase(); - var extLength = invariantExt.length; - return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; - } - function isJSFile(fname) { - return isFileOfExtension(fname, ".js"); - } - TypeScript.isJSFile = isJSFile; - function isSTRFile(fname) { - return isFileOfExtension(fname, ".str"); - } - TypeScript.isSTRFile = isSTRFile; - function isTSFile(fname) { - return isFileOfExtension(fname, ".ts"); - } - TypeScript.isTSFile = isTSFile; - function isDSTRFile(fname) { - return isFileOfExtension(fname, ".d.str"); - } - TypeScript.isDSTRFile = isDSTRFile; - function isDTSFile(fname) { - return isFileOfExtension(fname, ".d.ts"); - } - TypeScript.isDTSFile = isDTSFile; - function getPrettyName(modPath, quote, treatAsFileName) { - if (typeof quote === "undefined") { quote = true; } - if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } - var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); - var components = this.getPathComponents(modName); - return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; - } - TypeScript.getPrettyName = getPrettyName; - function getPathComponents(path) { - return path.split("/"); - } - TypeScript.getPathComponents = getPathComponents; - function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { - absoluteModPath = switchToForwardSlashes(absoluteModPath); - var modComponents = this.getPathComponents(absoluteModPath); - var fixedModComponents = this.getPathComponents(fixedModFilePath); - var joinStartIndex = 0; - for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { - break; - } - } - if(joinStartIndex != 0) { - var relativePath = ""; - var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); - for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != "") { - relativePath = relativePath + "../"; - } - } - return relativePath + relativePathComponents.join("/"); - } - return absoluteModPath; - } - TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; - function quoteBaseName(modPath) { - var modName = trimModName(stripQuotes(modPath)); - var path = getRootFilePath(modName); - if(path == "") { - return modPath; - } else { - var components = modName.split(path); - var fileIndex = components.length > 1 ? 1 : 0; - return quoteStr(components[fileIndex]); - } - } - TypeScript.quoteBaseName = quoteBaseName; - function changePathToSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".str"; - } - TypeScript.changePathToSTR = changePathToSTR; - function changePathToDSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.str"; - } - TypeScript.changePathToDSTR = changePathToDSTR; - function changePathToTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".ts"; - } - TypeScript.changePathToTS = changePathToTS; - function changePathToDTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.ts"; - } - TypeScript.changePathToDTS = changePathToDTS; - function isRelative(path) { - return path.charAt(0) == "."; - } - TypeScript.isRelative = isRelative; - function isRooted(path) { - return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); - } - TypeScript.isRooted = isRooted; - function getRootFilePath(outFname) { - if(outFname == "") { - return outFname; - } else { - var isPath = outFname.indexOf("/") != -1; - return isPath ? filePath(outFname) : ""; - } - } - TypeScript.getRootFilePath = getRootFilePath; - function filePathComponents(fullPath) { - fullPath = switchToForwardSlashes(fullPath); - var components = getPathComponents(fullPath); - return components.slice(0, components.length - 1); - } - TypeScript.filePathComponents = filePathComponents; - function filePath(fullPath) { - var path = filePathComponents(fullPath); - return path.join("/") + "/"; - } - TypeScript.filePath = filePath; - function normalizeURL(url) { - var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; - var matches = hostDomainAndPortRegex.exec(url); - if(matches) { - var hostDomainAndPort = matches[1]; - var actualPath = matches[3]; - return hostDomainAndPort + normalizePath(actualPath); - } - return normalizePath(url); - } - TypeScript.normalizeURL = normalizeURL; - TypeScript.pathNormalizeRegExp = /\//g; - function normalizePath(path) { - path = switchToForwardSlashes(path); - var startedWithSep = path.charAt(0) === "/"; - var parts = this.getPathComponents(path); - for(var i = 0; i < parts.length; i++) { - if(parts[i] === "." || parts[i] === "") { - parts.splice(i, 1); - i--; - } - if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { - parts.splice(i - 1, 2); - i -= 2; - } - } - return (startedWithSep ? "/" : "") + parts.join("/"); - } - TypeScript.normalizePath = normalizePath; - function normalizeImportPath(path) { - return normalizePath(path); - } - TypeScript.normalizeImportPath = normalizeImportPath; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var SourceUnit = (function () { - function SourceUnit(path, content) { - this.path = path; - this.content = content; - this.referencedFiles = null; - } - SourceUnit.prototype.getText = function (start, end) { - return this.content.substring(start, end); - }; - SourceUnit.prototype.getLength = function () { - return this.content.length; - }; - return SourceUnit; - })(); - TypeScript.SourceUnit = SourceUnit; - var CompilationEnvironment = (function () { - function CompilationEnvironment(compilationSettings, ioHost) { - this.compilationSettings = compilationSettings; - this.ioHost = ioHost; - this.residentCode = []; - this.code = []; - this.inputOutputMap = []; - } - return CompilationEnvironment; - })(); - TypeScript.CompilationEnvironment = CompilationEnvironment; - var CodeResolver = (function () { - function CodeResolver(environment) { - this.environment = environment; - this.visited = { - }; - } - CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { - var resolvedFile = { - content: null, - path: referencePath - }; - var ioHost = this.environment.ioHost; - var isRelativePath = TypeScript.isRelative(referencePath); - var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); - var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); - if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { - normalizedPath += ".ts"; - } - normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); - var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); - if(!this.visited[absoluteModuleID]) { - if(isRelativePath || isRootedPath || !performSearch) { - try { - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - try { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } - } - } - TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); - resolvedFile.path = normalizedPath; - this.visited[absoluteModuleID] = true; - } catch (err) { - TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); - return false; - } - } else { - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - } - if(resolvedFile) { - resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); - TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); - resolvedFile.content = resolvedFile.content; - this.visited[absoluteModuleID] = true; - } else { - TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); - } - } - if(resolvedFile && resolvedFile.content != null) { - var rootDir = ioHost.dirName(resolvedFile.path); - var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); - var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); - var resolvedFilePath = ioHost.resolvePath(resolvedFile.path); - sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; - for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { - var fileReference = preProcessedFileInfo.referencedFiles[i]; - var normalizedPath = TypeScript.isRooted(fileReference.path) ? fileReference.path : rootDir + "/" + fileReference.path; - normalizedPath = ioHost.resolvePath(normalizedPath); - if(resolvedFilePath == normalizedPath) { - resolutionDispatcher.postResolutionError(normalizedPath, fileReference.startLine, fileReference.startCol, "Incorrect reference: File contains reference to itself."); - continue; - } - var resolutionResult = this.resolveCode(fileReference.path, rootDir, false, resolutionDispatcher); - if(!resolutionResult) { - resolutionDispatcher.postResolutionError(resolvedFilePath, fileReference.startLine, fileReference.startCol, "Incorrect reference: referenced file: \"" + fileReference.path + "\" cannot be resolved."); - } - } - for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { - var fileImport = preProcessedFileInfo.importedFiles[i]; - var resolutionResult = this.resolveCode(fileImport.path, rootDir, true, resolutionDispatcher); - if(!resolutionResult) { - resolutionDispatcher.postResolutionError(resolvedFilePath, fileImport.startLine, fileImport.startCol, "Incorrect reference: imported file: \"" + fileImport.path + "\" cannot be resolved."); - } - } - resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); - } - } - return true; - }; - return CodeResolver; - })(); - TypeScript.CodeResolver = CodeResolver; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var StyleSettings = (function () { - function StyleSettings() { - this.bitwise = false; - this.blockInCompoundStmt = false; - this.eqeqeq = false; - this.forin = false; - this.emptyBlocks = true; - this.newMustBeUsed = false; - this.requireSemi = false; - this.assignmentInCond = false; - this.eqnull = false; - this.evalOK = true; - this.innerScopeDeclEscape = true; - this.funcInLoop = true; - this.reDeclareLocal = true; - this.literalSubscript = true; - this.implicitAny = false; - } - StyleSettings.prototype.setOption = function (opt, val) { - var optExists = this[opt]; - if(optExists !== undefined) { - this[opt] = val; - return true; - } else { - return false; - } - }; - StyleSettings.prototype.parseOptions = function (str) { - var opts = str.split(";"); - for(var i = 0, len = opts.length; i < len; i++) { - var opt = opts[i]; - var val = true; - var colonIndex = opt.lastIndexOf(":"); - if(colonIndex >= 0) { - var valStr = opt.substring(colonIndex + 1); - opt = opt.substring(0, colonIndex); - if(valStr == "off") { - val = false; - } - } - if(!this.setOption(opt, val)) { - return false; - } - } - return true; - }; - return StyleSettings; - })(); - TypeScript.StyleSettings = StyleSettings; - var CompilationSettings = (function () { - function CompilationSettings() { - this.styleSettings = new StyleSettings(); - this.propagateConstants = false; - this.minWhitespace = false; - this.parseOnly = false; - this.errorRecovery = false; - this.emitComments = false; - this.watch = false; - this.exec = false; - this.resolve = true; - this.controlFlow = false; - this.printControlFlow = false; - this.controlFlowUseDef = false; - this.errorOnWith = true; - this.preprocess = true; - this.canCallDefinitionSignature = false; - this.inferPropertiesFromThisAssignment = false; - this.useDefaultLib = true; - this.codeGenTarget = TypeScript.CodeGenTarget.ES3; - this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; - this.outputOption = ""; - this.mapSourceFiles = false; - this.emitFullSourceMapPath = false; - this.generateDeclarationFiles = false; - this.useCaseSensitiveFileResolution = false; - } - CompilationSettings.prototype.setStyleOptions = function (str) { - this.styleSettings.parseOptions(str); - }; - return CompilationSettings; - })(); - TypeScript.CompilationSettings = CompilationSettings; - function getFileReferenceFromReferencePath(comment) { - var referencesRegEx = /^(\/\/\/\s*/gim; - var match = referencesRegEx.exec(comment); - if(match) { - var path = TypeScript.normalizePath(match[3]); - var adjustedPath = TypeScript.normalizePath(path); - var isResident = match.length >= 7 && match[6] == "true"; - if(isResident) { - TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); - } - return { - minChar: 0, - limChar: 0, - startLine: 0, - startCol: 0, - path: TypeScript.switchToForwardSlashes(adjustedPath), - isResident: isResident - }; - } else { - return null; - } - } - function getAdditionalDependencyPath(comment) { - var amdDependencyRegEx = /^(\/\/\/\s*/gim; - var match = amdDependencyRegEx.exec(comment); - if(match) { - var path = match[3]; - return path; - } else { - return null; - } - } - TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; - function getImplicitImport(comment) { - var implicitImportRegEx = /^(\/\/\/\s*/gim; - var match = implicitImportRegEx.exec(comment); - if(match) { - return true; - } - return false; - } - TypeScript.getImplicitImport = getImplicitImport; - function getStyleSettings(comment, styleSettings) { - var styleRegEx = /^(\/\/\/\s*/gim; - var settings = styleRegEx.exec(comment); - if(settings) { - var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/gim; - settings = settingsRegEx.exec(settings[2]); - if(settings) { - for(var i = 0; i < settings.length; i++) { - var setting = (settings[i]).split("="); - var on = "\"on\""; - switch(setting[0]) { - case "blockInCompoundStmt": - styleSettings.blockInCompoundStmt = setting[1] == on; - break; - case "eqeqeq": - styleSettings.eqeqeq = setting[1] == on; - break; - case "forin": - styleSettings.forin = setting[1] == on; - break; - case "emptyBlocks": - styleSettings.emptyBlocks = setting[1] == on; - break; - case "newMustBeUsed": - styleSettings.newMustBeUsed = setting[1] == on; - break; - case "requireSemi": - styleSettings.requireSemi = setting[1] == on; - break; - case "assignmentInCond": - styleSettings.assignmentInCond = setting[1] == on; - break; - case "eqnull": - styleSettings.eqnull = setting[1] == on; - break; - case "evalOK": - styleSettings.evalOK = setting[1] == on; - break; - case "innerScopeDeclEscape": - styleSettings.innerScopeDeclEscape = setting[1] == on; - break; - case "funcInLoop": - styleSettings.funcInLoop = setting[1] == on; - break; - case "reDeclareLocal": - styleSettings.reDeclareLocal = setting[1] == on; - break; - case "literalSubscript": - styleSettings.literalSubscript = setting[1] == on; - break; - case "implicitAny": - styleSettings.implicitAny = setting[1] == on; - break; - } - } - } - } - } - TypeScript.getStyleSettings = getStyleSettings; - function getReferencedFiles(sourceText) { - var preProcessInfo = preProcessFile(sourceText, null, false); - return preProcessInfo.referencedFiles; - } - TypeScript.getReferencedFiles = getReferencedFiles; - function preProcessFile(sourceText, options, readImportFiles) { - if (typeof options === "undefined") { options = new CompilationSettings(); } - if (typeof readImportFiles === "undefined") { readImportFiles = true; } - var scanner = new TypeScript.Scanner(); - scanner.resetComments(); - scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var tok = scanner.scan(); - var comments = []; - var comment = null; - var leftCurlies = []; - var settings = options; - var referencedFiles = []; - var importedFiles = []; - var isLibFile = false; - while(tok.tokenId != TypeScript.TokenID.EndOfFile) { - if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Equals) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Module) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.OpenParen) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.StringLiteral) { - var ref = { - minChar: scanner.startPos, - limChar: scanner.pos, - startLine: scanner.line, - startCol: scanner.col, - path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), - isResident: false - }; - importedFiles.push(ref); - } - } - } - } - } - } - if(tok.tokenId == TypeScript.TokenID.OpenBrace) { - leftCurlies.push(tok); - } - if(tok.tokenId == TypeScript.TokenID.CloseBrace) { - leftCurlies.pop(); - } - tok = scanner.scan(); - } - comments = scanner.getComments(); - for(var iComment = 0; iComment < comments.length; iComment++) { - comment = comments[iComment]; - if(!comment.isBlock) { - var referencedCode = getFileReferenceFromReferencePath(comment.getText()); - if(referencedCode) { - referencedCode.minChar = comment.startPos; - referencedCode.limChar = referencedCode.minChar + comment.value.length; - var result = { - line: -1, - col: -1 - }; - TypeScript.getSourceLineColFromMap(result, comment.startPos, scanner.lineMap); - if(result.col >= 0) { - result.col++; - } - referencedCode.startLine = result.line; - referencedCode.startCol = result.col; - referencedFiles.push(referencedCode); - } - if(settings) { - getStyleSettings(comment.getText(), settings.styleSettings); - var isNoLibRegex = /^(\/\/\/\s*/gim; - var isNoLibMatch = isNoLibRegex.exec(comment.getText()); - if(isNoLibMatch) { - isLibFile = (isNoLibMatch[3] == "true"); - } - } - } - } - return { - settings: settings, - referencedFiles: referencedFiles, - importedFiles: importedFiles, - isLibFile: isLibFile - }; - } - TypeScript.preProcessFile = preProcessFile; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var IncrementalParser = (function () { - function IncrementalParser(logger) { - this.logger = logger; - this.astLogger = new TypeScript.AstLogger(this.logger); - } - IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - if(editRange.isUnknown()) { - this.logger.log(" Bailing out because edit range is unknown"); - return null; - } - var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); - var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); - if(scope1 == null || scope2 == null) { - this.logger.log(" Bailing out because containing scopes cannot be determined"); - return null; - } - if(scope1.scopeStartAST !== scope2.scopeStartAST) { - this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength <= 0) { - this.logger.log(" Bailing out because scope has been entirely removed from new source text"); - return null; - } - return scope1; - }; - IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); - if(scope1 === null) { - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength >= newSourceText.getLength() / 2) { - this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); - return null; - } - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); - if(quickParseResult.endLexState != TypeScript.LexState.Start) { - this.logger.log(" Bailing out because scope contains unterminated comment"); - return null; - } - var scriptFragment = quickParseResult.Script; - if(scriptFragment.vars.members.length !== 0) { - this.logger.log(" Bailing out because new source text defines variables"); - return null; - } - if(scriptFragment.bod.members.length !== 1) { - this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); - return null; - } - var oldScope = scope1.scopeStartAST; - var newScope = scriptFragment.bod.members[0]; - if(oldScope.nodeType != newScope.nodeType) { - this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); - return null; - } - if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { - this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); - return null; - } - if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); - return null; - } - if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); - return null; - } - if(newScope.minChar !== 0) { - this.logger.log(" Bailing out because new function declaration does not start at position 0"); - return null; - } - if(newScope.limChar !== newScopeLength) { - this.logger.log(" Bailing out because new function declaration does not end at the new end position"); - return null; - } - return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); - }; - IncrementalParser.prototype.mergeTrees = function (updateResult) { - var _this = this; - TypeScript.timeFunction(this.logger, "mergeTrees()", function () { - var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); - _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); - _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); - _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); - _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); - }); - }; - IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { - var _this = this; - var pre = function (cur, parent, walker) { - if(cur === oldAst) { - newAst.preComments = cur.preComments; - newAst.postComments = cur.postComments; - _this.logger.log("replaced old AST node with new one in script AST"); - walker.options.stopWalk(); - return newAst; - } - if(TypeScript.isValidAstNode(cur)) { - if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - }; - IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { - var lineMap1 = script.locationInfo.lineMap; - var lineMap2 = partial.locationInfo.lineMap; - if(this.logger.information()) { - this.logger.log("lineMap1 (before):"); - this.astLogger.logLinemap(lineMap1); - this.logger.log("lineMap2 (quick parse):"); - this.astLogger.logLinemap(lineMap2); - this.logger.log("EditRange=" + editRange); - } - var i1 = 2; - var i2 = 2; - var len1 = lineMap1.length; - var len2 = lineMap2.length; - while(i1 < len1) { - if(lineMap1[i1] <= editRange.minChar) { - i1++; - } else if(lineMap1[i1] >= editRange.limChar) { - lineMap1[i1] += editRange.delta; - i1++; - } else { - if(i2 < len2) { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } else { - lineMap1.splice(i1, 1); - len1--; - } - } - } - if(i2 < len2) { - if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { - i1 = 2; - while(i1 < len1 && i2 < len2) { - if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { - i1++; - } else { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } - } - } - for(; i2 < len2; i2++) { - lineMap1.push(lineMap2[i2] + editRange.minChar); - } - } - if(this.logger.information()) { - this.logger.log("lineMap1 (after merge):"); - this.astLogger.logLinemap(lineMap1); - } - }; - IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { - var applyDelta = function (ast) { - if(ast.minChar !== -1 && ast.minChar >= start) { - ast.minChar += delta; - } - if(ast.limChar !== -1 && ast.limChar >= start) { - ast.limChar += delta; - } - }; - var applyDeltaToComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - applyDelta(comments[i]); - } - } - }; - var pre = function (cur, parent, walker) { - if(cur.limChar !== -1 && cur.limChar < start) { - walker.options.goChildren = false; - } - applyDelta(cur); - applyDeltaToComments(cur.preComments); - applyDeltaToComments(cur.postComments); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(ast, pre); - }; - return IncrementalParser; - })(); - TypeScript.IncrementalParser = IncrementalParser; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var DeclFileWriter = (function () { - function DeclFileWriter(declFile) { - this.declFile = declFile; - this.onNewLine = true; - } - DeclFileWriter.prototype.Write = function (s) { - this.declFile.Write(s); - this.onNewLine = false; - }; - DeclFileWriter.prototype.WriteLine = function (s) { - this.declFile.WriteLine(s); - this.onNewLine = true; - }; - DeclFileWriter.prototype.Close = function () { - this.declFile.Close(); - }; - return DeclFileWriter; - })(); - TypeScript.DeclFileWriter = DeclFileWriter; - var DeclarationEmitter = (function () { - function DeclarationEmitter(checker, emitOptions, errorReporter) { - this.checker = checker; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.declFile = null; - this.indenter = new TypeScript.Indenter(); - this.declarationContainerStack = []; - this.isDottedModuleName = []; - this.ignoreCallbackAst = null; - this.singleDeclFile = null; - this.varListCount = 0; - } - DeclarationEmitter.prototype.getAstDeclarationContainer = function () { - return this.declarationContainerStack[this.declarationContainerStack.length - 1]; - }; - DeclarationEmitter.prototype.emitDottedModuleName = function () { - return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; - }; - DeclarationEmitter.prototype.setDeclarationFile = function (file) { - this.declFile = new DeclFileWriter(file); - }; - DeclarationEmitter.prototype.Close = function () { - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - DeclarationEmitter.prototype.emitDeclarations = function (script) { - TypeScript.AstWalkerWithDetailCallback.walk(script, this); - }; - DeclarationEmitter.prototype.getIndentString = function (declIndent) { - if (typeof declIndent === "undefined") { declIndent = false; } - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - DeclarationEmitter.prototype.emitIndent = function () { - this.declFile.Write(this.getIndentString()); - }; - DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { - if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } - if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } - var container; - if(useDeclarationContainerTop) { - container = this.getAstDeclarationContainer(); - } else { - container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; - } - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - return false; - } - if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { - return false; - } - return true; - }; - DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { - if(this.ignoreCallbackAst) { - TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); - this.ignoreCallbackAst = null; - return false; - } else if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { - this.ignoreCallbackAst = astWithPrePostCallback; - return false; - } - return true; - }; - DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { - var result = this.getIndentString(); - var accessorString = ""; - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { - accessorString = "get "; - } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { - accessorString = "set "; - } - var container = this.getAstDeclarationContainer(); - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - result += "export "; - } - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { - result += "private "; - } - result += "static " + accessorString; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { - result += "private " + accessorString; - } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { - result += "public " + accessorString; - } else { - if(accessorString == "") { - result += typeString + " "; - } else { - result += accessorString; - } - } - } - return result; - }; - DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { - this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); - }; - DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { - if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } - return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); - }; - DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { - this.declarationContainerStack.push(ast); - }; - DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { - TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); - this.declarationContainerStack.pop(); - }; - DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { - if (typeof emitIndent === "undefined") { emitIndent = false; } - if(memberName.prefix == "{ ") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.WriteLine("{"); - this.indenter.increaseIndent(); - emitIndent = true; - } else if(memberName.prefix != "") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write(memberName.prefix); - emitIndent = false; - } - if(memberName.isString()) { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write((memberName).text); - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - this.emitTypeNamesMember(ar.entries[index], emitIndent); - if(ar.delim == "; ") { - this.declFile.WriteLine(";"); - } - } - } - if(memberName.suffix == "}") { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.Write(memberName.suffix); - } else { - this.declFile.Write(memberName.suffix); - } - }; - DeclarationEmitter.prototype.emitTypeSignature = function (type) { - var containingScope = null; - var declarationContainerAst = this.getAstDeclarationContainer(); - switch(declarationContainerAst.nodeType) { - case TypeScript.NodeType.ModuleDeclaration: - case TypeScript.NodeType.InterfaceDeclaration: - case TypeScript.NodeType.FuncDecl: - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.containedScope; - } - break; - case TypeScript.NodeType.Script: - var script = declarationContainerAst; - if(script.bod) { - containingScope = script.bod.enclosingScope; - } - break; - case TypeScript.NodeType.ClassDeclaration: - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.instanceType.containedScope; - } - break; - default: - TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); - } - var typeNameMembers = type.getScopedTypeNameEx(containingScope); - this.emitTypeNamesMember(typeNameMembers); - }; - DeclarationEmitter.prototype.emitComment = function (comment) { - var text = comment.getText(); - if(this.declFile.onNewLine) { - this.emitIndent(); - } else if(!comment.isBlockComment) { - this.declFile.WriteLine(""); - this.emitIndent(); - } - this.declFile.Write(text[0]); - for(var i = 1; i < text.length; i++) { - this.declFile.WriteLine(""); - this.emitIndent(); - this.declFile.Write(text[i]); - } - if(comment.endsLine || !comment.isBlockComment) { - this.declFile.WriteLine(""); - } else { - this.declFile.Write(" "); - } - }; - DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { - if (typeof endLine === "undefined") { endLine = true; } - if(!this.emitOptions.emitComments) { - return; - } - var declComments = astOrSymbol.getDocComments(); - if(declComments.length > 0) { - for(var i = 0; i < declComments.length; i++) { - this.emitComment(declComments[i]); - } - if(endLine) { - if(!this.declFile.onNewLine) { - this.declFile.WriteLine(""); - } - } else { - if(this.declFile.onNewLine) { - this.emitIndent(); - } - } - } - }; - DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { - if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { - var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - this.emitDeclarationComments(varDecl); - if(!interfaceMember) { - if(this.varListCount >= 0) { - this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); - this.varListCount = -this.varListCount; - } - this.declFile.Write(varDecl.id.text); - } else { - this.emitIndent(); - this.declFile.Write(varDecl.id.text); - if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("?"); - } - } - var type = null; - if(varDecl.typeExpr && varDecl.typeExpr.type) { - type = varDecl.typeExpr.type; - } else if(varDecl.sym) { - type = (varDecl.sym).getType(); - if(type == this.checker.anyType) { - type = null; - } - } - if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(type); - } - if(this.varListCount > 0) { - this.varListCount--; - } else if(this.varListCount < 0) { - this.varListCount++; - } - if(this.varListCount < 0) { - this.declFile.Write(", "); - } else { - this.declFile.WriteLine(";"); - } - } - return false; - }; - DeclarationEmitter.prototype.BlockCallback = function (pre, block) { - if(!block.isStatementBlock) { - if(pre) { - this.varListCount = block.statements.members.length; - } else { - this.varListCount = 0; - } - return true; - } - return false; - }; - DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { - this.emitDeclarationComments(argDecl, false); - this.declFile.Write(argDecl.id.text); - if(argDecl.isOptionalArg()) { - this.declFile.Write("?"); - } - if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - }; - DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { - if(!pre) { - return false; - } - if(funcDecl.isAccessor()) { - return this.emitPropertyAccessorSignature(funcDecl); - } - var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - if(funcDecl.bod) { - if(funcDecl.isConstructor) { - if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { - return false; - } - } else { - if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - return false; - } - } - } else if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - var signatures = funcDecl.type.call.signatures; - var firstSignature = signatures[0].declAST; - if(firstSignature.bod) { - firstSignature = signatures[1].declAST; - } - if(firstSignature != funcDecl) { - return false; - } - } - if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { - return false; - } - this.emitDeclarationComments(funcDecl); - if(funcDecl.isConstructor) { - this.emitIndent(); - this.declFile.Write("constructor"); - } else { - var id = funcDecl.getNameText(); - if(!isInterfaceMember) { - this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); - if(id != "__missing" || !funcDecl.name || !funcDecl.name.isMissing()) { - this.declFile.Write(id); - } else if(funcDecl.isConstructMember()) { - this.declFile.Write("new"); - } - } else { - this.emitIndent(); - if(funcDecl.isConstructMember()) { - this.declFile.Write("new"); - } else if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { - this.declFile.Write(id); - if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("? "); - } - } - } - } - if(!funcDecl.isIndexerMember()) { - this.declFile.Write("("); - } else { - this.declFile.Write("["); - } - this.indenter.increaseIndent(); - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - this.emitArgDecl(argDecl, funcDecl); - if(i < (argsLen - 1)) { - this.declFile.Write(", "); - } - } - } - if(funcDecl.variableArgList) { - var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; - if(funcDecl.arguments.members.length > 1) { - this.declFile.Write(", ..."); - } else { - this.declFile.Write("..."); - } - this.emitArgDecl(lastArg, funcDecl); - } - this.indenter.decreaseIndent(); - if(!funcDecl.isIndexerMember()) { - this.declFile.Write(")"); - } else { - this.declFile.Write("]"); - } - if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(funcDecl.signature.returnType.type); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { - if(bases && (bases.members.length > 0)) { - this.declFile.Write(" " + qual + " "); - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = baseExpr.type.symbol; - var baseType = baseExpr.type; - if(i > 0) { - this.declFile.Write(", "); - } - this.emitTypeSignature(baseType); - } - } - }; - DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { - var accessorSymbol = funcDecl.accessorSymbol; - if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { - return false; - } - this.emitDeclarationComments(accessorSymbol); - this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); - this.declFile.Write(funcDecl.name.text); - var propertyType = accessorSymbol.getType(); - if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { - this.declFile.Write(" : "); - this.emitTypeSignature(propertyType); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { - this.emitDeclarationComments(argDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); - this.declFile.Write(argDecl.id.text); - if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - this.declFile.WriteLine(";"); - } - } - } - }; - DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { - return false; - } - if(pre) { - var className = classDecl.name.text; - this.emitDeclarationComments(classDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); - this.declFile.Write(className); - this.emitBaseList(classDecl.extendsList, "extends"); - this.emitBaseList(classDecl.implementsList, "implements"); - this.declFile.WriteLine(" {"); - this.pushDeclarationContainer(classDecl); - this.indenter.increaseIndent(); - if(classDecl.constructorDecl) { - this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); - } - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(classDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { - return false; - } - if(pre) { - var interfaceName = interfaceDecl.name.text; - this.emitDeclarationComments(interfaceDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); - this.declFile.Write(interfaceName); - this.emitBaseList(interfaceDecl.extendsList, "extends"); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - this.pushDeclarationContainer(interfaceDecl); - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(interfaceDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { - if(pre) { - if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { - this.emitDeclarationComments(importDecl); - this.emitIndent(); - this.declFile.Write("import "); - this.declFile.Write(importDecl.id.text + " = "); - if(importDecl.isDynamicImport) { - this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); - } else { - this.declFile.WriteLine(importDecl.getAliasName() + ";"); - } - } - } - return false; - }; - DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { - if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { - return false; - } - this.emitDeclarationComments(moduleDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); - this.declFile.WriteLine(moduleDecl.name.text + " {"); - this.indenter.increaseIndent(); - var membersLen = moduleDecl.members.members.length; - for(var j = 1; j < membersLen; j++) { - var memberDecl = moduleDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.emitDeclarationComments(memberDecl); - this.emitIndent(); - this.declFile.WriteLine((memberDecl).id.text + ","); - } else { - TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); - } - } - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - return false; - }; - DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - if(pre) { - if(!this.emitOptions.outputMany) { - this.singleDeclFile = this.declFile; - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - try { - this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - } - this.pushDeclarationContainer(moduleDecl); - } else { - if(!this.emitOptions.outputMany) { - TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - this.declFile = this.singleDeclFile; - } - this.popDeclarationContainer(moduleDecl); - } - } - return true; - } - if(moduleDecl.isEnum()) { - if(pre) { - this.emitEnumSignature(moduleDecl); - } - return false; - } - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { - return false; - } - if(pre) { - if(this.emitDottedModuleName()) { - this.dottedModuleEmit += "."; - } else { - this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); - } - this.dottedModuleEmit += moduleDecl.name.text; - var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); - var moduleDeclComments = moduleDecl.getDocComments(); - isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); - this.isDottedModuleName.push(isCurrentModuleDotted); - this.pushDeclarationContainer(moduleDecl); - if(!isCurrentModuleDotted) { - this.emitDeclarationComments(moduleDecl); - this.declFile.Write(this.dottedModuleEmit); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - } - } else { - if(!this.emitDottedModuleName()) { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - this.popDeclarationContainer(moduleDecl); - this.isDottedModuleName.pop(); - } - return true; - }; - DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { - if(pre) { - if(this.emitOptions.outputMany) { - for(var i = 0; i < script.referencedFiles.length; i++) { - var referencePath = script.referencedFiles[i].path; - var declareFileName; - if(TypeScript.isRooted(referencePath)) { - declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); - } else { - declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); - } - this.declFile.WriteLine('/// '); - } - } - this.pushDeclarationContainer(script); - } else { - this.popDeclarationContainer(script); - } - return true; - }; - DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { - return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); - }; - return DeclarationEmitter; - })(); - TypeScript.DeclarationEmitter = DeclarationEmitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (UpdateUnitKind) { - UpdateUnitKind._map = []; - UpdateUnitKind._map[0] = "Unknown"; - UpdateUnitKind.Unknown = 0; - UpdateUnitKind._map[1] = "NoEdits"; - UpdateUnitKind.NoEdits = 1; - UpdateUnitKind._map[2] = "EditsInsideSingleScope"; - UpdateUnitKind.EditsInsideSingleScope = 2; - })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); - var UpdateUnitKind = TypeScript.UpdateUnitKind; - var ScriptEditRange = (function () { - function ScriptEditRange(minChar, limChar, delta) { - this.minChar = minChar; - this.limChar = limChar; - this.delta = delta; - } - ScriptEditRange.unknown = function unknown() { - return new ScriptEditRange(-1, -1, -1); - }; - ScriptEditRange.prototype.isUnknown = function () { - return this.minChar === -1 && this.limChar === -1 && this.delta === -1; - }; - ScriptEditRange.prototype.containsPosition = function (pos) { - return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); - }; - ScriptEditRange.prototype.toString = function () { - return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; - }; - return ScriptEditRange; - })(); - TypeScript.ScriptEditRange = ScriptEditRange; - var UpdateUnitResult = (function () { - function UpdateUnitResult(kind, unitIndex, script1, script2) { - this.kind = kind; - this.unitIndex = unitIndex; - this.script1 = script1; - this.script2 = script2; - this.scope1 = null; - this.scope2 = null; - this.editRange = null; - this.parseErrors = []; - } - UpdateUnitResult.noEdits = function noEdits(unitIndex) { - return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); - }; - UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); - result.parseErrors = parseErrors; - return result; - }; - UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); - result.scope1 = scope1; - result.scope2 = scope2; - result.editRange = editRange; - result.parseErrors = parseErrors; - return result; - }; - return UpdateUnitResult; - })(); - TypeScript.UpdateUnitResult = UpdateUnitResult; - var ErrorEntry = (function () { - function ErrorEntry(unitIndex, minChar, limChar, message) { - this.unitIndex = unitIndex; - this.minChar = minChar; - this.limChar = limChar; - this.message = message; - } - return ErrorEntry; - })(); - TypeScript.ErrorEntry = ErrorEntry; - TypeScript.defaultSettings = new TypeScript.CompilationSettings(); - var TypeScriptCompiler = (function () { - function TypeScriptCompiler(errorOutput, logger, settings) { - if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } - if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } - this.errorOutput = errorOutput; - this.logger = logger; - this.settings = settings; - this.parser = new TypeScript.Parser(); - this.typeFlow = null; - this.scripts = new TypeScript.ASTList(); - this.units = new Array(); - this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); - this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); - this.errorReporter.parser = this.parser; - this.initTypeChecker(this.errorOutput); - this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; - this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; - this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; - this.emitSettings = new TypeScript.EmitOptions(this.settings); - TypeScript.codeGenTarget = settings.codeGenTarget; - } - TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { - return TypeScript.timeFunction(this.logger, funcDescription, func); - }; - TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { - this.persistentTypeState.refreshPersistentState(); - this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); - this.typeChecker.errorReporter = this.errorReporter; - this.typeChecker.checkControlFlow = this.settings.controlFlow; - this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; - this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; - this.typeChecker.errorsOnWith = this.settings.errorOnWith; - this.typeChecker.styleSettings = this.settings.styleSettings; - this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; - this.errorReporter.checker = this.typeChecker; - this.setErrorOutput(this.errorOutput); - }; - TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { - this.errorOutput = outerr; - this.errorReporter.setErrOut(outerr); - this.parser.outfile = outerr; - }; - TypeScriptCompiler.prototype.emitCommentsToOutput = function () { - this.emitSettings = new TypeScript.EmitOptions(this.settings); - }; - TypeScriptCompiler.prototype.setErrorCallback = function (fn) { - this.parser.errorCallback = fn; - }; - TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { - return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); - }; - TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("updateSourceUnit(" + filename + ")", function () { - var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); - return _this.applyUpdateResult(updateResult); - }); - }; - TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { - switch(updateResult.kind) { - case UpdateUnitKind.NoEdits: - return false; - case UpdateUnitKind.Unknown: - this.scripts.members[updateResult.unitIndex] = updateResult.script2; - this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; - for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { - var e = updateResult.parseErrors[i]; - if(this.parser.errorCallback) { - this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); - } - } - return true; - case UpdateUnitKind.EditsInsideSingleScope: - new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); - return true; - } - }; - TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { - for(var i = 0, len = _this.units.length; i < len; i++) { - if(_this.units[i].filename == filename) { - if((_this.scripts.members[i]).isResident) { - return UpdateUnitResult.noEdits(i); - } - if(setRecovery) { - _this.parser.setErrorRecovery(null); - } - var updateResult; - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var svErrorCallback = _this.parser.errorCallback; - if(svErrorCallback) { - _this.parser.errorCallback = errorCapture; - } - var oldScript = _this.scripts.members[i]; - var newScript = _this.parser.parse(sourceText, filename, i); - if(svErrorCallback) { - _this.parser.errorCallback = svErrorCallback; - } - updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); - return updateResult; - } - } - throw new Error("Unknown file \"" + filename + "\""); - }); - }; - TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { - if (typeof keepResident === "undefined") { keepResident = false; } - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); - }; - TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - var _this = this; - return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { - var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); - script.referencedFiles = referencedFiles; - script.isResident = keepResident; - _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); - var index = _this.units.length; - _this.units[index] = script.locationInfo; - _this.typeChecker.collectTypes(script); - _this.scripts.append(script); - return script; - }); - }; - TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { - return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); - }; - TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { - this.parser.setErrorRecovery(this.errorOutput); - var script = this.parser.parse(sourceText, filename, 0); - var index = this.units.length; - this.units[index] = script.locationInfo; - this.typeChecker.collectTypes(script); - this.scripts.append(script); - }; - TypeScriptCompiler.prototype.typeCheck = function () { - var _this = this; - return this.timeFunction("typeCheck()", function () { - var binder = new TypeScript.Binder(_this.typeChecker); - _this.typeChecker.units = _this.units; - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); - _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); - var i = 0; - var script = null; - var len = _this.scripts.members.length; - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.typeCheck(script); - script.hasBeenTypeChecked = true; - } - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - len = _this.scripts.members.length; - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.typeCheck(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { - function cleanASTType(ast, parent) { - ast.type = null; - if(ast.nodeType == TypeScript.NodeType.VarDecl) { - var vardecl = ast; - vardecl.sym = null; - } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - var argdecl = ast; - argdecl.sym = null; - } else if(ast.nodeType == TypeScript.NodeType.Name) { - var name = ast; - name.sym = null; - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcdecl = ast; - funcdecl.signature = null; - funcdecl.freeVariables = new Array(); - funcdecl.symbols = null; - funcdecl.accessorSymbol = null; - funcdecl.scopeType = null; - } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var modDecl = ast; - modDecl.mod = null; - } else if(ast.nodeType == TypeScript.NodeType.With) { - (ast).withSym = null; - } else if(ast.nodeType == TypeScript.NodeType.Catch) { - (ast).containedScope = null; - } else if(ast.nodeType === TypeScript.NodeType.Script) { - (ast).externallyVisibleImportedSymbols = []; - } - return ast; - } - TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); - }; - TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { - var _this = this; - return this.timeFunction("cleanTypesForReTypeCheck()", function () { - for(var i = 0, len = _this.scripts.members.length; i < len; i++) { - var script = _this.scripts.members[i]; - if((script).isResident) { - continue; - } - _this.cleanASTTypesForReTypeCheck(script); - _this.typeChecker.collectTypes(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { - return this.timeFunction("attemptIncrementalTypeCheck()", function () { - return false; - }); - }; - TypeScriptCompiler.prototype.reTypeCheck = function () { - var _this = this; - return this.timeFunction("reTypeCheck()", function () { - TypeScript.CompilerDiagnostics.analysisPass++; - _this.initTypeChecker(_this.errorOutput); - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - _this.cleanTypesForReTypeCheck(); - return _this.typeCheck(); - }); - }; - TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(!script.isDeclareFile && script.topLevelMod != null) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { - var commonComponents = []; - var commonComponentsLength = -1; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(script.emitRequired(this.emitSettings)) { - var fileName = script.locationInfo.filename; - var fileComponents = TypeScript.filePathComponents(fileName); - if(commonComponentsLength == -1) { - commonComponents = fileComponents; - commonComponentsLength = commonComponents.length; - } else { - var updatedPath = false; - for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { - if(commonComponents[j] != fileComponents[j]) { - commonComponentsLength = j; - updatedPath = true; - if(j == 0) { - this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); - return; - } - break; - } - } - if(!updatedPath && fileComponents.length < commonComponentsLength) { - commonComponentsLength = fileComponents.length; - } - } - } - } - this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; - if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { - this.emitSettings.outputOption += "/"; - } - }; - TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { - this.emitSettings.ioHost = ioHost; - if(this.emitSettings.outputOption == "") { - this.emitSettings.outputMany = true; - this.emitSettings.commonDirectoryPath = ""; - return; - } - this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); - if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = true; - } else if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = false; - } else { - this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); - } - if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { - this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); - } - if(this.emitSettings.outputMany) { - this.updateCommonDirectoryPath(); - } - }; - TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { - if(this.emitSettings.outputMany) { - return this.outputScriptToUTF8(script); - } else { - return this.outputScriptsToUTF8((this.scripts.members)); - } - }; - TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { - return TypeScript.getDeclareFilePath(fileName); - }; - TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { - if(!this.settings.generateDeclarationFiles) { - return false; - } - if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { - return false; - } - return true; - }; - TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { - if(!this.canEmitDeclarations(script)) { - return null; - } - if(!declarationEmitter) { - var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); - var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); - declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); - declarationEmitter.setDeclarationFile(declareFile); - } - declarationEmitter.emitDeclarations(script); - if(!reuseEmitter) { - declarationEmitter.Close(); - return null; - } else { - return declarationEmitter; - } - }; - TypeScriptCompiler.prototype.emitDeclarations = function () { - if(!this.canEmitDeclarations()) { - return; - } - if(this.errorReporter.hasErrors) { - return; - } - if(this.scripts.members.length == 0) { - return; - } - var declarationEmitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || declarationEmitter == null) { - declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); - } else { - this.emitDeclarationsUnit(script, true, declarationEmitter); - } - } - if(declarationEmitter) { - declarationEmitter.Close(); - } - }; - TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { - if(wholeFileNameReplaced) { - return fileName; - } else { - var splitFname = fileName.split("."); - splitFname.pop(); - return splitFname.join(".") + extension; - } - }; - TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); - }; - TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter, inputOutputMapper) { - if(!script.emitRequired(this.emitSettings)) { - return null; - } - var fname = script.locationInfo.filename; - if(!emitter) { - var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); - var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); - if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter, this.settings.emitFullSourceMapPath)); - } - if(inputOutputMapper) { - inputOutputMapper(script.locationInfo.unitIndex, outFname); - } - } else if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter, this.settings.emitFullSourceMapPath)); - } - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - if(!reuseEmitter) { - emitter.Close(); - return null; - } else { - return emitter; - } - }; - TypeScriptCompiler.prototype.emit = function (ioHost, inputOutputMapper) { - this.parseEmitOption(ioHost); - var emitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || emitter == null) { - emitter = this.emitUnit(script, !this.emitSettings.outputMany, null, inputOutputMapper); - } else { - this.emitUnit(script, true, emitter); - } - } - if(emitter) { - emitter.Close(); - } - }; - TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { - if(this.settings.mapSourceFiles) { - throw Error("Cannot generate source map"); - } - if(this.settings.generateDeclarationFiles) { - throw Error("Cannot generate declaration files"); - } - if(this.settings.outputOption != "") { - throw Error("Cannot parse output option"); - } - var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); - ; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - } - }; - TypeScriptCompiler.prototype.emitAST = function (ioHost) { - this.parseEmitOption(ioHost); - var outFile = null; - var context = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || context == null) { - var fname = this.units[i].filename; - var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); - }; - var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); - outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - context = new TypeScript.PrintContext(outFile, this.parser); - } - TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); - if(this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - } - if(!this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - }; - TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { - return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); - }; - TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { - for(var i = 0, len = scripts.length; i < len; i++) { - var script = scripts[i]; - if(this.outputScriptToUTF8(script)) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitSettings.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return TypeScriptCompiler; - })(); - TypeScript.TypeScriptCompiler = TypeScriptCompiler; - var ScopeEntry = (function () { - function ScopeEntry(name, type, sym) { - this.name = name; - this.type = type; - this.sym = sym; - } - return ScopeEntry; - })(); - TypeScript.ScopeEntry = ScopeEntry; - var ScopeTraversal = (function () { - function ScopeTraversal(compiler) { - this.compiler = compiler; - } - ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { - if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { - return enclosingScopeContext.getObjectLiteralScope(); - } else if(enclosingScopeContext.isMemberCompletion) { - if(enclosingScopeContext.useFullAst) { - return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); - } else { - return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); - } - } else { - return enclosingScopeContext.getScope(); - } - }; - ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext, getPrettyTypeName) { - var scope = this.getScope(enclosingScopeContext); - if(scope == null) { - return []; - } - var inScopeNames = new TypeScript.StringHashTable(); - var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); - for(var i = 0; i < allSymbolNames.length; i++) { - var name = allSymbolNames[i]; - if(name == TypeScript.globalId || name == "_Core" || name == "_element") { - continue; - } - inScopeNames.add(name, ""); - } - var svModuleDecl = this.compiler.typeChecker.currentModDecl; - this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; - var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope, getPrettyTypeName); - this.compiler.typeChecker.currentModDecl = svModuleDecl; - return result; - }; - ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope, getPrettyTypeName) { - var result = []; - var enclosingScope = enclosingScopeContext.getScope(); - for(var i = 0; i < allNames.length; i++) { - var name = allNames[i]; - var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; - var symbol = scope.find(name, publicsOnly, false); - if(symbol == null) { - symbol = scope.find(name, publicsOnly, true); - } - var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; - if(symbol) { - if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { - var getPrettyOverload = getPrettyTypeName && symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl; - var type = symbol.getType(); - var typeName = type ? type.getScopedTypeName(enclosingScope, getPrettyOverload) : ""; - result.push(new ScopeEntry(name, typeName, symbol)); - } - } else { - if(name == "true" || name == "false") { - result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); - } - } - } - return result; - }; - return ScopeTraversal; - })(); - TypeScript.ScopeTraversal = ScopeTraversal; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (CompilerDiagnostics) { - CompilerDiagnostics.debug = false; - CompilerDiagnostics.diagnosticWriter = null; - CompilerDiagnostics.analysisPass = 0; - function Alert(output) { - if(CompilerDiagnostics.diagnosticWriter) { - CompilerDiagnostics.diagnosticWriter.Alert(output); - } - } - CompilerDiagnostics.Alert = Alert; - function debugPrint(s) { - if(CompilerDiagnostics.debug) { - Alert(s); - } - } - CompilerDiagnostics.debugPrint = debugPrint; - function assert(condition, s) { - if(CompilerDiagnostics.debug) { - if(!condition) { - Alert(s); - } - } - } - CompilerDiagnostics.assert = assert; - })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); - var CompilerDiagnostics = TypeScript.CompilerDiagnostics; - var NullLogger = (function () { - function NullLogger() { } - NullLogger.prototype.information = function () { - return false; - }; - NullLogger.prototype.debug = function () { - return false; - }; - NullLogger.prototype.warning = function () { - return false; - }; - NullLogger.prototype.error = function () { - return false; - }; - NullLogger.prototype.fatal = function () { - return false; - }; - NullLogger.prototype.log = function (s) { - }; - return NullLogger; - })(); - TypeScript.NullLogger = NullLogger; - var LoggerAdapter = (function () { - function LoggerAdapter(logger) { - this.logger = logger; - this._information = this.logger.information(); - this._debug = this.logger.debug(); - this._warning = this.logger.warning(); - this._error = this.logger.error(); - this._fatal = this.logger.fatal(); - } - LoggerAdapter.prototype.information = function () { - return this._information; - }; - LoggerAdapter.prototype.debug = function () { - return this._debug; - }; - LoggerAdapter.prototype.warning = function () { - return this._warning; - }; - LoggerAdapter.prototype.error = function () { - return this._error; - }; - LoggerAdapter.prototype.fatal = function () { - return this._fatal; - }; - LoggerAdapter.prototype.log = function (s) { - this.logger.log(s); - }; - return LoggerAdapter; - })(); - TypeScript.LoggerAdapter = LoggerAdapter; - var BufferedLogger = (function () { - function BufferedLogger() { - this.logContents = []; - } - BufferedLogger.prototype.information = function () { - return false; - }; - BufferedLogger.prototype.debug = function () { - return false; - }; - BufferedLogger.prototype.warning = function () { - return false; - }; - BufferedLogger.prototype.error = function () { - return false; - }; - BufferedLogger.prototype.fatal = function () { - return false; - }; - BufferedLogger.prototype.log = function (s) { - this.logContents.push(s); - }; - return BufferedLogger; - })(); - TypeScript.BufferedLogger = BufferedLogger; - function timeFunction(logger, funcDescription, func) { - var start = +new Date(); - var result = func(); - var end = +new Date(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); - return result; - } - TypeScript.timeFunction = timeFunction; - function stringToLiteral(value, length) { - var result = ""; - var addChar = function (index) { - var ch = value.charCodeAt(index); - switch(ch) { - case 0x09: - result += "\\t"; - break; - case 0x0a: - result += "\\n"; - break; - case 0x0b: - result += "\\v"; - break; - case 0x0c: - result += "\\f"; - break; - case 0x0d: - result += "\\r"; - break; - case 0x22: - result += "\\\""; - break; - case 0x27: - result += "\\\'"; - break; - case 0x5c: - result += "\\"; - break; - default: - result += value.charAt(index); - } - }; - var tooLong = (value.length > length); - if(tooLong) { - var mid = length >> 1; - for(var i = 0; i < mid; i++) { - addChar(i); - } - result += "(...)"; - for(var i = value.length - mid; i < value.length; i++) { - addChar(i); - } - } else { - length = value.length; - for(var i = 0; i < length; i++) { - addChar(i); - } - } - return result; - } - TypeScript.stringToLiteral = stringToLiteral; -})(TypeScript || (TypeScript = {})); -var IOUtils; -(function (IOUtils) { - function createDirectoryStructure(ioHost, dirName) { - if(ioHost.directoryExists(dirName)) { - return; - } - var parentDirectory = ioHost.dirName(dirName); - if(parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - function throwIOError(message, error) { - var errorMessage = message; - if(error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; - var BufferedTextWriter = (function () { - function BufferedTextWriter(writer, capacity) { - if (typeof capacity === "undefined") { capacity = 1024; } - this.writer = writer; - this.capacity = capacity; - this.buffer = ""; - } - BufferedTextWriter.prototype.Write = function (str) { - this.buffer += str; - if(this.buffer.length >= this.capacity) { - this.writer.Write(this.buffer); - this.buffer = ""; - } - }; - BufferedTextWriter.prototype.WriteLine = function (str) { - this.Write(str + '\r\n'); - }; - BufferedTextWriter.prototype.Close = function () { - this.writer.Write(this.buffer); - this.writer.Close(); - this.buffer = null; - }; - return BufferedTextWriter; - })(); - IOUtils.BufferedTextWriter = BufferedTextWriter; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - function getStreamObject() { - if(streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - var args = []; - for(var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { - streamObj.Charset = 'unicode'; - } else if(bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { - streamObj.Charset = 'utf-8'; - } - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - while(true) { - if(fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - if(rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if(fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - }finally { - if(streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || { - }; - function filesInFolder(folder, root) { - var paths = []; - var fc; - if(options.recursive) { - fc = new Enumerator(folder.subfolders); - for(; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - fc = new Enumerator(folder.files); - for(; !fc.atEnd(); fc.moveNext()) { - if(!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - return paths; - } - var folder = fso.GetFolder(path); - var paths = []; - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch(buffer[0]) { - case 0xFE: - if(buffer[1] == 0xFF) { - var i = 0; - while((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 0xFF: - if(buffer[1] == 0xFE) { - return buffer.toString("ucs2", 2); - } - break; - case 0xEF: - if(buffer[1] == 0xBB) { - return buffer.toString("utf8", 3); - } - } - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if(stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if(stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 0775); - } - } - mkdirRecursiveSync(_path.dirname(path)); - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return new IOUtils.BufferedTextWriter({ - Write: function (str) { - _fs.writeSync(fd, str); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }); - }, - dir: function dir(path, spec, options) { - options = options || { - }; - function filesInFolder(folder) { - var paths = []; - var files = _fs.readdirSync(folder); - for(var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if(options.recursive && stat.isDirectory()) { - paths = paths.concat(filesInFolder(folder + "/" + files[i])); - } else if(stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - return paths; - } - return filesInFolder(path); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - while(true) { - if(_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - if(rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - var fileChanged = function (curr, prev) { - if(!firstRun) { - if(curr.mtime < prev.mtime) { - return; - } - _fs.unwatchFile(filename, fileChanged); - if(!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { - persistent: true, - interval: 500 - }, fileChanged); - }; - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; - if(typeof ActiveXObject === "function") { - return getWindowsScriptHostIO(); - } else if(typeof require === "function") { - return getNodeIO(); - } else { - return null; - } -})(); -var OptionsParser = (function () { - function OptionsParser(host) { - this.host = host; - this.DEFAULT_SHORT_FLAG = "-"; - this.DEFAULT_LONG_FLAG = "--"; - this.unnamed = []; - this.options = []; - } - OptionsParser.prototype.findOption = function (arg) { - for(var i = 0; i < this.options.length; i++) { - if(arg === this.options[i].short || arg === this.options[i].name) { - return this.options[i]; - } - } - return null; - }; - OptionsParser.prototype.printUsage = function () { - this.host.printLine("Syntax: tsc [options] [file ..]"); - this.host.printLine(""); - this.host.printLine("Examples: tsc hello.ts"); - this.host.printLine(" tsc --out foo.js foo.ts"); - this.host.printLine(" tsc @args.txt"); - this.host.printLine(""); - this.host.printLine("Options:"); - var output = []; - var maxLength = 0; - this.options = this.options.sort(function (a, b) { - var aName = a.name.toLowerCase(); - var bName = b.name.toLowerCase(); - if(aName > bName) { - return 1; - } else if(aName < bName) { - return -1; - } else { - return 0; - } - }); - for(var i = 0; i < this.options.length; i++) { - var option = this.options[i]; - if(option.experimental) { - continue; - } - if(!option.usage) { - break; - } - var usageString = " "; - var type = option.type ? " " + option.type.toUpperCase() : ""; - if(option.short) { - usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; - } - usageString += this.DEFAULT_LONG_FLAG + option.name + type; - output.push([ - usageString, - option.usage - ]); - if(usageString.length > maxLength) { - maxLength = usageString.length; - } - } - output.push([ - " @", - "Insert command line options and files from a file." - ]); - for(var i = 0; i < output.length; i++) { - this.host.printLine(output[i][0] + (new Array(maxLength - output[i][0].length + 3)).join(" ") + output[i][1]); - } - }; - OptionsParser.prototype.option = function (name, config, short) { - if(!config) { - config = short; - short = null; - } - config.name = name; - config.short = short; - config.flag = false; - this.options.push(config); - }; - OptionsParser.prototype.flag = function (name, config, short) { - if(!config) { - config = short; - short = null; - } - config.name = name; - config.short = short; - config.flag = true; - this.options.push(config); - }; - OptionsParser.prototype.parseString = function (argString) { - var position = 0; - var tokens = argString.match(/\s+|"|[^\s"]+/g); - function peek() { - return tokens[position]; - } - function consume() { - return tokens[position++]; - } - function consumeQuotedString() { - var value = ''; - consume(); - var token = peek(); - while(token && token !== '"') { - consume(); - value += token; - token = peek(); - } - consume(); - return value; - } - var args = []; - var currentArg = ''; - while(position < tokens.length) { - var token = peek(); - if(token === '"') { - currentArg += consumeQuotedString(); - } else if(token.match(/\s/)) { - if(currentArg.length > 0) { - args.push(currentArg); - currentArg = ''; - } - consume(); - } else { - consume(); - currentArg += token; - } - } - if(currentArg.length > 0) { - args.push(currentArg); - } - this.parse(args); - }; - OptionsParser.prototype.parse = function (args) { - var position = 0; - function consume() { - return args[position++]; - } - while(position < args.length) { - var current = consume(); - var match = current.match(/^(--?|@)(.*)/); - var value = null; - if(match) { - if(match[1] === '@') { - this.parseString(this.host.readFile(match[2])); - } else { - var arg = match[2]; - var option = this.findOption(arg); - if(option === null) { - this.host.printLine("Unknown option '" + arg + "'"); - this.host.printLine("Use the '--help' flag to see options"); - } else { - if(!option.flag) { - value = consume(); - } - option.set(value); - } - } - } else { - this.unnamed.push(current); - } - } - }; - return OptionsParser; -})(); -var ErrorReporter = (function () { - function ErrorReporter(ioHost) { - this.ioHost = ioHost; - this.hasErrors = false; - } - ErrorReporter.prototype.Write = function (s) { - this.hasErrors = true; - this.ioHost.stderr.Write(s); - }; - ErrorReporter.prototype.WriteLine = function (s) { - this.hasErrors = true; - this.ioHost.stderr.WriteLine(s); - }; - ErrorReporter.prototype.Close = function () { - }; - ErrorReporter.prototype.reset = function () { - this.hasErrors = false; - }; - return ErrorReporter; -})(); -var CommandLineHost = (function () { - function CommandLineHost(compilationSettings, errorReporter) { - this.compilationSettings = compilationSettings; - this.errorReporter = errorReporter; - this.pathMap = { - }; - this.resolvedPaths = { - }; - } - CommandLineHost.prototype.getPathIdentifier = function (path) { - return this.compilationSettings.useCaseSensitiveFileResolution ? path : path.toLocaleUpperCase(); - }; - CommandLineHost.prototype.isResolved = function (path) { - return this.resolvedPaths[this.getPathIdentifier(this.pathMap[path])] != undefined; - }; - CommandLineHost.prototype.resolveCompilationEnvironment = function (preEnv, resolver, traceDependencies) { - var _this = this; - var resolvedEnv = new TypeScript.CompilationEnvironment(preEnv.compilationSettings, preEnv.ioHost); - var nCode = preEnv.code.length; - var path = ""; - var postResolutionError = function (errorFile, errorMessage) { - _this.errorReporter(errorFile + (errorMessage == "" ? "" : ": " + errorMessage)); - }; - var resolutionDispatcher = { - postResolutionError: function (errorFile, line, col, errorMessage) { - _this.errorReporter(errorFile + "(" + line + "," + col + ") " + (errorMessage == "" ? "" : ": " + errorMessage)); - }, - postResolution: function (path, code) { - var pathId = _this.getPathIdentifier(path); - if(!_this.resolvedPaths[pathId]) { - resolvedEnv.code.push(code); - _this.resolvedPaths[pathId] = true; - } - } - }; - for(var i = 0; i < nCode; i++) { - path = TypeScript.switchToForwardSlashes(preEnv.ioHost.resolvePath(preEnv.code[i].path)); - this.pathMap[preEnv.code[i].path] = path; - resolver.resolveCode(path, "", false, resolutionDispatcher); - } - return resolvedEnv; - }; - return CommandLineHost; -})(); -var BatchCompiler = (function () { - function BatchCompiler(ioHost) { - this.ioHost = ioHost; - this.resolvedEnvironment = null; - this.compilerVersion = "0.8.3.0"; - this.printedVersion = false; - this.errorReporter = null; - this.compilationSettings = new TypeScript.CompilationSettings(); - this.compilationEnvironment = new TypeScript.CompilationEnvironment(this.compilationSettings, this.ioHost); - this.errorReporter = new ErrorReporter(this.ioHost); - } - BatchCompiler.prototype.resolve = function () { - var _this = this; - var resolver = new TypeScript.CodeResolver(this.compilationEnvironment); - var commandLineHost = new CommandLineHost(this.compilationSettings, function (err) { - return _this.errorReporter.WriteLine(err); - }); - var ret = commandLineHost.resolveCompilationEnvironment(this.compilationEnvironment, resolver, true); - for(var i = 0; i < this.compilationEnvironment.code.length; i++) { - if(!commandLineHost.isResolved(this.compilationEnvironment.code[i].path)) { - var path = this.compilationEnvironment.code[i].path; - if(!TypeScript.isSTRFile(path) && !TypeScript.isDSTRFile(path) && !TypeScript.isTSFile(path) && !TypeScript.isDTSFile(path)) { - this.errorReporter.WriteLine("Unknown extension for file: \"" + path + "\". Only .ts and .d.ts extensions are allowed."); - } else { - this.errorReporter.WriteLine("Error reading file \"" + path + "\": File not found"); - } - } - } - return ret; - }; - BatchCompiler.prototype.compile = function () { - var _this = this; - var compiler; - compiler = new TypeScript.TypeScriptCompiler(this.errorReporter, new TypeScript.NullLogger(), this.compilationSettings); - compiler.setErrorOutput(this.errorReporter); - compiler.setErrorCallback(function (minChar, charLen, message, unitIndex) { - compiler.errorReporter.hasErrors = true; - var fname = _this.resolvedEnvironment.code[unitIndex].path; - var lineCol = { - line: -1, - col: -1 - }; - compiler.parser.getSourceLineCol(lineCol, minChar); - var msg = fname + " (" + lineCol.line + "," + (lineCol.col + 1) + "): " + message; - if(_this.compilationSettings.errorRecovery) { - _this.errorReporter.WriteLine(msg); - } else { - throw new SyntaxError(msg); - } - }); - if(this.compilationSettings.emitComments) { - compiler.emitCommentsToOutput(); - } - var consumeUnit = function (code, addAsResident) { - try { - if(!_this.compilationSettings.resolve) { - code.content = _this.ioHost.readFile(code.path); - if(_this.compilationSettings.generateDeclarationFiles) { - TypeScript.CompilerDiagnostics.assert(code.referencedFiles == null, "With no resolve option, referenced files need to null"); - code.referencedFiles = TypeScript.getReferencedFiles(code); - } - } - if(code.content != null) { - if(_this.compilationSettings.parseOnly) { - compiler.parseUnit(code.content, code.path); - } else { - if(_this.compilationSettings.errorRecovery) { - compiler.parser.setErrorRecovery(_this.errorReporter); - } - compiler.addUnit(code.content, code.path, addAsResident, code.referencedFiles); - } - } - } catch (err) { - compiler.errorReporter.hasErrors = true; - _this.errorReporter.WriteLine(err.message); - } - }; - for(var iCode = 0; iCode < this.resolvedEnvironment.code.length; iCode++) { - if(!this.compilationSettings.parseOnly || (iCode > 0)) { - consumeUnit(this.resolvedEnvironment.code[iCode], false); - } - } - var emitterIOHost = { - createFile: function (fileName, useUTF8) { - return IOUtils.createFileAndFolderStructure(_this.ioHost, fileName, useUTF8); - }, - directoryExists: this.ioHost.directoryExists, - fileExists: this.ioHost.fileExists, - resolvePath: this.ioHost.resolvePath - }; - try { - if(!this.compilationSettings.parseOnly) { - compiler.typeCheck(); - var mapInputToOutput = function (unitIndex, outFile) { - _this.compilationEnvironment.inputOutputMap[unitIndex] = outFile; - }; - compiler.emit(emitterIOHost, mapInputToOutput); - compiler.emitDeclarations(); - } else { - compiler.emitAST(emitterIOHost); - } - } catch (err) { - compiler.errorReporter.hasErrors = true; - if(err.message != "EmitError") { - throw err; - } - } - return compiler.errorReporter.hasErrors; - }; - BatchCompiler.prototype.run = function () { - for(var i in this.compilationEnvironment.code) { - var outputFileName = this.compilationEnvironment.inputOutputMap[i]; - if(this.ioHost.fileExists(outputFileName)) { - var unitRes = this.ioHost.readFile(outputFileName); - this.ioHost.run(unitRes, outputFileName); - } - } - }; - BatchCompiler.prototype.batchCompile = function () { - var _this = this; - TypeScript.CompilerDiagnostics.diagnosticWriter = { - Alert: function (s) { - _this.ioHost.printLine(s); - } - }; - var code; - var opts = new OptionsParser(this.ioHost); - opts.option('out', { - usage: 'Concatenate and emit output to single file | Redirect output structure to the directory', - type: 'file|directory', - set: function (str) { - _this.compilationSettings.outputOption = str; - } - }); - opts.option('style', { - usage: 'Select style checking options (examples --style requireSemi:off or --style "eqeqeq;bitwise:off")', - experimental: true, - set: function (str) { - _this.compilationSettings.setStyleOptions(str); - } - }); - opts.flag('sourcemap', { - usage: 'Generates corresponding .map file', - set: function () { - _this.compilationSettings.mapSourceFiles = true; - } - }); - opts.flag('fullSourceMapPath', { - usage: 'Writes the full path of map file in the generated js file', - experimental: true, - set: function () { - _this.compilationSettings.emitFullSourceMapPath = true; - } - }); - opts.flag('declaration', { - usage: 'Generates corresponding .d.ts file', - set: function () { - _this.compilationSettings.generateDeclarationFiles = true; - } - }); - if(this.ioHost.watchFile) { - opts.flag('watch', { - usage: 'Watch output files', - set: function () { - _this.compilationSettings.watch = true; - } - }, 'w'); - } - opts.flag('exec', { - usage: 'Execute the script after compilation', - set: function () { - _this.compilationSettings.exec = true; - } - }, 'e'); - opts.flag('parse', { - usage: 'Parse only', - experimental: true, - set: function () { - _this.compilationSettings.parseOnly = true; - } - }); - opts.flag('minw', { - usage: 'Minimize whitespace', - experimental: true, - set: function () { - _this.compilationSettings.minWhitespace = true; - } - }, 'mw'); - opts.flag('const', { - usage: 'Propagate constants to emitted code', - experimental: true, - set: function () { - _this.compilationSettings.propagateConstants = true; - } - }); - opts.flag('errorrecovery', { - usage: 'Enable error recovery', - experimental: true, - set: function () { - _this.compilationSettings.errorRecovery = true; - } - }, 'er'); - opts.flag('comments', { - usage: 'Emit comments to output', - set: function () { - _this.compilationSettings.emitComments = true; - } - }, 'c'); - opts.flag('cflow', { - usage: 'Control flow', - experimental: true, - set: function () { - _this.compilationSettings.controlFlow = true; - } - }); - opts.flag('cflowp', { - usage: 'Print control flow', - experimental: true, - set: function () { - _this.compilationSettings.controlFlow = true; - _this.compilationSettings.printControlFlow = true; - } - }); - opts.flag('cflowu', { - usage: 'Print Use Def control flow', - experimental: true, - set: function () { - _this.compilationSettings.controlFlow = true; - _this.compilationSettings.controlFlowUseDef = true; - } - }); - opts.flag('noerroronwith', { - usage: 'Allow with statements', - experimental: true, - set: function () { - _this.compilationSettings.errorOnWith = false; - } - }); - opts.flag('noresolve', { - usage: 'Skip resolution and preprocessing', - experimental: true, - set: function () { - _this.compilationSettings.resolve = false; - _this.compilationSettings.preprocess = false; - } - }); - opts.flag('debug', { - usage: 'Print debug output', - experimental: true, - set: function () { - TypeScript.CompilerDiagnostics.debug = true; - } - }); - opts.flag('canCallDefinitionSignature', { - usage: 'Allows you to call the definition signature of an overload group', - experimental: true, - set: function () { - _this.compilationSettings.canCallDefinitionSignature = true; - } - }); - opts.flag('nooptimizemodules', { - usage: 'Do not optimize module codegen', - experimental: true, - set: function () { - TypeScript.optimizeModuleCodeGen = false; - } - }); - opts.flag('nolib', { - usage: 'Do not include a default lib.d.ts with global declarations', - set: function () { - _this.compilationSettings.useDefaultLib = false; - } - }); - opts.flag('inferProperties', { - usage: 'Infer class properties from top-level assignments to \'this\'', - experimental: true, - set: function () { - _this.compilationSettings.inferPropertiesFromThisAssignment = true; - } - }); - opts.option('target', { - usage: 'Specify ECMAScript target version: "ES3" (default), or "ES5"', - type: 'VER', - set: function (type) { - type = type.toLowerCase(); - if(type === 'es3') { - _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES3; - } else if(type === 'es5') { - _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES5; - } else { - _this.errorReporter.WriteLine("ECMAScript target version '" + type + "' not supported. Using default 'ES3' code generation"); - } - } - }); - opts.option('module', { - usage: 'Specify module code generation: "commonjs" (default) or "amd"', - type: 'kind', - set: function (type) { - type = type.toLowerCase(); - if(type === 'commonjs' || type === 'node') { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; - } else if(type === 'amd') { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Asynchronous; - } else { - _this.errorReporter.WriteLine("Module code generation '" + type + "' not supported. Using default 'commonjs' code generation"); - } - } - }); - var printedUsage = false; - opts.flag('help', { - usage: 'Print this message', - set: function () { - _this.printVersion(); - opts.printUsage(); - printedUsage = true; - } - }, 'h'); - opts.flag('useCaseSensitiveFileResolution', { - usage: 'Force file resolution to be case sensitive', - experimental: true, - set: function () { - _this.compilationSettings.useCaseSensitiveFileResolution = true; - } - }); - opts.flag('version', { - usage: 'Print the compiler\'s version: ' + this.compilerVersion, - set: function () { - _this.printVersion(); - } - }, 'v'); - opts.parse(this.ioHost.arguments); - if(this.compilationSettings.useDefaultLib) { - var compilerFilePath = this.ioHost.getExecutingFilePath(); - var binDirPath = this.ioHost.dirName(compilerFilePath); - var libStrPath = this.ioHost.resolvePath(binDirPath + "/lib.d.ts"); - code = new TypeScript.SourceUnit(libStrPath, null); - this.compilationEnvironment.code.push(code); - } - for(var i = 0; i < opts.unnamed.length; i++) { - code = new TypeScript.SourceUnit(opts.unnamed[i], null); - this.compilationEnvironment.code.push(code); - } - if(this.compilationEnvironment.code.length == (this.compilationSettings.useDefaultLib ? 1 : 0)) { - if(!printedUsage && !this.printedVersion) { - this.printVersion(); - opts.printUsage(); - this.ioHost.quit(1); - } - return; - } - var sourceFiles = []; - if(this.compilationSettings.watch) { - sourceFiles = this.compilationEnvironment.code.slice(0); - } - this.resolvedEnvironment = this.compilationSettings.resolve ? this.resolve() : this.compilationEnvironment; - this.compile(); - if(!this.errorReporter.hasErrors) { - if(this.compilationSettings.exec) { - this.run(); - } - } - if(this.compilationSettings.watch) { - this.watchFiles(sourceFiles); - } else { - this.ioHost.quit(this.errorReporter.hasErrors ? 1 : 0); - } - }; - BatchCompiler.prototype.printVersion = function () { - if(!this.printedVersion) { - this.ioHost.printLine("Version " + this.compilerVersion); - this.printedVersion = true; - } - }; - BatchCompiler.prototype.watchFiles = function (soruceFiles) { - var _this = this; - if(!this.ioHost.watchFile) { - this.errorReporter.WriteLine("Error: Current host does not support -w[atch] option"); - return; - } - var resolvedFiles = []; - var watchers = { - }; - var addWatcher = function (filename) { - if(!watchers[filename]) { - var watcher = _this.ioHost.watchFile(filename, onWatchedFileChange); - watchers[filename] = watcher; - } else { - TypeScript.CompilerDiagnostics.debugPrint("Cannot watch file, it is already watched."); - } - }; - var removeWatcher = function (filename) { - if(watchers[filename]) { - watchers[filename].close(); - delete watchers[filename]; - } else { - TypeScript.CompilerDiagnostics.debugPrint("Cannot stop watching file, it is not being watched."); - } - }; - var onWatchedFileChange = function () { - _this.compilationEnvironment.code = soruceFiles; - _this.errorReporter.reset(); - _this.resolvedEnvironment = _this.compilationSettings.resolve ? _this.resolve() : _this.compilationEnvironment; - var oldFiles = resolvedFiles; - var newFiles = []; - _this.resolvedEnvironment.code.forEach(function (sf) { - return newFiles.push(sf.path); - }); - newFiles = newFiles.sort(); - var i = 0, j = 0; - while(i < oldFiles.length && j < newFiles.length) { - var compareResult = oldFiles[i].localeCompare(newFiles[j]); - if(compareResult == 0) { - i++; - j++; - } else if(compareResult < 0) { - removeWatcher(oldFiles[i]); - i++; - } else { - addWatcher(newFiles[j]); - j++; - } - } - for(var k = i; k < oldFiles.length; k++) { - removeWatcher(oldFiles[k]); - } - for(var k = j; k < newFiles.length; k++) { - addWatcher(newFiles[k]); - } - resolvedFiles = newFiles; - ; - _this.ioHost.printLine(""); - _this.ioHost.printLine("Recompiling (" + new Date() + "): "); - resolvedFiles.forEach(function (f) { - return _this.ioHost.printLine(" " + f); - }); - _this.compile(); - if(!_this.errorReporter.hasErrors) { - if(_this.compilationSettings.exec) { - _this.run(); - } - } - }; - this.ioHost.stderr = this.ioHost.stdout; - this.resolvedEnvironment.code.forEach(function (sf) { - resolvedFiles.push(sf.path); - addWatcher(sf.path); - }); - resolvedFiles.sort(); - }; - return BatchCompiler; -})(); -var batch = new BatchCompiler(IO); -batch.batchCompile(); diff --git a/_infrastructure/tests/typescript_0.8.3/typescript.js b/_infrastructure/tests/typescript_0.8.3/typescript.js deleted file mode 100644 index 94641b33c..000000000 --- a/_infrastructure/tests/typescript_0.8.3/typescript.js +++ /dev/null @@ -1,23710 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -var TypeScript; -(function (TypeScript) { - function hasFlag(val, flag) { - return (val & flag) != 0; - } - TypeScript.hasFlag = hasFlag; - (function (ErrorRecoverySet) { - ErrorRecoverySet._map = []; - ErrorRecoverySet.None = 0; - ErrorRecoverySet.Comma = 1; - ErrorRecoverySet.SColon = 1 << 1; - ErrorRecoverySet.Asg = 1 << 2; - ErrorRecoverySet.BinOp = 1 << 3; - ErrorRecoverySet.RBrack = 1 << 4; - ErrorRecoverySet.RCurly = 1 << 5; - ErrorRecoverySet.RParen = 1 << 6; - ErrorRecoverySet.Dot = 1 << 7; - ErrorRecoverySet.Colon = 1 << 8; - ErrorRecoverySet.PrimType = 1 << 9; - ErrorRecoverySet.AddOp = 1 << 10; - ErrorRecoverySet.LCurly = 1 << 11; - ErrorRecoverySet.PreOp = 1 << 12; - ErrorRecoverySet.RegExp = 1 << 13; - ErrorRecoverySet.LParen = 1 << 14; - ErrorRecoverySet.LBrack = 1 << 15; - ErrorRecoverySet.Scope = 1 << 16; - ErrorRecoverySet.In = 1 << 17; - ErrorRecoverySet.SCase = 1 << 18; - ErrorRecoverySet.Else = 1 << 19; - ErrorRecoverySet.Catch = 1 << 20; - ErrorRecoverySet.Var = 1 << 21; - ErrorRecoverySet.Stmt = 1 << 22; - ErrorRecoverySet.While = 1 << 23; - ErrorRecoverySet.ID = 1 << 24; - ErrorRecoverySet.Prefix = 1 << 25; - ErrorRecoverySet.Literal = 1 << 26; - ErrorRecoverySet.RLit = 1 << 27; - ErrorRecoverySet.Func = 1 << 28; - ErrorRecoverySet.EOF = 1 << 29; - ErrorRecoverySet.TypeScriptS = 1 << 30; - ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; - ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; - ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; - })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); - var ErrorRecoverySet = TypeScript.ErrorRecoverySet; - (function (AllowedElements) { - AllowedElements._map = []; - AllowedElements.None = 0; - AllowedElements.ModuleDeclarations = 1 << 2; - AllowedElements.ClassDeclarations = 1 << 3; - AllowedElements.InterfaceDeclarations = 1 << 4; - AllowedElements.AmbientDeclarations = 1 << 10; - AllowedElements.Properties = 1 << 11; - AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; - AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; - })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); - var AllowedElements = TypeScript.AllowedElements; - (function (Modifiers) { - Modifiers._map = []; - Modifiers.None = 0; - Modifiers.Private = 1; - Modifiers.Public = 1 << 1; - Modifiers.Readonly = 1 << 2; - Modifiers.Ambient = 1 << 3; - Modifiers.Exported = 1 << 4; - Modifiers.Getter = 1 << 5; - Modifiers.Setter = 1 << 6; - Modifiers.Static = 1 << 7; - })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); - var Modifiers = TypeScript.Modifiers; - (function (ASTFlags) { - ASTFlags._map = []; - ASTFlags.None = 0; - ASTFlags.ExplicitSemicolon = 1; - ASTFlags.AutomaticSemicolon = 1 << 1; - ASTFlags.Writeable = 1 << 2; - ASTFlags.Error = 1 << 3; - ASTFlags.DotLHSPartial = 1 << 4; - ASTFlags.DotLHS = 1 << 5; - ASTFlags.IsStatement = 1 << 6; - ASTFlags.StrictMode = 1 << 7; - ASTFlags.PossibleOptionalParameter = 1 << 8; - ASTFlags.ClassBaseConstructorCall = 1 << 9; - ASTFlags.OptionalName = 1 << 10; - ASTFlags.SkipNextRParen = 1 << 11; - })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); - var ASTFlags = TypeScript.ASTFlags; - (function (DeclFlags) { - DeclFlags._map = []; - DeclFlags.None = 0; - DeclFlags.Exported = 1; - DeclFlags.Private = 1 << 1; - DeclFlags.Public = 1 << 2; - DeclFlags.Ambient = 1 << 3; - DeclFlags.Static = 1 << 4; - DeclFlags.LocalStatic = 1 << 5; - DeclFlags.GetAccessor = 1 << 6; - DeclFlags.SetAccessor = 1 << 7; - })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); - var DeclFlags = TypeScript.DeclFlags; - (function (ModuleFlags) { - ModuleFlags._map = []; - ModuleFlags.None = 0; - ModuleFlags.Exported = 1; - ModuleFlags.Private = 1 << 1; - ModuleFlags.Public = 1 << 2; - ModuleFlags.Ambient = 1 << 3; - ModuleFlags.Static = 1 << 4; - ModuleFlags.LocalStatic = 1 << 5; - ModuleFlags.GetAccessor = 1 << 6; - ModuleFlags.SetAccessor = 1 << 7; - ModuleFlags.IsEnum = 1 << 8; - ModuleFlags.ShouldEmitModuleDecl = 1 << 9; - ModuleFlags.IsWholeFile = 1 << 10; - ModuleFlags.IsDynamic = 1 << 11; - ModuleFlags.MustCaptureThis = 1 << 12; - })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); - var ModuleFlags = TypeScript.ModuleFlags; - (function (SymbolFlags) { - SymbolFlags._map = []; - SymbolFlags.None = 0; - SymbolFlags.Exported = 1; - SymbolFlags.Private = 1 << 1; - SymbolFlags.Public = 1 << 2; - SymbolFlags.Ambient = 1 << 3; - SymbolFlags.Static = 1 << 4; - SymbolFlags.LocalStatic = 1 << 5; - SymbolFlags.GetAccessor = 1 << 6; - SymbolFlags.SetAccessor = 1 << 7; - SymbolFlags.Property = 1 << 8; - SymbolFlags.Readonly = 1 << 9; - SymbolFlags.ModuleMember = 1 << 10; - SymbolFlags.InterfaceMember = 1 << 11; - SymbolFlags.ClassMember = 1 << 12; - SymbolFlags.BuiltIn = 1 << 13; - SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; - SymbolFlags.Constant = 1 << 15; - SymbolFlags.Optional = 1 << 16; - SymbolFlags.RecursivelyReferenced = 1 << 17; - SymbolFlags.Bound = 1 << 18; - SymbolFlags.CompilerGenerated = 1 << 19; - })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); - var SymbolFlags = TypeScript.SymbolFlags; - (function (VarFlags) { - VarFlags._map = []; - VarFlags.None = 0; - VarFlags.Exported = 1; - VarFlags.Private = 1 << 1; - VarFlags.Public = 1 << 2; - VarFlags.Ambient = 1 << 3; - VarFlags.Static = 1 << 4; - VarFlags.LocalStatic = 1 << 5; - VarFlags.GetAccessor = 1 << 6; - VarFlags.SetAccessor = 1 << 7; - VarFlags.AutoInit = 1 << 8; - VarFlags.Property = 1 << 9; - VarFlags.Readonly = 1 << 10; - VarFlags.Class = 1 << 11; - VarFlags.ClassProperty = 1 << 12; - VarFlags.ClassBodyProperty = 1 << 13; - VarFlags.ClassConstructorProperty = 1 << 14; - VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; - VarFlags.Constant = 1 << 16; - VarFlags.MustCaptureThis = 1 << 17; - })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); - var VarFlags = TypeScript.VarFlags; - (function (FncFlags) { - FncFlags._map = []; - FncFlags.None = 0; - FncFlags.Exported = 1; - FncFlags.Private = 1 << 1; - FncFlags.Public = 1 << 2; - FncFlags.Ambient = 1 << 3; - FncFlags.Static = 1 << 4; - FncFlags.LocalStatic = 1 << 5; - FncFlags.GetAccessor = 1 << 6; - FncFlags.SetAccessor = 1 << 7; - FncFlags.Signature = 1 << 9; - FncFlags.Method = 1 << 10; - FncFlags.HasReturnExpression = 1 << 11; - FncFlags.CallMember = 1 << 12; - FncFlags.ConstructMember = 1 << 13; - FncFlags.HasSelfReference = 1 << 14; - FncFlags.IsFatArrowFunction = 1 << 15; - FncFlags.IndexerMember = 1 << 16; - FncFlags.IsFunctionExpression = 1 << 17; - FncFlags.ClassMethod = 1 << 18; - FncFlags.ClassPropertyMethodExported = 1 << 19; - FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; - FncFlags.IsPropertyBound = 1 << 21; - })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); - var FncFlags = TypeScript.FncFlags; - (function (SignatureFlags) { - SignatureFlags._map = []; - SignatureFlags.None = 0; - SignatureFlags.IsIndexer = 1; - SignatureFlags.IsStringIndexer = 1 << 1; - SignatureFlags.IsNumberIndexer = 1 << 2; - })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); - var SignatureFlags = TypeScript.SignatureFlags; - function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { - return fncOrVarOrSymbolOrModuleFlags; - } - TypeScript.ToDeclFlags = ToDeclFlags; - (function (TypeFlags) { - TypeFlags._map = []; - TypeFlags.None = 0; - TypeFlags.HasImplementation = 1; - TypeFlags.HasSelfReference = 1 << 1; - TypeFlags.MergeResult = 1 << 2; - TypeFlags.IsEnum = 1 << 3; - TypeFlags.BuildingName = 1 << 4; - TypeFlags.HasBaseType = 1 << 5; - TypeFlags.HasBaseTypeOfObject = 1 << 6; - TypeFlags.IsClass = 1 << 7; - })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); - var TypeFlags = TypeScript.TypeFlags; - (function (TypeRelationshipFlags) { - TypeRelationshipFlags._map = []; - TypeRelationshipFlags.SuccessfulComparison = 0; - TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; - TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; - TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; - TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; - TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; - TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; - TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; - })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); - var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; - (function (CodeGenTarget) { - CodeGenTarget._map = []; - CodeGenTarget.ES3 = 0; - CodeGenTarget.ES5 = 1; - })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); - var CodeGenTarget = TypeScript.CodeGenTarget; - (function (ModuleGenTarget) { - ModuleGenTarget._map = []; - ModuleGenTarget.Synchronous = 0; - ModuleGenTarget.Asynchronous = 1; - ModuleGenTarget.Local = 1 << 1; - })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); - var ModuleGenTarget = TypeScript.ModuleGenTarget; - TypeScript.codeGenTarget = CodeGenTarget.ES3; - TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; - TypeScript.optimizeModuleCodeGen = true; - function flagsToString(e, flags) { - var builder = ""; - for(var i = 1; i < (1 << 31); i = i << 1) { - if((flags & i) != 0) { - for(var k in e) { - if(e[k] == i) { - if(builder.length > 0) { - builder += "|"; - } - builder += k; - break; - } - } - } - } - return builder; - } - TypeScript.flagsToString = flagsToString; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (NodeType) { - NodeType._map = []; - NodeType._map[0] = "None"; - NodeType.None = 0; - NodeType._map[1] = "Empty"; - NodeType.Empty = 1; - NodeType._map[2] = "EmptyExpr"; - NodeType.EmptyExpr = 2; - NodeType._map[3] = "True"; - NodeType.True = 3; - NodeType._map[4] = "False"; - NodeType.False = 4; - NodeType._map[5] = "This"; - NodeType.This = 5; - NodeType._map[6] = "Super"; - NodeType.Super = 6; - NodeType._map[7] = "QString"; - NodeType.QString = 7; - NodeType._map[8] = "Regex"; - NodeType.Regex = 8; - NodeType._map[9] = "Null"; - NodeType.Null = 9; - NodeType._map[10] = "ArrayLit"; - NodeType.ArrayLit = 10; - NodeType._map[11] = "ObjectLit"; - NodeType.ObjectLit = 11; - NodeType._map[12] = "Void"; - NodeType.Void = 12; - NodeType._map[13] = "Comma"; - NodeType.Comma = 13; - NodeType._map[14] = "Pos"; - NodeType.Pos = 14; - NodeType._map[15] = "Neg"; - NodeType.Neg = 15; - NodeType._map[16] = "Delete"; - NodeType.Delete = 16; - NodeType._map[17] = "Await"; - NodeType.Await = 17; - NodeType._map[18] = "In"; - NodeType.In = 18; - NodeType._map[19] = "Dot"; - NodeType.Dot = 19; - NodeType._map[20] = "From"; - NodeType.From = 20; - NodeType._map[21] = "Is"; - NodeType.Is = 21; - NodeType._map[22] = "InstOf"; - NodeType.InstOf = 22; - NodeType._map[23] = "Typeof"; - NodeType.Typeof = 23; - NodeType._map[24] = "NumberLit"; - NodeType.NumberLit = 24; - NodeType._map[25] = "Name"; - NodeType.Name = 25; - NodeType._map[26] = "TypeRef"; - NodeType.TypeRef = 26; - NodeType._map[27] = "Index"; - NodeType.Index = 27; - NodeType._map[28] = "Call"; - NodeType.Call = 28; - NodeType._map[29] = "New"; - NodeType.New = 29; - NodeType._map[30] = "Asg"; - NodeType.Asg = 30; - NodeType._map[31] = "AsgAdd"; - NodeType.AsgAdd = 31; - NodeType._map[32] = "AsgSub"; - NodeType.AsgSub = 32; - NodeType._map[33] = "AsgDiv"; - NodeType.AsgDiv = 33; - NodeType._map[34] = "AsgMul"; - NodeType.AsgMul = 34; - NodeType._map[35] = "AsgMod"; - NodeType.AsgMod = 35; - NodeType._map[36] = "AsgAnd"; - NodeType.AsgAnd = 36; - NodeType._map[37] = "AsgXor"; - NodeType.AsgXor = 37; - NodeType._map[38] = "AsgOr"; - NodeType.AsgOr = 38; - NodeType._map[39] = "AsgLsh"; - NodeType.AsgLsh = 39; - NodeType._map[40] = "AsgRsh"; - NodeType.AsgRsh = 40; - NodeType._map[41] = "AsgRs2"; - NodeType.AsgRs2 = 41; - NodeType._map[42] = "ConditionalExpression"; - NodeType.ConditionalExpression = 42; - NodeType._map[43] = "LogOr"; - NodeType.LogOr = 43; - NodeType._map[44] = "LogAnd"; - NodeType.LogAnd = 44; - NodeType._map[45] = "Or"; - NodeType.Or = 45; - NodeType._map[46] = "Xor"; - NodeType.Xor = 46; - NodeType._map[47] = "And"; - NodeType.And = 47; - NodeType._map[48] = "Eq"; - NodeType.Eq = 48; - NodeType._map[49] = "Ne"; - NodeType.Ne = 49; - NodeType._map[50] = "Eqv"; - NodeType.Eqv = 50; - NodeType._map[51] = "NEqv"; - NodeType.NEqv = 51; - NodeType._map[52] = "Lt"; - NodeType.Lt = 52; - NodeType._map[53] = "Le"; - NodeType.Le = 53; - NodeType._map[54] = "Gt"; - NodeType.Gt = 54; - NodeType._map[55] = "Ge"; - NodeType.Ge = 55; - NodeType._map[56] = "Add"; - NodeType.Add = 56; - NodeType._map[57] = "Sub"; - NodeType.Sub = 57; - NodeType._map[58] = "Mul"; - NodeType.Mul = 58; - NodeType._map[59] = "Div"; - NodeType.Div = 59; - NodeType._map[60] = "Mod"; - NodeType.Mod = 60; - NodeType._map[61] = "Lsh"; - NodeType.Lsh = 61; - NodeType._map[62] = "Rsh"; - NodeType.Rsh = 62; - NodeType._map[63] = "Rs2"; - NodeType.Rs2 = 63; - NodeType._map[64] = "Not"; - NodeType.Not = 64; - NodeType._map[65] = "LogNot"; - NodeType.LogNot = 65; - NodeType._map[66] = "IncPre"; - NodeType.IncPre = 66; - NodeType._map[67] = "DecPre"; - NodeType.DecPre = 67; - NodeType._map[68] = "IncPost"; - NodeType.IncPost = 68; - NodeType._map[69] = "DecPost"; - NodeType.DecPost = 69; - NodeType._map[70] = "TypeAssertion"; - NodeType.TypeAssertion = 70; - NodeType._map[71] = "FuncDecl"; - NodeType.FuncDecl = 71; - NodeType._map[72] = "Member"; - NodeType.Member = 72; - NodeType._map[73] = "VarDecl"; - NodeType.VarDecl = 73; - NodeType._map[74] = "ArgDecl"; - NodeType.ArgDecl = 74; - NodeType._map[75] = "Return"; - NodeType.Return = 75; - NodeType._map[76] = "Break"; - NodeType.Break = 76; - NodeType._map[77] = "Continue"; - NodeType.Continue = 77; - NodeType._map[78] = "Throw"; - NodeType.Throw = 78; - NodeType._map[79] = "For"; - NodeType.For = 79; - NodeType._map[80] = "ForIn"; - NodeType.ForIn = 80; - NodeType._map[81] = "If"; - NodeType.If = 81; - NodeType._map[82] = "While"; - NodeType.While = 82; - NodeType._map[83] = "DoWhile"; - NodeType.DoWhile = 83; - NodeType._map[84] = "Block"; - NodeType.Block = 84; - NodeType._map[85] = "Case"; - NodeType.Case = 85; - NodeType._map[86] = "Switch"; - NodeType.Switch = 86; - NodeType._map[87] = "Try"; - NodeType.Try = 87; - NodeType._map[88] = "TryCatch"; - NodeType.TryCatch = 88; - NodeType._map[89] = "TryFinally"; - NodeType.TryFinally = 89; - NodeType._map[90] = "Finally"; - NodeType.Finally = 90; - NodeType._map[91] = "Catch"; - NodeType.Catch = 91; - NodeType._map[92] = "List"; - NodeType.List = 92; - NodeType._map[93] = "Script"; - NodeType.Script = 93; - NodeType._map[94] = "ClassDeclaration"; - NodeType.ClassDeclaration = 94; - NodeType._map[95] = "InterfaceDeclaration"; - NodeType.InterfaceDeclaration = 95; - NodeType._map[96] = "ModuleDeclaration"; - NodeType.ModuleDeclaration = 96; - NodeType._map[97] = "ImportDeclaration"; - NodeType.ImportDeclaration = 97; - NodeType._map[98] = "With"; - NodeType.With = 98; - NodeType._map[99] = "Label"; - NodeType.Label = 99; - NodeType._map[100] = "LabeledStatement"; - NodeType.LabeledStatement = 100; - NodeType._map[101] = "EBStart"; - NodeType.EBStart = 101; - NodeType._map[102] = "GotoEB"; - NodeType.GotoEB = 102; - NodeType._map[103] = "EndCode"; - NodeType.EndCode = 103; - NodeType._map[104] = "Error"; - NodeType.Error = 104; - NodeType._map[105] = "Comment"; - NodeType.Comment = 105; - NodeType._map[106] = "Debugger"; - NodeType.Debugger = 106; - NodeType.GeneralNode = NodeType.FuncDecl; - NodeType.LastAsg = NodeType.AsgRs2; - })(TypeScript.NodeType || (TypeScript.NodeType = {})); - var NodeType = TypeScript.NodeType; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var BlockIntrinsics = (function () { - function BlockIntrinsics() { - this.prototype = undefined; - this.toString = undefined; - this.toLocaleString = undefined; - this.valueOf = undefined; - this.hasOwnProperty = undefined; - this.propertyIsEnumerable = undefined; - this.isPrototypeOf = undefined; - this["constructor"] = undefined; - } - return BlockIntrinsics; - })(); - TypeScript.BlockIntrinsics = BlockIntrinsics; - var StringHashTable = (function () { - function StringHashTable() { - this.itemCount = 0; - this.table = (new BlockIntrinsics()); - } - StringHashTable.prototype.getAllKeys = function () { - var result = []; - for(var k in this.table) { - if(this.table[k] != undefined) { - result[result.length] = k; - } - } - return result; - }; - StringHashTable.prototype.add = function (key, data) { - if(this.table[key] != undefined) { - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.table[key] != undefined) { - this.table[key] = data; - return false; - } - this.table[key] = data; - this.itemCount++; - return true; - }; - StringHashTable.prototype.map = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - fn(k, this.table[k], context); - } - } - }; - StringHashTable.prototype.every = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(!fn(k, this.table[k], context)) { - return false; - } - } - } - return true; - }; - StringHashTable.prototype.some = function (fn, context) { - for(var k in this.table) { - var data = this.table[k]; - if(data != undefined) { - if(fn(k, this.table[k], context)) { - return true; - } - } - } - return false; - }; - StringHashTable.prototype.count = function () { - return this.itemCount; - }; - StringHashTable.prototype.lookup = function (key) { - var data = this.table[key]; - if(data != undefined) { - return data; - } else { - return (null); - } - }; - return StringHashTable; - })(); - TypeScript.StringHashTable = StringHashTable; - var DualStringHashTable = (function () { - function DualStringHashTable(primaryTable, secondaryTable) { - this.primaryTable = primaryTable; - this.secondaryTable = secondaryTable; - this.insertPrimary = true; - } - DualStringHashTable.prototype.getAllKeys = function () { - return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); - }; - DualStringHashTable.prototype.add = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.add(key, data); - } else { - return this.secondaryTable.add(key, data); - } - }; - DualStringHashTable.prototype.addOrUpdate = function (key, data) { - if(this.insertPrimary) { - return this.primaryTable.addOrUpdate(key, data); - } else { - return this.secondaryTable.addOrUpdate(key, data); - } - }; - DualStringHashTable.prototype.map = function (fn, context) { - this.primaryTable.map(fn, context); - this.secondaryTable.map(fn, context); - }; - DualStringHashTable.prototype.every = function (fn, context) { - return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); - }; - DualStringHashTable.prototype.some = function (fn, context) { - return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); - }; - DualStringHashTable.prototype.count = function () { - return this.primaryTable.count() + this.secondaryTable.count(); - }; - DualStringHashTable.prototype.lookup = function (key) { - var data = this.primaryTable.lookup(key); - if(data != undefined) { - return data; - } else { - return this.secondaryTable.lookup(key); - } - }; - return DualStringHashTable; - })(); - TypeScript.DualStringHashTable = DualStringHashTable; - function numberHashFn(key) { - var c2 = 0x27d4eb2d; - key = (key ^ 61) ^ (key >>> 16); - key = key + (key << 3); - key = key ^ (key >>> 4); - key = key * c2; - key = key ^ (key >>> 15); - return key; - } - TypeScript.numberHashFn = numberHashFn; - function combineHashes(key1, key2) { - return key2 ^ ((key1 >> 5) + key1); - } - TypeScript.combineHashes = combineHashes; - var HashEntry = (function () { - function HashEntry(key, data) { - this.key = key; - this.data = data; - } - return HashEntry; - })(); - TypeScript.HashEntry = HashEntry; - var HashTable = (function () { - function HashTable(size, hashFn, equalsFn) { - this.size = size; - this.hashFn = hashFn; - this.equalsFn = equalsFn; - this.itemCount = 0; - this.table = new Array(); - for(var i = 0; i < this.size; i++) { - this.table[i] = null; - } - } - HashTable.prototype.add = function (key, data) { - var current; - var entry = new HashEntry(key, data); - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return false; - } - } - entry.next = this.table[val]; - this.table[val] = entry; - this.itemCount++; - return true; - }; - HashTable.prototype.remove = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - var result = null; - var prevEntry = null; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - result = current.data; - this.itemCount--; - if(prevEntry) { - prevEntry.next = current.next; - } else { - this.table[val] = current.next; - } - break; - } - prevEntry = current; - } - return result; - }; - HashTable.prototype.count = function () { - return this.itemCount; - }; - HashTable.prototype.lookup = function (key) { - var current; - var val = this.hashFn(key); - val = val % this.size; - for(current = this.table[val]; current != null; current = current.next) { - if(this.equalsFn(key, current.key)) { - return (current.data); - } - } - return (null); - }; - return HashTable; - })(); - TypeScript.HashTable = HashTable; - var SimpleHashTable = (function () { - function SimpleHashTable() { - this.keys = []; - this.values = []; - } - SimpleHashTable.prototype.lookup = function (key, findValue) { - var searchArray = this.keys; - if(findValue) { - searchArray = this.values; - } - for(var i = 0; i < searchArray.length; i++) { - if(searchArray[i] == key) { - return { - key: this.keys[i], - data: this.values[i] - }; - } - } - return null; - }; - SimpleHashTable.prototype.add = function (key, data) { - var lookupData = this.lookup(key); - if(lookupData) { - return false; - } - this.keys[this.keys.length] = key; - this.values[this.values.length] = data; - return true; - }; - return SimpleHashTable; - })(); - TypeScript.SimpleHashTable = SimpleHashTable; -})(TypeScript || (TypeScript = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -var TypeScript; -(function (TypeScript) { - var ASTSpan = (function () { - function ASTSpan() { - this.minChar = -1; - this.limChar = -1; - } - return ASTSpan; - })(); - TypeScript.ASTSpan = ASTSpan; - var AST = (function (_super) { - __extends(AST, _super); - function AST(nodeType) { - _super.call(this); - this.nodeType = nodeType; - this.type = null; - this.flags = TypeScript.ASTFlags.Writeable; - this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.preComments = null; - this.postComments = null; - this.docComments = null; - this.isParenthesized = false; - } - AST.prototype.isExpression = function () { - return false; - }; - AST.prototype.isStatementOrExpression = function () { - return false; - }; - AST.prototype.isCompoundStatement = function () { - return false; - }; - AST.prototype.isLeaf = function () { - return this.isStatementOrExpression() && (!this.isCompoundStatement()); - }; - AST.prototype.isDeclaration = function () { - return false; - }; - AST.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: - this.type = typeFlow.anyType; - break; - case TypeScript.NodeType.This: - return typeFlow.typeCheckThis(this); - case TypeScript.NodeType.Null: - this.type = typeFlow.nullType; - break; - case TypeScript.NodeType.False: - case TypeScript.NodeType.True: - this.type = typeFlow.booleanType; - break; - case TypeScript.NodeType.Super: - return typeFlow.typeCheckSuper(this); - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Empty: - case TypeScript.NodeType.Void: - this.type = typeFlow.voidType; - break; - default: - throw new Error("please implement in derived class"); - } - return this; - }; - AST.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - switch(this.nodeType) { - case TypeScript.NodeType.This: - emitter.recordSourceMappingStart(this); - if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - emitter.writeToOutput("_this"); - } else { - emitter.writeToOutput("this"); - } - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.Null: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("null"); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.False: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("false"); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.True: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("true"); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.Super: - emitter.recordSourceMappingStart(this); - emitter.emitSuperReference(); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.EndCode: - case TypeScript.NodeType.Error: - case TypeScript.NodeType.EmptyExpr: - break; - case TypeScript.NodeType.Empty: - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingEnd(this); - break; - case TypeScript.NodeType.Void: - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("void "); - emitter.recordSourceMappingEnd(this); - break; - default: - throw new Error("please implement in derived class"); - } - emitter.emitParensAndCommentsInPlace(this, false); - }; - AST.prototype.print = function (context) { - context.startLine(); - var lineCol = { - line: -1, - col: -1 - }; - var limLineCol = { - line: -1, - col: -1 - }; - if(context.parser !== null) { - context.parser.getSourceLineCol(lineCol, this.minChar); - context.parser.getSourceLineCol(limLineCol, this.limChar); - context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); - } - var lab = this.printLabel(); - if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { - lab += " (Error)"; - } - context.writeLine(lab); - }; - AST.prototype.printLabel = function () { - if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { - return TypeScript.nodeTypeTable[this.nodeType]; - } else { - return (TypeScript.NodeType)._map[this.nodeType]; - } - }; - AST.prototype.addToControlFlow = function (context) { - context.walker.options.goChildren = false; - context.addContent(this); - }; - AST.prototype.netFreeUses = function (container, freeUses) { - }; - AST.prototype.treeViewLabel = function () { - return (TypeScript.NodeType)._map[this.nodeType]; - }; - AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { - if(!name) { - return ""; - } - var resolved = ""; - var start = 0; - var i = 0; - while(i <= name.length - 6) { - if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { - var charCode = parseInt(name.substr(i + 2, 4), 16); - resolved += name.substr(start, i - start); - resolved += String.fromCharCode(charCode); - i += 6; - start = i; - continue; - } - i++; - } - resolved += name.substring(start); - return resolved; - }; - AST.prototype.getDocComments = function () { - if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { - return []; - } - if(!this.docComments) { - var preCommentsLength = this.preComments.length; - var docComments = []; - for(var i = preCommentsLength - 1; i >= 0; i--) { - if(this.preComments[i].isDocComment()) { - var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; - if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { - docComments.push(this.preComments[i]); - continue; - } - } - break; - } - this.docComments = docComments.reverse(); - } - return this.docComments; - }; - return AST; - })(ASTSpan); - TypeScript.AST = AST; - var IncompleteAST = (function (_super) { - __extends(IncompleteAST, _super); - function IncompleteAST(min, lim) { - _super.call(this, TypeScript.NodeType.Error); - this.minChar = min; - this.limChar = lim; - } - return IncompleteAST; - })(AST); - TypeScript.IncompleteAST = IncompleteAST; - var ASTList = (function (_super) { - __extends(ASTList, _super); - function ASTList() { - _super.call(this, TypeScript.NodeType.List); - this.enclosingScope = null; - this.members = new Array(); - } - ASTList.prototype.addToControlFlow = function (context) { - var len = this.members.length; - for(var i = 0; i < len; i++) { - if(context.noContinuation) { - context.addUnreachable(this.members[i]); - break; - } else { - this.members[i] = context.walk(this.members[i], this); - } - } - context.walker.options.goChildren = false; - }; - ASTList.prototype.append = function (ast) { - this.members[this.members.length] = ast; - return this; - }; - ASTList.prototype.appendAll = function (ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - for(var i = 0, len = list.members.length; i < len; i++) { - this.append(list.members[i]); - } - } else { - this.append(ast); - } - return this; - }; - ASTList.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); - emitter.recordSourceMappingEnd(this); - }; - ASTList.prototype.typeCheck = function (typeFlow) { - var len = this.members.length; - typeFlow.nestingLevel++; - for(var i = 0; i < len; i++) { - if(this.members[i]) { - this.members[i] = this.members[i].typeCheck(typeFlow); - } - } - typeFlow.nestingLevel--; - return this; - }; - return ASTList; - })(AST); - TypeScript.ASTList = ASTList; - var Identifier = (function (_super) { - __extends(Identifier, _super); - function Identifier(actualText, hasEscapeSequence) { - _super.call(this, TypeScript.NodeType.Name); - this.actualText = actualText; - this.hasEscapeSequence = hasEscapeSequence; - this.sym = null; - this.cloId = -1; - this.setText(actualText, hasEscapeSequence); - } - Identifier.prototype.setText = function (actualText, hasEscapeSequence) { - this.actualText = actualText; - if(hasEscapeSequence) { - this.text = AST.getResolvedIdentifierName(actualText); - } else { - this.text = actualText; - } - }; - Identifier.prototype.isMissing = function () { - return false; - }; - Identifier.prototype.isLeaf = function () { - return true; - }; - Identifier.prototype.treeViewLabel = function () { - return "id: " + this.actualText; - }; - Identifier.prototype.printLabel = function () { - if(this.actualText) { - return "id: " + this.actualText; - } else { - return "name node"; - } - }; - Identifier.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckName(this); - }; - Identifier.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptName(this, true); - }; - Identifier.fromToken = function fromToken(token) { - return new Identifier(token.getText(), (token).hasEscapeSequence); - }; - return Identifier; - })(AST); - TypeScript.Identifier = Identifier; - var MissingIdentifier = (function (_super) { - __extends(MissingIdentifier, _super); - function MissingIdentifier() { - _super.call(this, "__missing"); - } - MissingIdentifier.prototype.isMissing = function () { - return true; - }; - MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { - }; - return MissingIdentifier; - })(Identifier); - TypeScript.MissingIdentifier = MissingIdentifier; - var Label = (function (_super) { - __extends(Label, _super); - function Label(id) { - _super.call(this, TypeScript.NodeType.Label); - this.id = id; - } - Label.prototype.printLabel = function () { - return this.id.actualText + ":"; - }; - Label.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - Label.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.recordSourceMappingStart(this.id); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this.id); - emitter.writeLineToOutput(":"); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Label; - })(AST); - TypeScript.Label = Label; - var Expression = (function (_super) { - __extends(Expression, _super); - function Expression(nodeType) { - _super.call(this, nodeType); - } - Expression.prototype.isExpression = function () { - return true; - }; - Expression.prototype.isStatementOrExpression = function () { - return true; - }; - return Expression; - })(AST); - TypeScript.Expression = Expression; - var UnaryExpression = (function (_super) { - __extends(UnaryExpression, _super); - function UnaryExpression(nodeType, operand) { - _super.call(this, nodeType); - this.operand = operand; - this.targetType = null; - this.castTerm = null; - } - UnaryExpression.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - if(this.nodeType == TypeScript.NodeType.Throw) { - context.returnStmt(); - } - }; - UnaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Not: - return typeFlow.typeCheckBitNot(this); - case TypeScript.NodeType.LogNot: - return typeFlow.typeCheckLogNot(this); - case TypeScript.NodeType.Pos: - case TypeScript.NodeType.Neg: - return typeFlow.typeCheckUnaryNumberOperator(this); - case TypeScript.NodeType.IncPost: - case TypeScript.NodeType.IncPre: - case TypeScript.NodeType.DecPost: - case TypeScript.NodeType.DecPre: - return typeFlow.typeCheckIncOrDec(this); - case TypeScript.NodeType.ArrayLit: - typeFlow.typeCheckArrayLit(this); - return this; - case TypeScript.NodeType.ObjectLit: - typeFlow.typeCheckObjectLit(this); - return this; - case TypeScript.NodeType.Throw: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.voidType; - return this; - case TypeScript.NodeType.Typeof: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.stringType; - return this; - case TypeScript.NodeType.Delete: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.booleanType; - break; - case TypeScript.NodeType.TypeAssertion: - this.castTerm = typeFlow.typeCheck(this.castTerm); - var applyTargetType = !this.operand.isParenthesized; - var targetType = applyTargetType ? this.castTerm.type : null; - typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); - typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); - this.type = this.castTerm.type; - return this; - case TypeScript.NodeType.Void: - this.operand = typeFlow.typeCheck(this.operand); - this.type = typeFlow.checker.undefinedType; - break; - default: - throw new Error("please implement in derived class"); - } - return this; - }; - UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - switch(this.nodeType) { - case TypeScript.NodeType.IncPost: - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - emitter.writeToOutput("++"); - break; - case TypeScript.NodeType.LogNot: - emitter.writeToOutput("!"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); - break; - case TypeScript.NodeType.DecPost: - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - emitter.writeToOutput("--"); - break; - case TypeScript.NodeType.ObjectLit: - emitter.emitObjectLiteral(this.operand); - break; - case TypeScript.NodeType.ArrayLit: - emitter.emitArrayLiteral(this.operand); - break; - case TypeScript.NodeType.Not: - emitter.writeToOutput("~"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.Neg: - emitter.writeToOutput("-"); - if(this.operand.nodeType == TypeScript.NodeType.Neg) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); - break; - case TypeScript.NodeType.Pos: - emitter.writeToOutput("+"); - if(this.operand.nodeType == TypeScript.NodeType.Pos) { - this.operand.isParenthesized = true; - } - emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); - break; - case TypeScript.NodeType.IncPre: - emitter.writeToOutput("++"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); - break; - case TypeScript.NodeType.DecPre: - emitter.writeToOutput("--"); - emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); - break; - case TypeScript.NodeType.Throw: - emitter.writeToOutput("throw "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - emitter.writeToOutput(";"); - break; - case TypeScript.NodeType.Typeof: - emitter.writeToOutput("typeof "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.Delete: - emitter.writeToOutput("delete "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.Void: - emitter.writeToOutput("void "); - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - case TypeScript.NodeType.TypeAssertion: - emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); - break; - default: - throw new Error("please implement in derived class"); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return UnaryExpression; - })(Expression); - TypeScript.UnaryExpression = UnaryExpression; - var CallExpression = (function (_super) { - __extends(CallExpression, _super); - function CallExpression(nodeType, target, arguments) { - _super.call(this, nodeType); - this.target = target; - this.arguments = arguments; - this.signature = null; - this.minChar = this.target.minChar; - } - CallExpression.prototype.typeCheck = function (typeFlow) { - if(this.nodeType == TypeScript.NodeType.New) { - return typeFlow.typeCheckNew(this); - } else { - return typeFlow.typeCheckCall(this); - } - }; - CallExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.New) { - emitter.emitNew(this.target, this.arguments); - } else { - emitter.emitCall(this, this.target, this.arguments); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return CallExpression; - })(Expression); - TypeScript.CallExpression = CallExpression; - var BinaryExpression = (function (_super) { - __extends(BinaryExpression, _super); - function BinaryExpression(nodeType, operand1, operand2) { - _super.call(this, nodeType); - this.operand1 = operand1; - this.operand2 = operand2; - } - BinaryExpression.prototype.typeCheck = function (typeFlow) { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: - return typeFlow.typeCheckDotOperator(this); - case TypeScript.NodeType.Asg: - return typeFlow.typeCheckAsgOperator(this); - case TypeScript.NodeType.Add: - case TypeScript.NodeType.Sub: - case TypeScript.NodeType.Mul: - case TypeScript.NodeType.Div: - case TypeScript.NodeType.Mod: - case TypeScript.NodeType.Or: - case TypeScript.NodeType.And: - return typeFlow.typeCheckArithmeticOperator(this, false); - case TypeScript.NodeType.Xor: - return typeFlow.typeCheckBitwiseOperator(this, false); - case TypeScript.NodeType.Ne: - case TypeScript.NodeType.Eq: - var text; - if(typeFlow.checker.styleSettings.eqeqeq) { - text = TypeScript.nodeTypeTable[this.nodeType]; - typeFlow.checker.errorReporter.styleError(this, "use of " + text); - } else if(typeFlow.checker.styleSettings.eqnull) { - text = TypeScript.nodeTypeTable[this.nodeType]; - if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { - typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); - } - } - case TypeScript.NodeType.Eqv: - case TypeScript.NodeType.NEqv: - case TypeScript.NodeType.Lt: - case TypeScript.NodeType.Le: - case TypeScript.NodeType.Ge: - case TypeScript.NodeType.Gt: - return typeFlow.typeCheckBooleanOperator(this); - case TypeScript.NodeType.Index: - return typeFlow.typeCheckIndex(this); - case TypeScript.NodeType.Member: - this.type = typeFlow.voidType; - return this; - case TypeScript.NodeType.LogOr: - return typeFlow.typeCheckLogOr(this); - case TypeScript.NodeType.LogAnd: - return typeFlow.typeCheckLogAnd(this); - case TypeScript.NodeType.AsgAdd: - case TypeScript.NodeType.AsgSub: - case TypeScript.NodeType.AsgMul: - case TypeScript.NodeType.AsgDiv: - case TypeScript.NodeType.AsgMod: - case TypeScript.NodeType.AsgOr: - case TypeScript.NodeType.AsgAnd: - return typeFlow.typeCheckArithmeticOperator(this, true); - case TypeScript.NodeType.AsgXor: - return typeFlow.typeCheckBitwiseOperator(this, true); - case TypeScript.NodeType.Lsh: - case TypeScript.NodeType.Rsh: - case TypeScript.NodeType.Rs2: - return typeFlow.typeCheckShift(this, false); - case TypeScript.NodeType.AsgLsh: - case TypeScript.NodeType.AsgRsh: - case TypeScript.NodeType.AsgRs2: - return typeFlow.typeCheckShift(this, true); - case TypeScript.NodeType.Comma: - return typeFlow.typeCheckCommaOperator(this); - case TypeScript.NodeType.InstOf: - return typeFlow.typeCheckInstOf(this); - case TypeScript.NodeType.In: - return typeFlow.typeCheckInOperator(this); - case TypeScript.NodeType.From: - typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); - break; - default: - throw new Error("please implement in derived class"); - } - return this; - }; - BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { - var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(binTokenId != undefined) { - emitter.emitJavascript(this.operand1, binTokenId, false); - if(TypeScript.tokenTable[binTokenId].text == "instanceof") { - emitter.writeToOutput(" instanceof "); - } else if(TypeScript.tokenTable[binTokenId].text == "in") { - emitter.writeToOutput(" in "); - } else { - emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); - } - emitter.emitJavascript(this.operand2, binTokenId, false); - } else { - switch(this.nodeType) { - case TypeScript.NodeType.Dot: - if(!emitter.tryEmitConstant(this)) { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); - emitter.writeToOutput("."); - emitter.emitJavascriptName(this.operand2, false); - } - break; - case TypeScript.NodeType.Index: - emitter.emitIndex(this.operand1, this.operand2); - break; - case TypeScript.NodeType.Member: - if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { - var funcDecl = this.operand2; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - emitter.writeToOutput("get "); - } else { - emitter.writeToOutput("set "); - } - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - } else { - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); - emitter.writeToOutputTrimmable(": "); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - case TypeScript.NodeType.Comma: - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); - if(emitter.emitState.inObjectLiteral) { - emitter.writeLineToOutput(", "); - } else { - emitter.writeToOutput(","); - } - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); - break; - case TypeScript.NodeType.Is: - throw new Error("should be de-sugared during type check"); - default: - throw new Error("please implement in derived class"); - } - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return BinaryExpression; - })(Expression); - TypeScript.BinaryExpression = BinaryExpression; - var ConditionalExpression = (function (_super) { - __extends(ConditionalExpression, _super); - function ConditionalExpression(operand1, operand2, operand3) { - _super.call(this, TypeScript.NodeType.ConditionalExpression); - this.operand1 = operand1; - this.operand2 = operand2; - this.operand3 = operand3; - } - ConditionalExpression.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckQMark(this); - }; - ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" ? "); - emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); - emitter.writeToOutput(" : "); - emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ConditionalExpression; - })(Expression); - TypeScript.ConditionalExpression = ConditionalExpression; - var NumberLiteral = (function (_super) { - __extends(NumberLiteral, _super); - function NumberLiteral(value, text) { - _super.call(this, TypeScript.NodeType.NumberLit); - this.value = value; - this.text = text; - } - NumberLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.doubleType; - return this; - }; - NumberLiteral.prototype.treeViewLabel = function () { - return "num: " + this.printLabel(); - }; - NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - NumberLiteral.prototype.printLabel = function () { - return this.text; - }; - return NumberLiteral; - })(Expression); - TypeScript.NumberLiteral = NumberLiteral; - var RegexLiteral = (function (_super) { - __extends(RegexLiteral, _super); - function RegexLiteral(text) { - _super.call(this, TypeScript.NodeType.Regex); - this.text = text; - } - RegexLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.regexType; - return this; - }; - RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return RegexLiteral; - })(Expression); - TypeScript.RegexLiteral = RegexLiteral; - var StringLiteral = (function (_super) { - __extends(StringLiteral, _super); - function StringLiteral(text) { - _super.call(this, TypeScript.NodeType.QString); - this.text = text; - } - StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitStringLiteral(this.text); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - StringLiteral.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.stringType; - return this; - }; - StringLiteral.prototype.treeViewLabel = function () { - return "st: " + this.text; - }; - StringLiteral.prototype.printLabel = function () { - return this.text; - }; - return StringLiteral; - })(Expression); - TypeScript.StringLiteral = StringLiteral; - var ModuleElement = (function (_super) { - __extends(ModuleElement, _super); - function ModuleElement(nodeType) { - _super.call(this, nodeType); - } - return ModuleElement; - })(AST); - TypeScript.ModuleElement = ModuleElement; - var ImportDeclaration = (function (_super) { - __extends(ImportDeclaration, _super); - function ImportDeclaration(id, alias) { - _super.call(this, TypeScript.NodeType.ImportDeclaration); - this.id = id; - this.alias = alias; - this.varFlags = TypeScript.VarFlags.None; - this.isDynamicImport = false; - } - ImportDeclaration.prototype.isStatementOrExpression = function () { - return true; - }; - ImportDeclaration.prototype.isDeclaration = function () { - return true; - }; - ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - var mod = this.alias.type; - if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { - var prevModAliasId = emitter.modAliasId; - var prevFirstModAlias = emitter.firstModAlias; - emitter.recordSourceMappingStart(this); - emitter.emitParensAndCommentsInPlace(this, true); - emitter.writeToOutput("var " + this.id.actualText + " = "); - emitter.modAliasId = this.id.actualText; - emitter.firstModAlias = this.firstAliasedModToString(); - emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); - if(!this.isDynamicImport) { - emitter.writeToOutput(";"); - } - emitter.emitParensAndCommentsInPlace(this, false); - emitter.recordSourceMappingEnd(this); - emitter.modAliasId = prevModAliasId; - emitter.firstModAlias = prevFirstModAlias; - } - }; - ImportDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckImportDecl(this); - }; - ImportDeclaration.prototype.getAliasName = function (aliasAST) { - if (typeof aliasAST === "undefined") { aliasAST = this.alias; } - if(aliasAST.nodeType == TypeScript.NodeType.Name) { - return (aliasAST).actualText; - } else { - var dotExpr = aliasAST; - return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); - } - }; - ImportDeclaration.prototype.firstAliasedModToString = function () { - if(this.alias.nodeType == TypeScript.NodeType.Name) { - return (this.alias).actualText; - } else { - var dotExpr = this.alias; - var firstMod = dotExpr.operand1; - return firstMod.actualText; - } - }; - return ImportDeclaration; - })(ModuleElement); - TypeScript.ImportDeclaration = ImportDeclaration; - var BoundDecl = (function (_super) { - __extends(BoundDecl, _super); - function BoundDecl(id, nodeType, nestingLevel) { - _super.call(this, nodeType); - this.id = id; - this.nestingLevel = nestingLevel; - this.init = null; - this.typeExpr = null; - this.varFlags = TypeScript.VarFlags.None; - this.sym = null; - } - BoundDecl.prototype.isDeclaration = function () { - return true; - }; - BoundDecl.prototype.isStatementOrExpression = function () { - return true; - }; - BoundDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); - }; - BoundDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); - }; - BoundDecl.prototype.isProperty = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); - }; - BoundDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckBoundDecl(this); - }; - BoundDecl.prototype.printLabel = function () { - return this.treeViewLabel(); - }; - return BoundDecl; - })(AST); - TypeScript.BoundDecl = BoundDecl; - var VarDecl = (function (_super) { - __extends(VarDecl, _super); - function VarDecl(id, nest) { - _super.call(this, id, TypeScript.NodeType.VarDecl, nest); - } - VarDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - VarDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - VarDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); - }; - VarDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptVarDecl(this, tokenId); - }; - VarDecl.prototype.treeViewLabel = function () { - return "var " + this.id.actualText; - }; - return VarDecl; - })(BoundDecl); - TypeScript.VarDecl = VarDecl; - var ArgDecl = (function (_super) { - __extends(ArgDecl, _super); - function ArgDecl(id) { - _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); - this.isOptional = false; - this.parameterPropertySym = null; - } - ArgDecl.prototype.isOptionalArg = function () { - return this.isOptional || this.init; - }; - ArgDecl.prototype.treeViewLabel = function () { - return "arg: " + this.id.actualText; - }; - ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(this.id.actualText); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return ArgDecl; - })(BoundDecl); - TypeScript.ArgDecl = ArgDecl; - var internalId = 0; - var FuncDecl = (function (_super) { - __extends(FuncDecl, _super); - function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { - _super.call(this, nodeType); - this.name = name; - this.bod = bod; - this.isConstructor = isConstructor; - this.arguments = arguments; - this.vars = vars; - this.scopes = scopes; - this.statics = statics; - this.hint = null; - this.fncFlags = TypeScript.FncFlags.None; - this.returnTypeAnnotation = null; - this.variableArgList = false; - this.jumpRefs = null; - this.internalNameCache = null; - this.tmp1Declared = false; - this.enclosingFnc = null; - this.freeVariables = []; - this.unitIndex = -1; - this.classDecl = null; - this.boundToProperty = null; - this.isOverload = false; - this.innerStaticFuncs = []; - this.isInlineCallLiteral = false; - this.accessorSymbol = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.returnStatementsWithExpressions = []; - this.scopeType = null; - this.endingToken = null; - this.constructorSpan = null; - } - FuncDecl.prototype.isDeclaration = function () { - return true; - }; - FuncDecl.prototype.internalName = function () { - if(this.internalNameCache == null) { - var extName = this.getNameText(); - if(extName) { - this.internalNameCache = "_internal_" + extName; - } else { - this.internalNameCache = "_internal_" + internalId++; - } - } - return this.internalNameCache; - }; - FuncDecl.prototype.hasSelfReference = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); - }; - FuncDecl.prototype.setHasSelfReference = function () { - this.fncFlags |= TypeScript.FncFlags.HasSelfReference; - }; - FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); - }; - FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { - this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; - }; - FuncDecl.prototype.addCloRef = function (id, sym) { - if(this.envids == null) { - this.envids = new Array(); - } - this.envids[this.envids.length] = id; - var outerFnc = this.enclosingFnc; - if(sym) { - while(outerFnc && (outerFnc.type.symbol != sym.container)) { - outerFnc.addJumpRef(sym); - outerFnc = outerFnc.enclosingFnc; - } - } - return this.envids.length - 1; - }; - FuncDecl.prototype.addJumpRef = function (sym) { - if(this.jumpRefs == null) { - this.jumpRefs = new Array(); - } - var id = new Identifier(sym.name); - this.jumpRefs[this.jumpRefs.length] = id; - id.sym = sym; - id.cloId = this.addCloRef(id, null); - }; - FuncDecl.prototype.buildControlFlow = function () { - var entry = new TypeScript.BasicBlock(); - var exit = new TypeScript.BasicBlock(); - var context = new TypeScript.ControlFlowContext(entry, exit); - var controlFlowPrefix = function (ast, parent, walker) { - ast.addToControlFlow(walker.state); - return ast; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); - context.walker = walker; - walker.walk(this.bod, this); - return context; - }; - FuncDecl.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFunction(this); - }; - FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptFunction(this); - }; - FuncDecl.prototype.getNameText = function () { - if(this.name) { - return this.name.actualText; - } else { - return this.hint; - } - }; - FuncDecl.prototype.isMethod = function () { - return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isCallMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); - }; - FuncDecl.prototype.isConstructMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); - }; - FuncDecl.prototype.isIndexerMember = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); - }; - FuncDecl.prototype.isSpecialFn = function () { - return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); - }; - FuncDecl.prototype.isAnonymousFn = function () { - return this.name === null; - }; - FuncDecl.prototype.isAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isGetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); - }; - FuncDecl.prototype.isSetAccessor = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); - }; - FuncDecl.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); - }; - FuncDecl.prototype.isExported = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); - }; - FuncDecl.prototype.isPrivate = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); - }; - FuncDecl.prototype.isPublic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); - }; - FuncDecl.prototype.isStatic = function () { - return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); - }; - FuncDecl.prototype.treeViewLabel = function () { - if(this.name == null) { - return "funcExpr"; - } else { - return "func: " + this.name.actualText; - } - }; - FuncDecl.prototype.ClearFlags = function () { - this.fncFlags = TypeScript.FncFlags.None; - }; - FuncDecl.prototype.isSignature = function () { - return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; - }; - return FuncDecl; - })(AST); - TypeScript.FuncDecl = FuncDecl; - var LocationInfo = (function () { - function LocationInfo(filename, lineMap, unitIndex) { - this.filename = filename; - this.lineMap = lineMap; - this.unitIndex = unitIndex; - } - return LocationInfo; - })(); - TypeScript.LocationInfo = LocationInfo; - TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); - var Script = (function (_super) { - __extends(Script, _super); - function Script(vars, scopes) { - _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); - this.locationInfo = null; - this.referencedFiles = []; - this.requiresGlobal = false; - this.requiresExtendsBlock = false; - this.isResident = false; - this.isDeclareFile = false; - this.hasBeenTypeChecked = false; - this.topLevelMod = null; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.externallyVisibleImportedSymbols = []; - this.vars = vars; - } - Script.prototype.setCachedEmitRequired = function (value) { - this.cachedEmitRequired = value; - return this.cachedEmitRequired; - }; - Script.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckScript(this); - }; - Script.prototype.treeViewLabel = function () { - return "Script"; - }; - Script.prototype.emitRequired = function (emitOptions) { - if(this.cachedEmitRequired != undefined) { - return this.cachedEmitRequired; - } - if(!this.isDeclareFile && !this.isResident && this.bod) { - if(this.bod.members.length == 0) { - return this.setCachedEmitRequired(true); - } - for(var i = 0, len = this.bod.members.length; i < len; i++) { - var stmt = this.bod.members[i]; - if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { - if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType == TypeScript.NodeType.VarDecl) { - if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { - if(!(stmt).isSignature()) { - return this.setCachedEmitRequired(true); - } - } else if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { - return this.setCachedEmitRequired(true); - } - } - if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { - return this.setCachedEmitRequired(true); - } - } - return this.setCachedEmitRequired(false); - }; - Script.prototype.emit = function (emitter, tokenId, startLine) { - if(this.emitRequired(emitter.emitOptions)) { - emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); - } - }; - Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { - if(this.isExternallyVisibleSymbol(symbol)) { - return; - } - if(!symbol.getType().symbol.isExternallyVisible(checker)) { - var quotes = ""; - var moduleName = symbol.getType().symbol.prettyName; - if(!TypeScript.isQuoted(moduleName)) { - quotes = "'"; - } - checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); - } - this.externallyVisibleImportedSymbols.push(symbol); - }; - Script.prototype.isExternallyVisibleSymbol = function (symbol) { - for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { - if(this.externallyVisibleImportedSymbols[i] == symbol) { - return true; - } - } - return false; - }; - return Script; - })(FuncDecl); - TypeScript.Script = Script; - var NamedDeclaration = (function (_super) { - __extends(NamedDeclaration, _super); - function NamedDeclaration(nodeType, name, members) { - _super.call(this, nodeType); - this.name = name; - this.members = members; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - } - NamedDeclaration.prototype.isDeclaration = function () { - return true; - }; - return NamedDeclaration; - })(ModuleElement); - TypeScript.NamedDeclaration = NamedDeclaration; - var ModuleDeclaration = (function (_super) { - __extends(ModuleDeclaration, _super); - function ModuleDeclaration(name, members, vars, endingToken) { - _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); - this.endingToken = endingToken; - this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; - this.amdDependencies = []; - this.containsUnicodeChar = false; - this.containsUnicodeCharInComment = false; - this.vars = vars; - this.prettyName = this.name.actualText; - } - ModuleDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); - }; - ModuleDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); - }; - ModuleDeclaration.prototype.isEnum = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); - }; - ModuleDeclaration.prototype.isWholeFile = function () { - return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - ModuleDeclaration.prototype.recordNonInterface = function () { - this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - }; - ModuleDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckModule(this); - }; - ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.emitJavascriptModule(this); - emitter.emitParensAndCommentsInPlace(this, false); - } - }; - return ModuleDeclaration; - })(NamedDeclaration); - TypeScript.ModuleDeclaration = ModuleDeclaration; - var TypeDeclaration = (function (_super) { - __extends(TypeDeclaration, _super); - function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { - _super.call(this, nodeType, name, members); - this.extendsList = extendsList; - this.implementsList = implementsList; - this.varFlags = TypeScript.VarFlags.None; - } - TypeDeclaration.prototype.isExported = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); - }; - TypeDeclaration.prototype.isAmbient = function () { - return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); - }; - return TypeDeclaration; - })(NamedDeclaration); - TypeScript.TypeDeclaration = TypeDeclaration; - var ClassDeclaration = (function (_super) { - __extends(ClassDeclaration, _super); - function ClassDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); - this.knownMemberNames = { - }; - this.constructorDecl = null; - this.constructorNestingLevel = 0; - this.endingToken = null; - } - ClassDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckClass(this); - }; - ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitJavascriptClass(this); - }; - return ClassDeclaration; - })(TypeDeclaration); - TypeScript.ClassDeclaration = ClassDeclaration; - var InterfaceDeclaration = (function (_super) { - __extends(InterfaceDeclaration, _super); - function InterfaceDeclaration(name, members, extendsList, implementsList) { - _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); - } - InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckInterface(this); - }; - InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { - }; - return InterfaceDeclaration; - })(TypeDeclaration); - TypeScript.InterfaceDeclaration = InterfaceDeclaration; - var Statement = (function (_super) { - __extends(Statement, _super); - function Statement(nodeType) { - _super.call(this, nodeType); - this.flags |= TypeScript.ASTFlags.IsStatement; - } - Statement.prototype.isLoop = function () { - return false; - }; - Statement.prototype.isStatementOrExpression = function () { - return true; - }; - Statement.prototype.isCompoundStatement = function () { - return this.isLoop(); - }; - Statement.prototype.typeCheck = function (typeFlow) { - this.type = typeFlow.voidType; - return this; - }; - return Statement; - })(ModuleElement); - TypeScript.Statement = Statement; - var LabeledStatement = (function (_super) { - __extends(LabeledStatement, _super); - function LabeledStatement(labels, stmt) { - _super.call(this, TypeScript.NodeType.LabeledStatement); - this.labels = labels; - this.stmt = stmt; - } - LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.labels) { - var labelsLen = this.labels.members.length; - for(var i = 0; i < labelsLen; i++) { - this.labels.members[i].emit(emitter, tokenId, startLine); - } - } - this.stmt.emit(emitter, tokenId, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - LabeledStatement.prototype.typeCheck = function (typeFlow) { - typeFlow.typeCheck(this.labels); - this.stmt = this.stmt.typeCheck(typeFlow); - return this; - }; - LabeledStatement.prototype.addToControlFlow = function (context) { - var beforeBB = context.current; - var bb = new TypeScript.BasicBlock(); - context.current = bb; - beforeBB.addSuccessor(bb); - }; - return LabeledStatement; - })(Statement); - TypeScript.LabeledStatement = LabeledStatement; - var Block = (function (_super) { - __extends(Block, _super); - function Block(statements, isStatementBlock) { - _super.call(this, TypeScript.NodeType.Block); - this.statements = statements; - this.isStatementBlock = isStatementBlock; - } - Block.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.isStatementBlock) { - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - } else { - emitter.setInVarBlock(this.statements.members.length); - } - var temp = emitter.setInObjectLiteral(false); - if(this.statements) { - emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); - } - if(this.isStatementBlock) { - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Block.prototype.addToControlFlow = function (context) { - var afterIfNeeded = new TypeScript.BasicBlock(); - context.pushStatement(this, context.current, afterIfNeeded); - if(this.statements) { - context.walk(this.statements, this); - } - context.walker.options.goChildren = false; - context.popStatement(); - if(afterIfNeeded.predecessors.length > 0) { - context.current.addSuccessor(afterIfNeeded); - context.current = afterIfNeeded; - } - }; - Block.prototype.typeCheck = function (typeFlow) { - if(!typeFlow.checker.styleSettings.emptyBlocks) { - if((this.statements === null) || (this.statements.members.length == 0)) { - typeFlow.checker.errorReporter.styleError(this, "empty block"); - } - } - typeFlow.typeCheck(this.statements); - return this; - }; - return Block; - })(Statement); - TypeScript.Block = Block; - var Jump = (function (_super) { - __extends(Jump, _super); - function Jump(nodeType) { - _super.call(this, nodeType); - this.target = null; - this.resolvedTarget = null; - } - Jump.prototype.hasExplicitTarget = function () { - return (this.target); - }; - Jump.prototype.setResolvedTarget = function (parser, stmt) { - if(stmt.isLoop()) { - this.resolvedTarget = stmt; - return true; - } - if(this.nodeType === TypeScript.NodeType.Continue) { - parser.reportParseError("continue statement applies only to loops"); - return false; - } else { - if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { - this.resolvedTarget = stmt; - return true; - } else { - parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); - return false; - } - } - }; - Jump.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); - }; - Jump.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.nodeType == TypeScript.NodeType.Break) { - emitter.writeToOutput("break"); - } else { - emitter.writeToOutput("continue"); - } - if(this.hasExplicitTarget()) { - emitter.writeToOutput(" " + this.target); - } - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return Jump; - })(Statement); - TypeScript.Jump = Jump; - var WhileStatement = (function (_super) { - __extends(WhileStatement, _super); - function WhileStatement(cond) { - _super.call(this, TypeScript.NodeType.While); - this.cond = cond; - this.body = null; - } - WhileStatement.prototype.isLoop = function () { - return true; - }; - WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("while("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, false); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWhile(this); - }; - WhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - context.addContent(this.cond); - var condBlock = context.current; - var targetInfo = null; - if(this.body) { - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return WhileStatement; - })(Statement); - TypeScript.WhileStatement = WhileStatement; - var DoWhileStatement = (function (_super) { - __extends(DoWhileStatement, _super); - function DoWhileStatement() { - _super.call(this, TypeScript.NodeType.DoWhile); - this.body = null; - this.whileAST = null; - this.cond = null; - } - DoWhileStatement.prototype.isLoop = function () { - return true; - }; - DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("do"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingStart(this.whileAST); - emitter.writeToOutput("while"); - emitter.recordSourceMappingEnd(this.whileAST); - emitter.writeToOutput('('); - emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); - emitter.writeToOutput(")"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.writeToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - DoWhileStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckDoWhile(this); - }; - DoWhileStatement.prototype.addToControlFlow = function (context) { - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var targetInfo = null; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - context.addContent(this.cond); - context.current = afterLoop; - loopEnd.addSuccessor(afterLoop); - } else { - context.addUnreachable(this.cond); - } - context.walker.options.goChildren = false; - }; - return DoWhileStatement; - })(Statement); - TypeScript.DoWhileStatement = DoWhileStatement; - var IfStatement = (function (_super) { - __extends(IfStatement, _super); - function IfStatement(cond) { - _super.call(this, TypeScript.NodeType.If); - this.cond = cond; - this.elseBod = null; - this.statement = new ASTSpan(); - } - IfStatement.prototype.isCompoundStatement = function () { - return true; - }; - IfStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("if("); - emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.thenBod, true); - if(this.elseBod) { - if(this.elseBod.nodeType === TypeScript.NodeType.If) { - emitter.writeToOutput(" else "); - this.elseBod.emit(emitter, tokenId, false); - } else { - emitter.writeToOutput(" else"); - emitter.emitJavascriptStatements(this.elseBod, true); - } - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - IfStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckIf(this); - }; - IfStatement.prototype.addToControlFlow = function (context) { - this.cond.addToControlFlow(context); - var afterIf = new TypeScript.BasicBlock(); - var beforeIf = context.current; - context.pushStatement(this, beforeIf, afterIf); - var hasContinuation = false; - context.current = new TypeScript.BasicBlock(); - beforeIf.addSuccessor(context.current); - context.walk(this.thenBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } - if(this.elseBod) { - context.current = new TypeScript.BasicBlock(); - context.noContinuation = false; - beforeIf.addSuccessor(context.current); - context.walk(this.elseBod, this); - if(!context.noContinuation) { - hasContinuation = true; - context.current.addSuccessor(afterIf); - } else { - if(hasContinuation) { - context.noContinuation = false; - } - } - } else { - beforeIf.addSuccessor(afterIf); - context.noContinuation = false; - hasContinuation = true; - } - var targetInfo = context.popStatement(); - if(afterIf.predecessors.length > 0) { - context.noContinuation = false; - hasContinuation = true; - } - if(hasContinuation) { - context.current = afterIf; - } - context.walker.options.goChildren = false; - }; - return IfStatement; - })(Statement); - TypeScript.IfStatement = IfStatement; - var ReturnStatement = (function (_super) { - __extends(ReturnStatement, _super); - function ReturnStatement() { - _super.call(this, TypeScript.NodeType.Return); - this.returnExpression = null; - } - ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - if(this.returnExpression) { - emitter.writeToOutput("return "); - emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); - if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { - emitter.writeToOutput(";"); - } - } else { - emitter.writeToOutput("return;"); - } - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ReturnStatement.prototype.addToControlFlow = function (context) { - _super.prototype.addToControlFlow.call(this, context); - context.returnStmt(); - }; - ReturnStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckReturn(this); - }; - return ReturnStatement; - })(Statement); - TypeScript.ReturnStatement = ReturnStatement; - var EndCode = (function (_super) { - __extends(EndCode, _super); - function EndCode() { - _super.call(this, TypeScript.NodeType.EndCode); - } - return EndCode; - })(AST); - TypeScript.EndCode = EndCode; - var ForInStatement = (function (_super) { - __extends(ForInStatement, _super); - function ForInStatement(lval, obj) { - _super.call(this, TypeScript.NodeType.ForIn); - this.lval = lval; - this.obj = obj; - this.statement = new ASTSpan(); - if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { - (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; - } - } - ForInStatement.prototype.isLoop = function () { - return true; - }; - ForInStatement.prototype.isFiltered = function () { - if(this.body) { - var singleItem = null; - if(this.body.nodeType == TypeScript.NodeType.List) { - var stmts = this.body; - if(stmts.members.length == 1) { - singleItem = stmts.members[0]; - } - } else { - singleItem = this.body; - } - if(singleItem !== null) { - if(singleItem.nodeType == TypeScript.NodeType.Block) { - var block = singleItem; - if((block.statements !== null) && (block.statements.members.length == 1)) { - singleItem = block.statements.members[0]; - } - } - if(singleItem.nodeType == TypeScript.NodeType.If) { - var cond = (singleItem).cond; - if(cond.nodeType == TypeScript.NodeType.Call) { - var target = (cond).target; - if(target.nodeType == TypeScript.NodeType.Dot) { - var binex = target; - if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { - var prop = binex.operand2; - if(prop.actualText == "hasOwnProperty") { - var args = (cond).arguments; - if((args !== null) && (args.members.length == 1)) { - var arg = args.members[0]; - if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { - if(((this.lval).actualText) == (arg).actualText) { - return true; - } - } - } - } - } - } - } - } - } - } - return false; - }; - ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("for("); - emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); - emitter.writeToOutput(" in "); - emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForInStatement.prototype.typeCheck = function (typeFlow) { - if(typeFlow.checker.styleSettings.forin) { - if(!this.isFiltered()) { - typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); - } - } - return typeFlow.typeCheckForIn(this); - }; - ForInStatement.prototype.addToControlFlow = function (context) { - if(this.lval) { - context.addContent(this.lval); - } - if(this.obj) { - context.addContent(this.obj); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - if(this.body) { - context.pushStatement(this, loopStart, afterLoop); - context.walk(this.body, this); - context.popStatement(); - } - if(!(context.noContinuation)) { - var loopEnd = context.current; - loopEnd.addSuccessor(loopStart); - } - context.current = afterLoop; - context.noContinuation = false; - loopHeader.addSuccessor(afterLoop); - context.walker.options.goChildren = false; - }; - return ForInStatement; - })(Statement); - TypeScript.ForInStatement = ForInStatement; - var ForStatement = (function (_super) { - __extends(ForStatement, _super); - function ForStatement(init) { - _super.call(this, TypeScript.NodeType.For); - this.init = init; - } - ForStatement.prototype.isLoop = function () { - return true; - }; - ForStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.writeToOutput("for("); - if(this.init) { - if(this.init.nodeType != TypeScript.NodeType.List) { - emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); - } else { - emitter.setInVarBlock((this.init).members.length); - emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); - } - } - emitter.writeToOutput("; "); - emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); - emitter.writeToOutput("; "); - emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - ForStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckFor(this); - }; - ForStatement.prototype.addToControlFlow = function (context) { - if(this.init) { - context.addContent(this.init); - } - var loopHeader = context.current; - var loopStart = new TypeScript.BasicBlock(); - var afterLoop = new TypeScript.BasicBlock(); - loopHeader.addSuccessor(loopStart); - context.current = loopStart; - var condBlock = null; - var continueTarget = loopStart; - var incrBB = null; - if(this.incr) { - incrBB = new TypeScript.BasicBlock(); - continueTarget = incrBB; - } - if(this.cond) { - condBlock = context.current; - context.addContent(this.cond); - context.current = new TypeScript.BasicBlock(); - condBlock.addSuccessor(context.current); - } - var targetInfo = null; - if(this.body) { - context.pushStatement(this, continueTarget, afterLoop); - context.walk(this.body, this); - targetInfo = context.popStatement(); - } - if(this.incr) { - if(context.noContinuation) { - if(incrBB.predecessors.length == 0) { - context.addUnreachable(this.incr); - } - } else { - context.current.addSuccessor(incrBB); - context.current = incrBB; - context.addContent(this.incr); - } - } - var loopEnd = context.current; - if(!(context.noContinuation)) { - loopEnd.addSuccessor(loopStart); - } - if(condBlock) { - condBlock.addSuccessor(afterLoop); - context.noContinuation = false; - } - if(afterLoop.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterLoop; - } - context.walker.options.goChildren = false; - }; - return ForStatement; - })(Statement); - TypeScript.ForStatement = ForStatement; - var WithStatement = (function (_super) { - __extends(WithStatement, _super); - function WithStatement(expr) { - _super.call(this, TypeScript.NodeType.With); - this.expr = expr; - this.withSym = null; - } - WithStatement.prototype.isCompoundStatement = function () { - return true; - }; - WithStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("with ("); - if(this.expr) { - emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); - } - emitter.writeToOutput(")"); - emitter.emitJavascriptStatements(this.body, true); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - WithStatement.prototype.typeCheck = function (typeFlow) { - return typeFlow.typeCheckWith(this); - }; - return WithStatement; - })(Statement); - TypeScript.WithStatement = WithStatement; - var SwitchStatement = (function (_super) { - __extends(SwitchStatement, _super); - function SwitchStatement(val) { - _super.call(this, TypeScript.NodeType.Switch); - this.val = val; - this.defaultCase = null; - this.statement = new ASTSpan(); - } - SwitchStatement.prototype.isCompoundStatement = function () { - return true; - }; - SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - var temp = emitter.setInObjectLiteral(false); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("switch("); - emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.writeLineToOutput(" {"); - emitter.indenter.increaseIndent(); - var casesLen = this.caseList.members.length; - for(var i = 0; i < casesLen; i++) { - var caseExpr = this.caseList.members[i]; - emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); - } - emitter.indenter.decreaseIndent(); - emitter.emitIndent(); - emitter.writeToOutput("}"); - emitter.setInObjectLiteral(temp); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - SwitchStatement.prototype.typeCheck = function (typeFlow) { - var len = this.caseList.members.length; - this.val = typeFlow.typeCheck(this.val); - for(var i = 0; i < len; i++) { - this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); - } - this.defaultCase = typeFlow.typeCheck(this.defaultCase); - this.type = typeFlow.voidType; - return this; - }; - SwitchStatement.prototype.addToControlFlow = function (context) { - var condBlock = context.current; - context.addContent(this.val); - var execBlock = new TypeScript.BasicBlock(); - var afterSwitch = new TypeScript.BasicBlock(); - condBlock.addSuccessor(execBlock); - context.pushSwitch(execBlock); - context.current = execBlock; - context.pushStatement(this, execBlock, afterSwitch); - context.walk(this.caseList, this); - context.popSwitch(); - var targetInfo = context.popStatement(); - var hasCondContinuation = (this.defaultCase == null); - if(this.defaultCase == null) { - condBlock.addSuccessor(afterSwitch); - } - if(afterSwitch.predecessors.length > 0) { - context.noContinuation = false; - context.current = afterSwitch; - } else { - context.noContinuation = true; - } - context.walker.options.goChildren = false; - }; - return SwitchStatement; - })(Statement); - TypeScript.SwitchStatement = SwitchStatement; - var CaseStatement = (function (_super) { - __extends(CaseStatement, _super); - function CaseStatement() { - _super.call(this, TypeScript.NodeType.Case); - this.expr = null; - this.colonSpan = new ASTSpan(); - } - CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - if(this.expr) { - emitter.writeToOutput("case "); - emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); - } else { - emitter.writeToOutput("default"); - } - emitter.recordSourceMappingStart(this.colonSpan); - emitter.writeToOutput(":"); - emitter.recordSourceMappingEnd(this.colonSpan); - if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { - emitter.emitJavascriptStatements(this.body, false); - } else { - emitter.writeLineToOutput(""); - emitter.indenter.increaseIndent(); - emitter.emitBareJavascriptStatements(this.body); - emitter.indenter.decreaseIndent(); - } - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - CaseStatement.prototype.typeCheck = function (typeFlow) { - this.expr = typeFlow.typeCheck(this.expr); - typeFlow.typeCheck(this.body); - this.type = typeFlow.voidType; - return this; - }; - CaseStatement.prototype.addToControlFlow = function (context) { - var execBlock = new TypeScript.BasicBlock(); - var sw = context.currentSwitch[context.currentSwitch.length - 1]; - if(this.expr) { - var exprBlock = new TypeScript.BasicBlock(); - context.current = exprBlock; - sw.addSuccessor(exprBlock); - context.addContent(this.expr); - exprBlock.addSuccessor(execBlock); - } else { - sw.addSuccessor(execBlock); - } - context.current = execBlock; - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - return CaseStatement; - })(Statement); - TypeScript.CaseStatement = CaseStatement; - var TypeReference = (function (_super) { - __extends(TypeReference, _super); - function TypeReference(term, arrayCount) { - _super.call(this, TypeScript.NodeType.TypeRef); - this.term = term; - this.arrayCount = arrayCount; - } - TypeReference.prototype.emit = function (emitter, tokenId, startLine) { - throw new Error("should not emit a type ref"); - }; - TypeReference.prototype.typeCheck = function (typeFlow) { - var prevInTCTR = typeFlow.inTypeRefTypeCheck; - typeFlow.inTypeRefTypeCheck = true; - var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); - typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); - if(this.term) { - typeFlow.typeCheck(this.term); - } - typeFlow.checkForVoidConstructor(typeLink.type, this); - this.type = typeLink.type; - if(this.term) { - this.term.type = this.type; - } - typeFlow.inTypeRefTypeCheck = prevInTCTR; - return this; - }; - return TypeReference; - })(AST); - TypeScript.TypeReference = TypeReference; - var TryFinally = (function (_super) { - __extends(TryFinally, _super); - function TryFinally(tryNode, finallyNode) { - _super.call(this, TypeScript.NodeType.TryFinally); - this.tryNode = tryNode; - this.finallyNode = finallyNode; - } - TryFinally.prototype.isCompoundStatement = function () { - return true; - }; - TryFinally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - }; - TryFinally.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.finallyNode = typeFlow.typeCheck(this.finallyNode); - this.type = typeFlow.voidType; - return this; - }; - TryFinally.prototype.addToControlFlow = function (context) { - var afterFinally = new TypeScript.BasicBlock(); - context.walk(this.tryNode, this); - var finBlock = new TypeScript.BasicBlock(); - if(context.current) { - context.current.addSuccessor(finBlock); - } - context.current = finBlock; - context.pushStatement(this, null, afterFinally); - context.walk(this.finallyNode, this); - if(!context.noContinuation && context.current) { - context.current.addSuccessor(afterFinally); - } - if(afterFinally.predecessors.length > 0) { - context.current = afterFinally; - } else { - context.noContinuation = true; - } - context.popStatement(); - context.walker.options.goChildren = false; - }; - return TryFinally; - })(Statement); - TypeScript.TryFinally = TryFinally; - var TryCatch = (function (_super) { - __extends(TryCatch, _super); - function TryCatch(tryNode, catchNode) { - _super.call(this, TypeScript.NodeType.TryCatch); - this.tryNode = tryNode; - this.catchNode = catchNode; - } - TryCatch.prototype.isCompoundStatement = function () { - return true; - }; - TryCatch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); - emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - TryCatch.prototype.addToControlFlow = function (context) { - var beforeTry = context.current; - var tryBlock = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(tryBlock); - context.current = tryBlock; - var afterTryCatch = new TypeScript.BasicBlock(); - context.pushStatement(this, null, afterTryCatch); - context.walk(this.tryNode, this); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = new TypeScript.BasicBlock(); - beforeTry.addSuccessor(context.current); - context.walk(this.catchNode, this); - context.popStatement(); - if(!context.noContinuation) { - if(context.current) { - context.current.addSuccessor(afterTryCatch); - } - } - context.current = afterTryCatch; - context.walker.options.goChildren = false; - }; - TryCatch.prototype.typeCheck = function (typeFlow) { - this.tryNode = typeFlow.typeCheck(this.tryNode); - this.catchNode = typeFlow.typeCheck(this.catchNode); - this.type = typeFlow.voidType; - return this; - }; - return TryCatch; - })(Statement); - TypeScript.TryCatch = TryCatch; - var Try = (function (_super) { - __extends(Try, _super); - function Try(body) { - _super.call(this, TypeScript.NodeType.Try); - this.body = body; - } - Try.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("try "); - emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Try.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - Try.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - return Try; - })(Statement); - TypeScript.Try = Try; - var Catch = (function (_super) { - __extends(Catch, _super); - function Catch(param, body) { - _super.call(this, TypeScript.NodeType.Catch); - this.param = param; - this.body = body; - this.statement = new ASTSpan(); - this.containedScope = null; - if(this.param) { - this.param.varFlags |= TypeScript.VarFlags.AutoInit; - } - } - Catch.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput(" "); - emitter.recordSourceMappingStart(this.statement); - emitter.writeToOutput("catch ("); - emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); - emitter.writeToOutput(")"); - emitter.recordSourceMappingEnd(this.statement); - emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Catch.prototype.addToControlFlow = function (context) { - if(this.param) { - context.addContent(this.param); - var bodBlock = new TypeScript.BasicBlock(); - context.current.addSuccessor(bodBlock); - context.current = bodBlock; - } - if(this.body) { - context.walk(this.body, this); - } - context.noContinuation = false; - context.walker.options.goChildren = false; - }; - Catch.prototype.typeCheck = function (typeFlow) { - var prevScope = typeFlow.scope; - typeFlow.scope = this.containedScope; - this.param = typeFlow.typeCheck(this.param); - var exceptVar = new TypeScript.ValueLocation(); - var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); - exceptVar.symbol = varSym; - exceptVar.typeLink = new TypeScript.TypeLink(); - exceptVar.typeLink.type = typeFlow.anyType; - var thisFnc = typeFlow.thisFnc; - if(thisFnc && thisFnc.type) { - exceptVar.symbol.container = thisFnc.type.symbol; - } else { - exceptVar.symbol.container = null; - } - this.param.sym = exceptVar.symbol; - typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); - this.body = typeFlow.typeCheck(this.body); - if(typeFlow.checker.inProvisionalTypecheckMode()) { - var table = typeFlow.scope.getTable(); - (table).secondaryTable.table[exceptVar.symbol.name] = undefined; - } - this.type = typeFlow.voidType; - typeFlow.scope = prevScope; - return this; - }; - return Catch; - })(Statement); - TypeScript.Catch = Catch; - var Finally = (function (_super) { - __extends(Finally, _super); - function Finally(body) { - _super.call(this, TypeScript.NodeType.Finally); - this.body = body; - } - Finally.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("finally"); - emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); - emitter.recordSourceMappingEnd(this); - emitter.emitParensAndCommentsInPlace(this, false); - }; - Finally.prototype.addToControlFlow = function (context) { - if(this.body) { - context.walk(this.body, this); - } - context.walker.options.goChildren = false; - context.noContinuation = false; - }; - Finally.prototype.typeCheck = function (typeFlow) { - this.body = typeFlow.typeCheck(this.body); - return this; - }; - return Finally; - })(Statement); - TypeScript.Finally = Finally; - var Comment = (function (_super) { - __extends(Comment, _super); - function Comment(content, isBlockComment, endsLine) { - _super.call(this, TypeScript.NodeType.Comment); - this.content = content; - this.isBlockComment = isBlockComment; - this.endsLine = endsLine; - this.text = null; - this.docCommentText = null; - } - Comment.prototype.getText = function () { - if(this.text == null) { - if(this.isBlockComment) { - this.text = this.content.split("\n"); - for(var i = 0; i < this.text.length; i++) { - this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); - } - } else { - this.text = [ - (this.content.replace(/^\s+|\s+$/g, '')) - ]; - } - } - return this.text; - }; - Comment.prototype.isDocComment = function () { - if(this.isBlockComment) { - return this.content.charAt(2) == "*" && this.content.charAt(3) != "/"; - } - return false; - }; - Comment.prototype.getDocCommentText = function () { - if(this.docCommentText == null) { - this.docCommentText = Comment.cleanJSDocComment(this.content); - } - return this.docCommentText; - }; - Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { - var endIndex = line.length; - if(maxSpacesToRemove != undefined) { - endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); - } - for(; startIndex < endIndex; startIndex++) { - var charCode = line.charCodeAt(startIndex); - if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { - return startIndex; - } - } - if(endIndex != line.length) { - return endIndex; - } - return -1; - }; - Comment.isSpaceChar = function isSpaceChar(line, index) { - var length = line.length; - if(index < length) { - var charCode = line.charCodeAt(index); - return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; - } - return index == length; - }; - Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { - var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); - if(nonSpaceIndex != -1) { - var jsDocSpacesRemoved = nonSpaceIndex; - if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { - var startIndex = nonSpaceIndex + 1; - nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); - if(nonSpaceIndex != -1) { - jsDocSpacesRemoved = nonSpaceIndex - startIndex; - } else { - return null; - } - } - return { - minChar: nonSpaceIndex, - limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, - jsDocSpacesRemoved: jsDocSpacesRemoved - }; - } - return null; - }; - Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { - var docCommentLines = []; - content = content.replace("/**", ""); - if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { - content = content.substring(0, content.length - 2); - } - var lines = content.split("\n"); - var inParamTag = false; - for(var l = 0; l < lines.length; l++) { - var line = lines[l]; - var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); - if(!cleanLinePos) { - continue; - } - var docCommentText = ""; - var prevPos = cleanLinePos.minChar; - for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { - var wasInParamtag = inParamTag; - if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { - if(!wasInParamtag) { - docCommentText += line.substring(prevPos, i); - } - prevPos = i; - inParamTag = true; - } else if(wasInParamtag) { - prevPos = i; - inParamTag = false; - } - } - if(!inParamTag) { - docCommentText += line.substring(prevPos, cleanLinePos.limChar); - } - var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); - if(newCleanPos) { - if(spacesToRemove == undefined) { - spacesToRemove = cleanLinePos.jsDocSpacesRemoved; - } - docCommentLines.push(docCommentText); - } - } - return docCommentLines.join("\n"); - }; - Comment.getDocCommentText = function getDocCommentText(comments) { - var docCommentText = []; - for(var c = 0; c < comments.length; c++) { - var commentText = comments[c].getDocCommentText(); - if(commentText != "") { - docCommentText.push(commentText); - } - } - return docCommentText.join("\n"); - }; - Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { - if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { - return ""; - } - for(var i = 0; i < fncDocComments.length; i++) { - var commentContents = fncDocComments[i].content; - for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { - j += 6; - if(!Comment.isSpaceChar(commentContents, j)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j); - if(j == -1) { - break; - } - if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { - j++; - var charCode = 0; - for(var curlies = 1; j < commentContents.length; j++) { - charCode = commentContents.charCodeAt(j); - if(charCode == TypeScript.LexCodeLC) { - curlies++; - continue; - } - if(charCode == TypeScript.LexCodeRC) { - curlies--; - if(curlies == 0) { - break; - } else { - continue; - } - } - if(charCode == TypeScript.LexCodeAtSign) { - break; - } - } - if(j == commentContents.length) { - break; - } - if(charCode == TypeScript.LexCodeAtSign) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + 1); - if(j == -1) { - break; - } - } - if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { - continue; - } - j = Comment.consumeLeadingSpace(commentContents, j + param.length); - if(j == -1) { - return ""; - } - var endOfParam = commentContents.indexOf("@", j); - var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); - var paramSpacesToRemove = undefined; - var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; - if(paramLineIndex != 0) { - if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { - paramLineIndex++; - } - } - var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); - if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { - paramSpacesToRemove = j - startSpaceRemovalIndex - 1; - } - return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); - } - } - return ""; - }; - Comment.getDocCommentFirstOverloadSignature = function getDocCommentFirstOverloadSignature(signatureGroup) { - for(var i = 0; i < signatureGroup.signatures.length; i++) { - var signature = signatureGroup.signatures[i]; - if(signature == signatureGroup.definitionSignature) { - continue; - } - return TypeScript.Comment.getDocCommentText(signature.declAST.getDocComments()); - } - return ""; - }; - return Comment; - })(AST); - TypeScript.Comment = Comment; - var DebuggerStatement = (function (_super) { - __extends(DebuggerStatement, _super); - function DebuggerStatement() { - _super.call(this, TypeScript.NodeType.Debugger); - } - DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { - emitter.emitParensAndCommentsInPlace(this, true); - emitter.recordSourceMappingStart(this); - emitter.writeToOutput("debugger"); - emitter.recordSourceMappingEnd(this); - emitter.writeLineToOutput(";"); - emitter.emitParensAndCommentsInPlace(this, false); - }; - return DebuggerStatement; - })(Statement); - TypeScript.DebuggerStatement = DebuggerStatement; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstWalkOptions = (function () { - function AstWalkOptions() { - this.goChildren = true; - this.goNextSibling = true; - this.reverseSiblings = false; - } - AstWalkOptions.prototype.stopWalk = function (stop) { - if (typeof stop === "undefined") { stop = true; } - this.goChildren = !stop; - this.goNextSibling = !stop; - }; - return AstWalkOptions; - })(); - TypeScript.AstWalkOptions = AstWalkOptions; - var AstWalker = (function () { - function AstWalker(childrenWalkers, pre, post, options, state) { - this.childrenWalkers = childrenWalkers; - this.pre = pre; - this.post = post; - this.options = options; - this.state = state; - } - AstWalker.prototype.walk = function (ast, parent) { - var preAst = this.pre(ast, parent, this); - if(preAst === undefined) { - preAst = ast; - } - if(this.options.goChildren) { - var svGoSib = this.options.goNextSibling; - this.options.goNextSibling = true; - this.childrenWalkers[ast.nodeType](ast, parent, this); - this.options.goNextSibling = svGoSib; - } else { - this.options.goChildren = true; - } - if(this.post) { - var postAst = this.post(preAst, parent, this); - if(postAst === undefined) { - postAst = preAst; - } - return postAst; - } else { - return preAst; - } - }; - return AstWalker; - })(); - var AstWalkerFactory = (function () { - function AstWalkerFactory() { - this.childrenWalkers = []; - this.initChildrenWalkers(); - } - AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { - return this.getWalker(pre, post, options, state).walk(ast, null); - }; - AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { - return this.getSlowWalker(pre, post, options, state); - }; - AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { - if(!options) { - options = new AstWalkOptions(); - } - return new AstWalker(this.childrenWalkers, pre, post, options, state); - }; - AstWalkerFactory.prototype.initChildrenWalkers = function () { - this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; - this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; - this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; - this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; - this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; - this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; - this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; - this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; - this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; - this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; - this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; - this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; - this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; - this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; - this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; - this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; - this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; - this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; - this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; - this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; - this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; - for(var e in (TypeScript.NodeType)._map) { - if((this.childrenWalkers)[e] === undefined) { - throw new Error("initWalkers function is not up to date with enum content!"); - } - } - }; - return AstWalkerFactory; - })(); - TypeScript.AstWalkerFactory = AstWalkerFactory; - var globalAstWalkerFactory; - function getAstWalkerFactory() { - if(!globalAstWalkerFactory) { - globalAstWalkerFactory = new AstWalkerFactory(); - } - return globalAstWalkerFactory; - } - TypeScript.getAstWalkerFactory = getAstWalkerFactory; - var ChildrenWalkers; - (function (ChildrenWalkers) { - function walkNone(preAst, parent, walker) { - } - ChildrenWalkers.walkNone = walkNone; - function walkListChildren(preAst, parent, walker) { - var len = preAst.members.length; - if(walker.options.reverseSiblings) { - for(var i = len - 1; i >= 0; i--) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } else { - for(var i = 0; i < len; i++) { - if(walker.options.goNextSibling) { - preAst.members[i] = walker.walk(preAst.members[i], preAst); - } - } - } - } - ChildrenWalkers.walkListChildren = walkListChildren; - function walkUnaryExpressionChildren(preAst, parent, walker) { - if(preAst.castTerm) { - preAst.castTerm = walker.walk(preAst.castTerm, preAst); - } - if(preAst.operand) { - preAst.operand = walker.walk(preAst.operand, preAst); - } - } - ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; - function walkBinaryExpressionChildren(preAst, parent, walker) { - if(walker.options.reverseSiblings) { - if(preAst.operand2) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if((preAst.operand1) && (walker.options.goNextSibling)) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - } else { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if((preAst.operand2) && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - } - } - ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; - function walkTypeReferenceChildren(preAst, parent, walker) { - if(preAst.term) { - preAst.term = walker.walk(preAst.term, preAst); - } - } - ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; - function walkCallExpressionChildren(preAst, parent, walker) { - if(!walker.options.reverseSiblings) { - preAst.target = walker.walk(preAst.target, preAst); - } - if(preAst.arguments && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { - preAst.target = walker.walk(preAst.target, preAst); - } - } - ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; - function walkTrinaryExpressionChildren(preAst, parent, walker) { - if(preAst.operand1) { - preAst.operand1 = walker.walk(preAst.operand1, preAst); - } - if(preAst.operand2 && (walker.options.goNextSibling)) { - preAst.operand2 = walker.walk(preAst.operand2, preAst); - } - if(preAst.operand3 && (walker.options.goNextSibling)) { - preAst.operand3 = walker.walk(preAst.operand3, preAst); - } - } - ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; - function walkFuncDeclChildren(preAst, parent, walker) { - if(preAst.name) { - preAst.name = walker.walk(preAst.name, preAst); - } - if(preAst.arguments && (walker.options.goNextSibling)) { - preAst.arguments = walker.walk(preAst.arguments, preAst); - } - if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { - preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); - } - if(preAst.bod && (walker.options.goNextSibling)) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; - function walkBoundDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if((preAst.typeExpr) && (walker.options.goNextSibling)) { - preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); - } - } - ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; - function walkReturnStatementChildren(preAst, parent, walker) { - if(preAst.returnExpression) { - preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); - } - } - ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; - function walkForStatementChildren(preAst, parent, walker) { - if(preAst.init) { - preAst.init = walker.walk(preAst.init, preAst); - } - if(preAst.cond && walker.options.goNextSibling) { - preAst.cond = walker.walk(preAst.cond, preAst); - } - if(preAst.incr && walker.options.goNextSibling) { - preAst.incr = walker.walk(preAst.incr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; - function walkForInStatementChildren(preAst, parent, walker) { - preAst.lval = walker.walk(preAst.lval, preAst); - if(walker.options.goNextSibling) { - preAst.obj = walker.walk(preAst.obj, preAst); - } - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; - function walkIfStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.thenBod && (walker.options.goNextSibling)) { - preAst.thenBod = walker.walk(preAst.thenBod, preAst); - } - if(preAst.elseBod && (walker.options.goNextSibling)) { - preAst.elseBod = walker.walk(preAst.elseBod, preAst); - } - } - ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; - function walkWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; - function walkDoWhileStatementChildren(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst); - if(preAst.body && (walker.options.goNextSibling)) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; - function walkBlockChildren(preAst, parent, walker) { - if(preAst.statements) { - preAst.statements = walker.walk(preAst.statements, preAst); - } - } - ChildrenWalkers.walkBlockChildren = walkBlockChildren; - function walkCaseStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; - function walkSwitchStatementChildren(preAst, parent, walker) { - if(preAst.val) { - preAst.val = walker.walk(preAst.val, preAst); - } - if((preAst.caseList) && walker.options.goNextSibling) { - preAst.caseList = walker.walk(preAst.caseList, preAst); - } - } - ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; - function walkTryChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkTryChildren = walkTryChildren; - function walkTryCatchChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if((preAst.catchNode) && walker.options.goNextSibling) { - preAst.catchNode = walker.walk(preAst.catchNode, preAst); - } - } - ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; - function walkTryFinallyChildren(preAst, parent, walker) { - if(preAst.tryNode) { - preAst.tryNode = walker.walk(preAst.tryNode, preAst); - } - if(preAst.finallyNode && walker.options.goNextSibling) { - preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); - } - } - ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; - function walkFinallyChildren(preAst, parent, walker) { - if(preAst.body) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; - function walkCatchChildren(preAst, parent, walker) { - if(preAst.param) { - preAst.param = walker.walk(preAst.param, preAst); - } - if((preAst.body) && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkCatchChildren = walkCatchChildren; - function walkRecordChildren(preAst, parent, walker) { - preAst.name = walker.walk(preAst.name, preAst); - if(walker.options.goNextSibling && preAst.members) { - preAst.members = walker.walk(preAst.members, preAst); - } - } - ChildrenWalkers.walkRecordChildren = walkRecordChildren; - function walkNamedTypeChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; - function walkClassDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; - function walkScriptChildren(preAst, parent, walker) { - if(preAst.bod) { - preAst.bod = walker.walk(preAst.bod, preAst); - } - } - ChildrenWalkers.walkScriptChildren = walkScriptChildren; - function walkTypeDeclChildren(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker); - if(walker.options.goNextSibling && preAst.extendsList) { - preAst.extendsList = walker.walk(preAst.extendsList, preAst); - } - if(walker.options.goNextSibling && preAst.implementsList) { - preAst.implementsList = walker.walk(preAst.implementsList, preAst); - } - } - ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; - function walkModuleDeclChildren(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); - } - ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; - function walkImportDeclChildren(preAst, parent, walker) { - if(preAst.id) { - preAst.id = walker.walk(preAst.id, preAst); - } - if(preAst.alias) { - preAst.alias = walker.walk(preAst.alias, preAst); - } - } - ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; - function walkWithStatementChildren(preAst, parent, walker) { - if(preAst.expr) { - preAst.expr = walker.walk(preAst.expr, preAst); - } - if(preAst.body && walker.options.goNextSibling) { - preAst.body = walker.walk(preAst.body, preAst); - } - } - ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; - function walkLabelChildren(preAst, parent, walker) { - } - ChildrenWalkers.walkLabelChildren = walkLabelChildren; - function walkLabeledStatementChildren(preAst, parent, walker) { - preAst.labels = walker.walk(preAst.labels, preAst); - if(walker.options.goNextSibling) { - preAst.stmt = walker.walk(preAst.stmt, preAst); - } - } - ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; - })(ChildrenWalkers || (ChildrenWalkers = {})); -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (AstWalkerWithDetailCallback) { - function walk(script, callback) { - var pre = function (cur, parent) { - walker.options.goChildren = AstWalkerCallback(true, cur, callback); - return cur; - }; - var post = function (cur, parent) { - AstWalkerCallback(false, cur, callback); - return cur; - }; - var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); - walker.walk(script, null); - } - AstWalkerWithDetailCallback.walk = walk; - function AstWalkerCallback(pre, ast, callback) { - var nodeType = ast.nodeType; - var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; - if(callback[callbackString]) { - return callback[callbackString](pre, ast); - } - if(callback.DefaultCallback) { - return callback.DefaultCallback(pre, ast); - } - return true; - } - })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); - var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function lastOf(items) { - return (items === null || items.length === 0) ? null : items[items.length - 1]; - } - TypeScript.lastOf = lastOf; - function max(a, b) { - return a >= b ? a : b; - } - TypeScript.max = max; - function min(a, b) { - return a <= b ? a : b; - } - TypeScript.min = min; - var AstPath = (function () { - function AstPath() { - this.asts = []; - this.top = -1; - } - AstPath.reverseIndexOf = function reverseIndexOf(items, index) { - return (items === null || items.length <= index) ? null : items[items.length - index - 1]; - }; - AstPath.prototype.clone = function () { - var clone = new AstPath(); - clone.asts = this.asts.map(function (value) { - return value; - }); - clone.top = this.top; - return clone; - }; - AstPath.prototype.pop = function () { - var head = this.ast(); - this.up(); - while(this.asts.length > this.count()) { - this.asts.pop(); - } - return head; - }; - AstPath.prototype.push = function (ast) { - while(this.asts.length > this.count()) { - this.asts.pop(); - } - this.top = this.asts.length; - this.asts.push(ast); - }; - AstPath.prototype.up = function () { - if(this.top <= -1) { - throw new Error("Invalid call to 'up'"); - } - this.top--; - }; - AstPath.prototype.down = function () { - if(this.top == this.ast.length - 1) { - throw new Error("Invalid call to 'down'"); - } - this.top++; - }; - AstPath.prototype.nodeType = function () { - if(this.ast() == null) { - return TypeScript.NodeType.None; - } - return this.ast().nodeType; - }; - AstPath.prototype.ast = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); - }; - AstPath.prototype.parent = function () { - return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); - }; - AstPath.prototype.count = function () { - return this.top + 1; - }; - AstPath.prototype.get = function (index) { - return this.asts[index]; - }; - AstPath.prototype.isNameOfClass = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfInterface = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfArgument = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfVariable = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); - }; - AstPath.prototype.isNameOfModule = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isNameOfFunction = function () { - if(this.ast() === null || this.parent() === null) { - return false; - } - return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); - }; - AstPath.prototype.isChildOfScript = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; - }; - AstPath.prototype.isChildOfModule = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; - }; - AstPath.prototype.isChildOfClass = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; - }; - AstPath.prototype.isArgumentOfClassConstructor = function () { - var ast = lastOf(this.asts); - return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); - }; - AstPath.prototype.isChildOfInterface = function () { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; - }; - AstPath.prototype.isTopLevelImplicitModule = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); - }; - AstPath.prototype.isBodyOfScript = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfSwitch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfModule = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfClass = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfInterface = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfBlock = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFor = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCase = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfTry = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfCatch = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDoWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWhile = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfForIn = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfWith = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfFinally = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; - }; - AstPath.prototype.isCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; - }; - AstPath.prototype.isDefaultCaseOfSwitch = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; - }; - AstPath.prototype.isListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfObjectLit = function () { - return this.isListOfObjectLit(); - }; - AstPath.prototype.isEmptyListOfObjectLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; - }; - AstPath.prototype.isMemberOfObjectLit = function () { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; - }; - AstPath.prototype.isNameOfMemberOfObjectLit = function () { - return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; - }; - AstPath.prototype.isListOfArrayLit = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; - }; - AstPath.prototype.isTargetOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; - }; - AstPath.prototype.isMemberOfMember = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; - }; - AstPath.prototype.isItemOfList = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; - }; - AstPath.prototype.isThenOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isElseOfIf = function () { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; - }; - AstPath.prototype.isBodyOfDefaultCase = function () { - return this.isBodyOfCase(); - }; - AstPath.prototype.isSingleStatementList = function () { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; - }; - AstPath.prototype.isArgumentListOfFunction = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentOfFunction = function () { - return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; - }; - AstPath.prototype.isArgumentListOfCall = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isArgumentListOfNew = function () { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; - }; - AstPath.prototype.isSynthesizedBlock = function () { - return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; - }; - return AstPath; - })(); - TypeScript.AstPath = AstPath; - function isValidAstNode(ast) { - if(ast === null) { - return false; - } - if(ast.minChar === -1 || ast.limChar === -1) { - return false; - } - return true; - } - TypeScript.isValidAstNode = isValidAstNode; - var AstPathContext = (function () { - function AstPathContext() { - this.path = new TypeScript.AstPath(); - } - return AstPathContext; - })(); - TypeScript.AstPathContext = AstPathContext; - (function (GetAstPathOptions) { - GetAstPathOptions._map = []; - GetAstPathOptions.Default = 0; - GetAstPathOptions.EdgeInclusive = 1; - GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; - })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); - var GetAstPathOptions = TypeScript.GetAstPathOptions; - function getAstPathToPosition(script, pos, options) { - if (typeof options === "undefined") { options = GetAstPathOptions.Default; } - var lookInComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - var minChar = comments[i].minChar; - var limChar = comments[i].limChar; - if(!comments[i].isBlockComment) { - limChar++; - } - if(pos >= minChar && pos < limChar) { - ctx.path.push(comments[i]); - } - } - } - }; - var pre = function (cur, parent, walker) { - if(isValidAstNode(cur)) { - var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; - var minChar = cur.minChar; - var limChar = cur.limChar + (inclusive ? 1 : 0); - if(pos >= minChar && pos < limChar) { - var previous = ctx.path.ast(); - if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { - ctx.path.push(cur); - } else { - } - } - if(pos < limChar) { - lookInComments(cur.preComments); - } - if(pos >= minChar) { - lookInComments(cur.postComments); - } - if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { - walker.options.goChildren = (minChar <= pos && pos <= limChar); - } - } - return cur; - }; - var ctx = new AstPathContext(); - TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); - return ctx.path; - } - TypeScript.getAstPathToPosition = getAstPathToPosition; - function getTokenizationOffset(script, position) { - var bestOffset = 0; - var pre = function (cur, parent, walker) { - if(TypeScript.isValidAstNode(cur)) { - if(cur.minChar <= position) { - bestOffset = max(bestOffset, cur.minChar); - } - if(cur.minChar > position || cur.limChar < bestOffset) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return bestOffset; - } - TypeScript.getTokenizationOffset = getTokenizationOffset; - function walkAST(ast, callback) { - var pre = function (cur, parent, walker) { - var path = walker.state; - path.push(cur); - callback(path, walker); - return cur; - }; - var post = function (cur, parent, walker) { - var path = walker.state; - path.pop(); - return cur; - }; - var path = new AstPath(); - TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); - } - TypeScript.walkAST = walkAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AstLogger = (function () { - function AstLogger(logger) { - this.logger = logger; - } - AstLogger.prototype.logScript = function (script) { - var _this = this; - this.logLinemap(script.locationInfo.lineMap); - var stack = []; - var pre = function (cur, parent) { - stack.push(cur); - var indent = (stack.length - 1) * 2; - _this.logComments(script, cur.preComments, indent); - _this.logNode(script, cur, indent); - _this.logComments(script, cur.postComments, indent); - return cur; - }; - var post = function (cur, parent) { - stack.pop(); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre, post); - }; - AstLogger.prototype.logNode = function (script, cur, indent) { - var msg = this.addPadding("", indent, "| ", true); - msg = msg.concat("+ " + cur.treeViewLabel()); - msg = this.addPadding(msg, 70, " ", false); - msg = msg + this.addLineColumn(script, cur.minChar); - msg = this.addPadding(msg, 80, " ", false); - msg = msg + "=> "; - msg = msg + this.addLineColumn(script, cur.limChar); - msg = this.addPadding(msg, 102, " ", false); - msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); - msg = this.addPadding(msg, 115, " ", false); - msg = msg.concat("sym=" + (cur).sym); - msg = this.addPadding(msg, 135, " ", false); - msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); - this.logger.log(msg); - }; - AstLogger.prototype.logComments = function (script, comments, indent) { - if(comments == null) { - return; - } - for(var i = 0; i < comments.length; i++) { - this.logNode(script, comments[i], indent); - } - }; - AstLogger.prototype.logLinemap = function (linemap) { - var result = "["; - for(var i = 0; i < linemap.length; i++) { - if(i > 0) { - result += ","; - } - result += linemap[i]; - } - result += "]"; - this.logger.log("linemap: " + result); - }; - AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { - var result = (leftPadding ? "" : s); - for(var i = s.length; i < targetLength; i++) { - result = result + paddingString; - } - result = result + (leftPadding ? s : ""); - return result; - }; - AstLogger.prototype.addLineColumn = function (script, position) { - var lineInfo = { - line: -1, - col: -1 - }; - TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); - if(lineInfo.col !== -1) { - lineInfo.col++; - } - return "(" + lineInfo.line + ", " + lineInfo.col + ")"; - }; - return AstLogger; - })(); - TypeScript.AstLogger = AstLogger; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Binder = (function () { - function Binder(checker) { - this.checker = checker; - } - Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { - var extendsList = null; - if(typeLinks) { - extendsList = new Array(); - for(var i = 0, len = typeLinks.length; i < len; i++) { - extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); - } - } - return extendsList; - }; - Binder.prototype.resolveBases = function (scope, type) { - type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); - var i = 0, len = type.extendsList.length; - var derivedIsClass = type.isClassInstance(); - for(; i < len; i++) { - var baseIsClass = type.extendsList[i].isClassInstance(); - if(type.extendsList[i] != this.checker.anyType) { - var baseRef = type.extendsTypeLinks[i].ast; - if(derivedIsClass) { - if(!baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); - } - } else { - if(baseIsClass) { - this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); - } - } - } - } - type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); - if(type.implementsList) { - for(i = 0 , len = type.implementsList.length; i < len; i++) { - var iface = type.implementsList[i]; - var baseRef = type.implementsTypeLinks[i].ast; - if(iface.isClassInstance()) { - if(derivedIsClass) { - this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); - } - } - } - } - }; - Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { - var supplyVar = !(signatureGroup.hasImplementation); - for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { - var signature = signatureGroup.signatures[i]; - if(instanceType) { - signature.returnType.type = instanceType; - } else { - this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - this.bindSymbol(scope, signature.parameters[j]); - } - if(signature.hasVariableArgList) { - var lastParam = signature.parameters[paramLen - 1]; - lastParam.argsOffset = paramLen - 1; - if(!lastParam.getType().isArray()) { - this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); - lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); - } - } - } - }; - Binder.prototype.bindType = function (scope, type, instanceType) { - if(instanceType) { - this.bindType(scope, instanceType, null); - } - var callAndConstructScope = scope; - if(type.hasMembers()) { - var members = type.members; - var ambientMembers = type.ambientMembers; - var typeMembers = type.getAllEnclosedTypes(); - var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); - var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); - var agg = new TypeScript.SymbolAggregateScope(type.symbol); - var prevCurrentModDecl = this.checker.currentModDecl; - var prevBindStatus = this.checker.inBind; - agg.addParentScope(memberScope); - agg.addParentScope(scope); - if(type.isModuleType()) { - this.checker.currentModDecl = type.symbol.declAST; - this.checker.inBind = true; - } - if(members) { - this.bind(agg, type.members.allMembers); - } - if(typeMembers) { - this.bind(agg, typeMembers.allMembers); - } - if(ambientMembers) { - this.bind(agg, ambientMembers.allMembers); - } - if(ambientTypeMembers) { - this.bind(agg, ambientTypeMembers.allMembers); - } - if(type.isModuleType()) { - callAndConstructScope = agg; - } - this.checker.currentModDecl = prevCurrentModDecl; - this.checker.inBind = prevBindStatus; - } - if(type.extendsTypeLinks) { - this.resolveBases(scope, type); - } - if(type.construct) { - this.resolveSignatureGroup(type.construct, callAndConstructScope, instanceType); - } - if(type.call) { - this.resolveSignatureGroup(type.call, callAndConstructScope, null); - } - if(type.index) { - this.resolveSignatureGroup(type.index, scope, null); - } - if(type.elementType) { - this.bindType(scope, type.elementType, null); - } - }; - Binder.prototype.bindSymbol = function (scope, symbol) { - if(!symbol.bound) { - var prevLocationInfo = this.checker.locationInfo; - if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[symbol.unitIndex]; - } - switch(symbol.kind()) { - case TypeScript.SymbolKind.Type: - if(symbol.flags & TypeScript.SymbolFlags.Bound) { - break; - } - var typeSymbol = symbol; - typeSymbol.flags |= TypeScript.SymbolFlags.Bound; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { - this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); - if(typeSymbol.type.isModuleType()) { - for(var i = 0; i < typeSymbol.expansions.length; i++) { - this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); - } - } - } - break; - case TypeScript.SymbolKind.Field: - this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); - break; - case TypeScript.SymbolKind.Parameter: - this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); - break; - } - this.checker.locationInfo = prevLocationInfo; - } - symbol.bound = true; - }; - Binder.prototype.bind = function (scope, table) { - table.map(function (key, sym, binder) { - binder.bindSymbol(scope, sym); - }, this); - }; - return Binder; - })(); - TypeScript.Binder = Binder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Base64Format = (function () { - function Base64Format() { } - Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - Base64Format.encode = function encode(inValue) { - if(inValue < 64) { - return Base64Format.encodedValues.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - }; - Base64Format.decodeChar = function decodeChar(inChar) { - if(inChar.length === 1) { - return Base64Format.encodedValues.indexOf(inChar); - } else { - throw TypeError('"' + inChar + '" must have length 1'); - } - }; - return Base64Format; - })(); - var Base64VLQFormat = (function () { - function Base64VLQFormat() { } - Base64VLQFormat.encode = function encode(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 + Base64Format.encode(currentDigit); - }while(inValue > 0); - return encodedStr; - }; - Base64VLQFormat.decode = function decode(inString) { - var result = 0; - var negative = false; - var shift = 0; - for(var i = 0; i < inString.length; i++) { - var byte = Base64Format.decodeChar(inString[i]); - if(i === 0) { - if((byte & 1) === 1) { - negative = true; - } - result = (byte >> 1) & 15; - } else { - result = result | ((byte & 31) << shift); - } - shift += (i == 0) ? 4 : 5; - if((byte & 32) === 32) { - } else { - return { - value: negative ? -(result) : result, - rest: inString.substr(i + 1) - }; - } - } - throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); - }; - return Base64VLQFormat; - })(); - TypeScript.Base64VLQFormat = Base64VLQFormat; -})(TypeScript || (TypeScript = {})); -var JSON2 = { -}; -((function () { - 'use strict'; - function f(n) { - return n < 10 ? '0' + n : n; - } - if(typeof Date.prototype.toJSON !== 'function') { - Date.prototype.toJSON = function (key) { - return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; - }; - var strProto = String.prototype; - var numProto = Number.prototype; - numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"': '\\"', - '\\': '\\\\' - }, rep; - function quote(string) { - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - function str(key, holder) { - var i, k = null, v, length, mind = gap, partial, value = holder[key]; - if(value && typeof value === 'object' && typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - if(typeof rep === 'function') { - value = rep.call(holder, key, value); - } - switch(typeof value) { - case 'string': - return quote(value); - case 'number': - return isFinite(value) ? String(value) : 'null'; - case 'boolean': - case 'null': - return String(value); - case 'object': - if(!value) { - return 'null'; - } - gap += indent; - partial = []; - if(Object.prototype.toString.apply(value, []) === '[object Array]') { - length = value.length; - for(i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - if(rep && typeof rep === 'object') { - length = rep.length; - for(i = 0; i < length; i += 1) { - if(typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - for(k in value) { - if(Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if(v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - if(typeof JSON2.stringify !== 'function') { - JSON2.stringify = function (value, replacer, space) { - var i; - gap = ''; - indent = ''; - if(typeof space === 'number') { - for(i = 0; i < space; i += 1) { - indent += ' '; - } - } else if(typeof space === 'string') { - indent = space; - } - rep = replacer; - if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - return str('', { - '': value - }); - }; - } -})()); -var TypeScript; -(function (TypeScript) { - var SourceMapPosition = (function () { - function SourceMapPosition() { } - return SourceMapPosition; - })(); - TypeScript.SourceMapPosition = SourceMapPosition; - var SourceMapping = (function () { - function SourceMapping() { - this.start = new SourceMapPosition(); - this.end = new SourceMapPosition(); - this.nameIndex = -1; - this.childMappings = []; - } - return SourceMapping; - })(); - TypeScript.SourceMapping = SourceMapping; - var SourceMapper = (function () { - function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter, emitFullPathOfSourceMap) { - this.jsFile = jsFile; - this.sourceMapOut = sourceMapOut; - this.errorReporter = errorReporter; - this.sourceMappings = []; - this.currentMappings = []; - this.names = []; - this.currentNameIndex = []; - this.currentMappings.push(this.sourceMappings); - jsFileName = TypeScript.switchToForwardSlashes(jsFileName); - this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); - var removalIndex = jsFileName.lastIndexOf(this.jsFileName); - var fixedPath = jsFileName.substring(0, removalIndex); - if(emitFullPathOfSourceMap) { - if(jsFileName.indexOf("://") == -1) { - jsFileName = "file:///" + jsFileName; - } - this.jsFileName = jsFileName; - } - this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); - } - SourceMapper.MapFileExtension = ".map"; - SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { - var sourceMapper = allSourceMappers[0]; - sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); - var sourceMapOut = sourceMapper.sourceMapOut; - var mappingsString = ""; - var tsFiles = []; - var prevEmittedColumn = 0; - var prevEmittedLine = 0; - var prevSourceColumn = 0; - var prevSourceLine = 0; - var prevSourceIndex = 0; - var prevNameIndex = 0; - var namesList = []; - var namesCount = 0; - var emitComma = false; - var recordedPosition = null; - for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { - sourceMapper = allSourceMappers[sourceMapperIndex]; - var currentSourceIndex = tsFiles.length; - tsFiles.push(sourceMapper.tsFileName); - if(sourceMapper.names.length > 0) { - namesList.push.apply(namesList, sourceMapper.names); - } - var recordSourceMapping = function (mappedPosition, nameIndex) { - if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { - return; - } - if(prevEmittedLine !== mappedPosition.emittedLine) { - while(prevEmittedLine < mappedPosition.emittedLine) { - prevEmittedColumn = 0; - mappingsString = mappingsString + ";"; - prevEmittedLine++; - } - emitComma = false; - } else if(emitComma) { - mappingsString = mappingsString + ","; - } - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); - prevEmittedColumn = mappedPosition.emittedColumn; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); - prevSourceIndex = currentSourceIndex; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); - prevSourceLine = mappedPosition.sourceLine - 1; - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); - prevSourceColumn = mappedPosition.sourceColumn; - if(nameIndex >= 0) { - mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); - prevNameIndex = namesCount + nameIndex; - } - emitComma = true; - recordedPosition = mappedPosition; - }; - var recordSourceMappingSiblings = function (sourceMappings) { - for(var i = 0; i < sourceMappings.length; i++) { - var sourceMapping = sourceMappings[i]; - recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); - recordSourceMappingSiblings(sourceMapping.childMappings); - recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); - } - }; - recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); - namesCount = namesCount + sourceMapper.names.length; - } - sourceMapOut.Write(JSON2.stringify({ - version: 3, - file: sourceMapper.jsFileName, - sources: tsFiles, - names: namesList, - mappings: mappingsString - })); - try { - sourceMapOut.Close(); - } catch (ex) { - sourceMapper.errorReporter.emitterError(null, ex.message); - } - }; - return SourceMapper; - })(); - TypeScript.SourceMapper = SourceMapper; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (EmitContainer) { - EmitContainer._map = []; - EmitContainer._map[0] = "Prog"; - EmitContainer.Prog = 0; - EmitContainer._map[1] = "Module"; - EmitContainer.Module = 1; - EmitContainer._map[2] = "DynamicModule"; - EmitContainer.DynamicModule = 2; - EmitContainer._map[3] = "Class"; - EmitContainer.Class = 3; - EmitContainer._map[4] = "Constructor"; - EmitContainer.Constructor = 4; - EmitContainer._map[5] = "Function"; - EmitContainer.Function = 5; - EmitContainer._map[6] = "Args"; - EmitContainer.Args = 6; - EmitContainer._map[7] = "Interface"; - EmitContainer.Interface = 7; - })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); - var EmitContainer = TypeScript.EmitContainer; - var EmitState = (function () { - function EmitState() { - this.column = 0; - this.line = 0; - this.pretty = false; - this.inObjectLiteral = false; - this.container = EmitContainer.Prog; - } - return EmitState; - })(); - TypeScript.EmitState = EmitState; - var EmitOptions = (function () { - function EmitOptions(settings) { - this.ioHost = null; - this.outputMany = true; - this.commonDirectoryPath = ""; - this.minWhitespace = settings.minWhitespace; - this.propagateConstants = settings.propagateConstants; - this.emitComments = settings.emitComments; - this.outputOption = settings.outputOption; - this.emitFullSourceMapPath = settings.emitFullSourceMapPath; - } - EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { - if(this.outputMany) { - var updatedFileName = fileName; - if(this.outputOption != "") { - updatedFileName = fileName.replace(this.commonDirectoryPath, ""); - updatedFileName = this.outputOption + updatedFileName; - } - return extensionChanger(updatedFileName, false); - } else { - return extensionChanger(this.outputOption, true); - } - }; - return EmitOptions; - })(); - TypeScript.EmitOptions = EmitOptions; - var Indenter = (function () { - function Indenter() { - this.indentAmt = 0; - } - Indenter.indentStep = 4; - Indenter.indentStepString = " "; - Indenter.indentStrings = []; - Indenter.prototype.increaseIndent = function () { - this.indentAmt += Indenter.indentStep; - }; - Indenter.prototype.decreaseIndent = function () { - this.indentAmt -= Indenter.indentStep; - }; - Indenter.prototype.getIndent = function () { - var indentString = Indenter.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { - indentString += Indenter.indentStepString; - } - Indenter.indentStrings[this.indentAmt] = indentString; - } - return indentString; - }; - return Indenter; - })(); - TypeScript.Indenter = Indenter; - var Emitter = (function () { - function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { - this.checker = checker; - this.emittingFileName = emittingFileName; - this.outfile = outfile; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.globalThisCapturePrologueEmitted = false; - this.extendsPrologueEmitted = false; - this.thisClassNode = null; - this.thisFnc = null; - this.moduleDeclList = []; - this.moduleName = ""; - this.emitState = new EmitState(); - this.indenter = new Indenter(); - this.ambientModule = false; - this.modAliasId = null; - this.firstModAlias = null; - this.allSourceMappers = []; - this.sourceMapper = null; - this.captureThisStmtString = "var _this = this;"; - this.varListCountStack = [ - 0 - ]; - } - Emitter.prototype.setSourceMappings = function (mapper) { - this.allSourceMappers.push(mapper); - this.sourceMapper = mapper; - }; - Emitter.prototype.writeToOutput = function (s) { - this.outfile.Write(s); - this.emitState.column += s.length; - }; - Emitter.prototype.writeToOutputTrimmable = function (s) { - if(this.emitOptions.minWhitespace) { - s = s.replace(/[\s]*/g, ''); - } - this.writeToOutput(s); - }; - Emitter.prototype.writeLineToOutput = function (s) { - if(this.emitOptions.minWhitespace) { - this.writeToOutput(s); - var c = s.charCodeAt(s.length - 1); - if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { - this.writeToOutput(' '); - } - } else { - this.outfile.WriteLine(s); - this.emitState.column = 0; - this.emitState.line++; - } - }; - Emitter.prototype.writeCaptureThisStatement = function (ast) { - this.emitIndent(); - this.recordSourceMappingStart(ast); - this.writeToOutput(this.captureThisStmtString); - this.recordSourceMappingEnd(ast); - this.writeLineToOutput(""); - }; - Emitter.prototype.setInVarBlock = function (count) { - this.varListCountStack[this.varListCountStack.length - 1] = count; - }; - Emitter.prototype.setInObjectLiteral = function (val) { - var temp = this.emitState.inObjectLiteral; - this.emitState.inObjectLiteral = val; - return temp; - }; - Emitter.prototype.setContainer = function (c) { - var temp = this.emitState.container; - this.emitState.container = c; - return temp; - }; - Emitter.prototype.getIndentString = function () { - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - Emitter.prototype.emitIndent = function () { - this.writeToOutput(this.getIndentString()); - }; - Emitter.prototype.emitCommentInPlace = function (comment) { - var text = comment.getText(); - var hadNewLine = false; - if(comment.isBlockComment) { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.recordSourceMappingStart(comment); - this.writeToOutput(text[0]); - if(text.length > 1 || comment.endsLine) { - for(var i = 1; i < text.length; i++) { - this.writeLineToOutput(""); - this.emitIndent(); - this.writeToOutput(text[i]); - } - this.recordSourceMappingEnd(comment); - this.writeLineToOutput(""); - hadNewLine = true; - } else { - this.recordSourceMappingEnd(comment); - } - } else { - if(this.emitState.column == 0) { - this.emitIndent(); - } - this.recordSourceMappingStart(comment); - this.writeToOutput(text[0]); - this.recordSourceMappingEnd(comment); - this.writeLineToOutput(""); - hadNewLine = true; - } - if(hadNewLine) { - this.emitIndent(); - } else { - this.writeToOutput(" "); - } - }; - Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { - var comments = pre ? ast.preComments : ast.postComments; - if(ast.isParenthesized && !pre) { - this.writeToOutput(")"); - } - if(this.emitOptions.emitComments && comments && comments.length != 0) { - for(var i = 0; i < comments.length; i++) { - this.emitCommentInPlace(comments[i]); - } - } - if(ast.isParenthesized && pre) { - this.writeToOutput("("); - } - }; - Emitter.prototype.emitObjectLiteral = function (content) { - this.writeLineToOutput("{"); - this.indenter.increaseIndent(); - var inObjectLiteral = this.setInObjectLiteral(true); - this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); - this.setInObjectLiteral(inObjectLiteral); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - }; - Emitter.prototype.emitArrayLiteral = function (content) { - this.writeToOutput("["); - if(content) { - this.writeLineToOutput(""); - this.indenter.increaseIndent(); - this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); - this.indenter.decreaseIndent(); - this.emitIndent(); - } - this.writeToOutput("]"); - }; - Emitter.prototype.emitNew = function (target, args) { - this.writeToOutput("new "); - if(target.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = target; - if(typeRef.arrayCount) { - this.writeToOutput("Array()"); - } else { - this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); - this.writeToOutput("()"); - } - } else { - this.emitJavascript(target, TypeScript.TokenID.Tilde, false); - this.recordSourceMappingStart(args); - this.writeToOutput("("); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } - }; - Emitter.prototype.getConstantValue = function (init) { - if(init) { - if(init.nodeType === TypeScript.NodeType.NumberLit) { - var numLit = init; - return numLit.value; - } else if(init.nodeType === TypeScript.NodeType.Lsh) { - var binop = init; - if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { - return (binop.operand1).value << (binop.operand2).value; - } - } else if(init.nodeType === TypeScript.NodeType.Name) { - var ident = init; - if(ident.sym !== null && ident.sym.declAST.nodeType === TypeScript.NodeType.VarDecl) { - var varDecl = ident.sym.declAST; - return this.getConstantValue(varDecl.init); - } - } - } - return null; - }; - Emitter.prototype.tryEmitConstant = function (dotExpr) { - if(!this.emitOptions.propagateConstants) { - return false; - } - var propertyName = dotExpr.operand2; - if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { - if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { - if(propertyName.sym.declAST) { - var boundDecl = propertyName.sym.declAST; - var value = this.getConstantValue(boundDecl.init); - if(value !== null) { - this.writeToOutput(value.toString()); - var comment = " /* "; - comment += propertyName.actualText; - comment += " */ "; - this.writeToOutput(comment); - return true; - } - } - } - } - return false; - }; - Emitter.prototype.emitCall = function (callNode, target, args) { - if(!this.emitSuperCall(callNode)) { - if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput("("); - } - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("_super.call"); - } else { - this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); - } - if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { - this.writeToOutput(")"); - } - this.recordSourceMappingStart(args); - this.writeToOutput("("); - if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { - this.writeToOutput("this"); - if(args && args.members.length) { - this.writeToOutput(", "); - } - } - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput(")"); - this.recordSourceMappingEnd(args); - } else { - this.indenter.decreaseIndent(); - this.indenter.decreaseIndent(); - var constructorCall = new TypeScript.ASTList(); - constructorCall.members[0] = callNode; - this.emitConstructorCalls(constructorCall, this.thisClassNode); - this.indenter.increaseIndent(); - this.indenter.increaseIndent(); - } - } - }; - Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - this.recordSourceMappingStart(classDecl); - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - baseSymbol = (baseExpr).target.type.symbol; - } else { - baseSymbol = baseExpr.type.symbol; - } - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.emitIndent(); - this.writeToOutput("_super.call(this"); - var args = (baseExpr).arguments; - if(args && (args.members.length > 0)) { - this.writeToOutput(", "); - this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - } else { - if(baseExpr.type && (baseExpr.type.isClassInstance())) { - this.emitIndent(); - this.writeToOutput(classDecl.name.actualText + "._super.constructor"); - this.writeToOutput(".call(this)"); - } - } - } - this.recordSourceMappingEnd(classDecl); - }; - Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { - var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); - var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); - this.emitParensAndCommentsInPlace(funcDecl, true); - if(shouldParenthesize) { - this.writeToOutput("("); - } - this.recordSourceMappingStart(funcDecl); - if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { - this.writeToOutput("function "); - } - if(printName) { - var id = funcDecl.getNameText(); - if(id && !funcDecl.isAccessor()) { - if(funcDecl.name) { - this.recordSourceMappingStart(funcDecl.name); - } - this.writeToOutput(id); - if(funcDecl.name) { - this.recordSourceMappingEnd(funcDecl.name); - } - } - } - this.writeToOutput("("); - var argsLen = 0; - var i = 0; - var arg; - var defaultArgs = []; - if(funcDecl.arguments) { - var tempContainer = this.setContainer(EmitContainer.Args); - argsLen = funcDecl.arguments.members.length; - var printLen = argsLen; - if(funcDecl.variableArgList) { - printLen--; - } - for(i = 0; i < printLen; i++) { - arg = funcDecl.arguments.members[i]; - if(arg.init) { - defaultArgs.push(arg); - } - this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); - if(i < (printLen - 1)) { - this.writeToOutput(", "); - } - } - this.setContainer(tempContainer); - } - this.writeLineToOutput(") {"); - if(funcDecl.isConstructor) { - this.recordSourceMappingNameStart("constructor"); - } else if(funcDecl.isGetAccessor()) { - this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); - } else if(funcDecl.isSetAccessor()) { - this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); - } else { - this.recordSourceMappingNameStart(funcDecl.getNameText()); - } - this.indenter.increaseIndent(); - for(i = 0; i < defaultArgs.length; i++) { - var arg = defaultArgs[i]; - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); - this.writeLineToOutput("; }"); - this.recordSourceMappingEnd(arg); - } - if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { - if(funcDecl.arguments) { - argsLen = funcDecl.arguments.members.length; - for(i = 0; i < argsLen; i++) { - arg = funcDecl.arguments.members[i]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - this.emitConstructorCalls(bases, classDecl); - } - } - if(hasSelfRef) { - this.writeCaptureThisStatement(funcDecl); - } - if(funcDecl.variableArgList) { - argsLen = funcDecl.arguments.members.length; - var lastArg = funcDecl.arguments.members[argsLen - 1]; - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var "); - this.recordSourceMappingStart(lastArg.id); - this.writeToOutput(lastArg.id.actualText); - this.recordSourceMappingEnd(lastArg.id); - this.writeLineToOutput(" = [];"); - this.recordSourceMappingEnd(lastArg); - this.emitIndent(); - this.writeToOutput("for ("); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("var _i = 0;"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput(" "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); - this.recordSourceMappingEnd(lastArg); - this.writeToOutput("; "); - this.recordSourceMappingStart(lastArg); - this.writeToOutput("_i++"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(") {"); - this.indenter.increaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(lastArg); - this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); - this.recordSourceMappingEnd(lastArg); - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { - var nProps = (this.thisClassNode.members).members.length; - for(var i = 0; i < nProps; i++) { - if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(funcDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(funcDecl.endingToken); - this.recordSourceMappingEnd(funcDecl); - if(shouldParenthesize) { - this.writeToOutput(")"); - } - this.recordSourceMappingEnd(funcDecl); - this.emitParensAndCommentsInPlace(funcDecl, false); - if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isConstructor)) { - this.writeLineToOutput(""); - } else if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { - if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { - this.writeLineToOutput(";"); - } - } - }; - Emitter.prototype.emitJavascriptModule = function (moduleDecl) { - var modName = moduleDecl.name.actualText; - if(TypeScript.isTSFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 3)); - } else if(TypeScript.isSTRFile(modName)) { - moduleDecl.name.setText(modName.substring(0, modName.length - 4)); - } - if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { - var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); - var prevOutFile = this.outfile; - var prevOutFileName = this.emittingFileName; - var prevAllSourceMappers = this.allSourceMappers; - var prevSourceMapper = this.sourceMapper; - var prevColumn = this.emitState.column; - var prevLine = this.emitState.line; - var temp = this.setContainer(EmitContainer.Module); - var svModuleName = this.moduleName; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; - var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); - this.moduleName = moduleDecl.name.actualText; - if(isDynamicMod) { - var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); - var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; - modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); - if(this.emitOptions.ioHost) { - if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { - this.emittingFileName = modFilePath; - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); - if(prevSourceMapper != null) { - this.allSourceMappers = []; - var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); - this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter, this.emitOptions.emitFullSourceMapPath)); - this.emitState.column = 0; - this.emitState.line = 0; - } - } else { - TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); - } - } - this.setContainer(EmitContainer.DynamicModule); - this.recordSourceMappingStart(moduleDecl); - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - var dependencyList = "[\"require\", \"exports\""; - var importList = "require, exports"; - var importStatement = null; - for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { - importStatement = (moduleDecl.mod).importedModules[i]; - if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { - if(i <= (moduleDecl.mod).importedModules.length - 1) { - dependencyList += ", "; - importList += ", "; - } - importList += "__" + importStatement.id.actualText + "__"; - dependencyList += importStatement.firstAliasedModToString(); - } - } - for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { - dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; - } - dependencyList += "]"; - this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); - } else { - } - } else { - if(!isExported) { - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("var "); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(moduleDecl); - this.emitIndent(); - } - this.writeToOutput("("); - this.recordSourceMappingStart(moduleDecl); - this.writeToOutput("function ("); - this.recordSourceMappingStart(moduleDecl.name); - this.writeToOutput(this.moduleName); - this.recordSourceMappingEnd(moduleDecl.name); - this.writeLineToOutput(") {"); - } - if(!isWholeFile) { - this.recordSourceMappingNameStart(this.moduleName); - } - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.increaseIndent(); - } - if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { - this.writeCaptureThisStatement(moduleDecl); - } - this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.indenter.decreaseIndent(); - } - this.emitIndent(); - if(isDynamicMod) { - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("})"); - } else { - } - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl); - if(this.outfile != prevOutFile) { - this.Close(); - if(prevSourceMapper != null) { - this.allSourceMappers = prevAllSourceMappers; - this.sourceMapper = prevSourceMapper; - this.emitState.column = prevColumn; - this.emitState.line = prevLine; - } - this.outfile = prevOutFile; - this.emittingFileName = prevOutFileName; - } - } else { - var containingMod = null; - if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { - containingMod = moduleDecl.type.symbol.container.declAST; - } - var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); - this.recordSourceMappingStart(moduleDecl.endingToken); - if(temp == EmitContainer.Prog && isExported) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); - } else if(isExported || temp == EmitContainer.Prog) { - var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); - } else if(!isExported && temp != EmitContainer.Prog) { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); - } else { - this.writeToOutput("}"); - if(!isWholeFile) { - this.recordSourceMappingNameEnd(); - } - this.recordSourceMappingEnd(moduleDecl.endingToken); - this.writeToOutput(")();"); - } - this.recordSourceMappingEnd(moduleDecl); - this.writeLineToOutput(""); - if(temp != EmitContainer.Prog && isExported) { - this.emitIndent(); - this.recordSourceMappingStart(moduleDecl); - if(parentIsDynamic) { - this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); - } else { - this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); - } - this.recordSourceMappingEnd(moduleDecl); - } - } - this.setContainer(temp); - this.moduleName = svModuleName; - this.moduleDeclList.length--; - } - }; - Emitter.prototype.emitIndex = function (operand1, operand2) { - var temp = this.setInObjectLiteral(false); - this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); - this.writeToOutput("["); - this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); - this.writeToOutput("]"); - this.setInObjectLiteral(temp); - }; - Emitter.prototype.emitStringLiteral = function (text) { - this.writeToOutput(text); - }; - Emitter.prototype.emitJavascriptFunction = function (funcDecl) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { - return; - } - var temp; - var tempFnc = this.thisFnc; - this.thisFnc = funcDecl; - if(funcDecl.isConstructor) { - temp = this.setContainer(EmitContainer.Constructor); - } else { - temp = this.setContainer(EmitContainer.Function); - } - var bases = null; - var hasSelfRef = false; - var funcName = funcDecl.getNameText(); - if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { - var tempLit = this.setInObjectLiteral(false); - if(this.thisClassNode) { - bases = this.thisClassNode.extendsList; - } - hasSelfRef = Emitter.shouldCaptureThis(funcDecl); - this.recordSourceMappingStart(funcDecl); - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { - this.writeToOutput("this." + funcName + " = "); - this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); - } else { - this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); - } - this.setInObjectLiteral(tempLit); - } - this.setContainer(temp); - this.thisFnc = tempFnc; - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { - if(this.thisClassNode) { - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - } else if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { - this.emitIndent(); - var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); - this.recordSourceMappingEnd(funcDecl); - } - } - }; - Emitter.prototype.emitAmbientVarDecl = function (varDecl) { - if(varDecl.init) { - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.recordSourceMappingEnd(varDecl); - this.writeToOutput(";"); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.varListCount = function () { - return this.varListCountStack[this.varListCountStack.length - 1]; - }; - Emitter.prototype.emitVarDeclVar = function () { - if(this.varListCount() >= 0) { - this.writeToOutput("var "); - this.setInVarBlock(-this.varListCount()); - } - return true; - }; - Emitter.prototype.onEmitVar = function () { - if(this.varListCount() > 0) { - this.setInVarBlock(this.varListCount() - 1); - } else if(this.varListCount() < 0) { - this.setInVarBlock(this.varListCount() + 1); - } - }; - Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { - if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { - this.emitAmbientVarDecl(varDecl); - this.onEmitVar(); - } else { - var sym = varDecl.sym; - var hasInitializer = (varDecl.init != null); - this.emitParensAndCommentsInPlace(varDecl, true); - this.recordSourceMappingStart(varDecl); - if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { - var type = (sym.container).type; - if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { - if(this.emitState.container != EmitContainer.Args) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { - this.writeToOutput(sym.container.name + "."); - } else { - this.writeToOutput("this."); - } - } - } else if(type.hasImplementation()) { - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - this.emitVarDeclVar(); - } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { - this.writeToOutput("."); - } else { - if(this.emitState.container == EmitContainer.DynamicModule) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(this.moduleName + "."); - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { - this.writeToOutput("this."); - } else { - this.emitVarDeclVar(); - } - } - } - } else { - if(tokenId != TypeScript.TokenID.OpenParen) { - this.emitVarDeclVar(); - } - } - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - if(hasInitializer) { - this.writeToOutputTrimmable(" = "); - this.varListCountStack.push(0); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); - this.varListCountStack.pop(); - } - this.onEmitVar(); - if((tokenId != TypeScript.TokenID.OpenParen)) { - if(this.varListCount() < 0) { - this.writeToOutput(", "); - } else if(tokenId != TypeScript.TokenID.For) { - this.writeToOutputTrimmable(";"); - } - } - this.recordSourceMappingEnd(varDecl); - this.emitParensAndCommentsInPlace(varDecl, false); - } - }; - Emitter.prototype.declEnclosed = function (moduleDecl) { - if(moduleDecl == null) { - return true; - } - for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { - if(this.moduleDeclList[i] == moduleDecl) { - return true; - } - } - return false; - }; - Emitter.prototype.emitJavascriptName = function (name, addThis) { - var sym = name.sym; - this.emitParensAndCommentsInPlace(name, true); - this.recordSourceMappingStart(name); - if(!name.isMissing()) { - if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { - if(sym.container && (sym.container.name != TypeScript.globalId)) { - if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { - if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } else if(sym.kind() == TypeScript.SymbolKind.Field) { - var fieldSym = sym; - if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { - if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { - if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - this.writeToOutput("exports."); - } else { - this.writeToOutput(sym.container.name + "."); - } - } - } else { - if(sym.isInstanceProperty()) { - this.emitThis(); - this.writeToOutput("."); - } - } - } else if(sym.kind() == TypeScript.SymbolKind.Type) { - if(sym.isInstanceProperty()) { - var typeSym = sym; - var type = typeSym.type; - if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { - this.emitThis(); - this.writeToOutput("."); - } - } else if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { - this.writeToOutput(sym.container.name + "."); - } - } - } else if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { - this.writeToOutput("this."); - } - } - if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { - var moduleDecl = sym.declAST; - if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { - this.writeLineToOutput("__" + this.modAliasId + "__;"); - } else { - var modPath = name.actualText; - var isSingleQuotedMod = TypeScript.isSingleQuoted(modPath); - var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); - modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); - modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); - if(isSingleQuotedMod) { - modPath = TypeScript.changeToSingleQuote(modPath); - } - this.writeToOutput("require(" + modPath + ")"); - } - } else { - this.writeToOutput(name.actualText); - } - } - this.recordSourceMappingEnd(name); - this.emitParensAndCommentsInPlace(name, false); - }; - Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { - if(stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); - if(emitEmptyBod || hasContents) { - var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); - this.recordSourceMappingStart(stmts); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(" {"); - this.indenter.increaseIndent(); - } - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); - if(!hasOnlyBlockStatement) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeToOutput("}"); - } - this.recordSourceMappingEnd(stmts); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else if(emitEmptyBod) { - this.writeToOutput("{ }"); - } - }; - Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if(stmts.nodeType != TypeScript.NodeType.Block) { - if(stmts.nodeType == TypeScript.NodeType.List) { - var stmtList = stmts; - if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { - this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); - this.writeLineToOutput(""); - } else { - this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - } else { - this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); - } - }; - Emitter.prototype.recordSourceMappingNameStart = function (name) { - if(this.sourceMapper) { - var finalName = name; - if(!name) { - finalName = ""; - } else if(this.sourceMapper.currentNameIndex.length > 0) { - finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]] + "." + name; - } - this.sourceMapper.names.push(finalName); - this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); - } - }; - Emitter.prototype.recordSourceMappingNameEnd = function () { - if(this.sourceMapper) { - this.sourceMapper.currentNameIndex.pop(); - } - }; - Emitter.prototype.recordSourceMappingStart = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - var lineCol = { - line: -1, - col: -1 - }; - var sourceMapping = new TypeScript.SourceMapping(); - sourceMapping.start.emittedColumn = this.emitState.column; - sourceMapping.start.emittedLine = this.emitState.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); - sourceMapping.start.sourceColumn = lineCol.col; - sourceMapping.start.sourceLine = lineCol.line; - TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); - sourceMapping.end.sourceColumn = lineCol.col; - sourceMapping.end.sourceLine = lineCol.line; - if(this.sourceMapper.currentNameIndex.length > 0) { - sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; - } - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - siblings.push(sourceMapping); - this.sourceMapper.currentMappings.push(sourceMapping.childMappings); - } - }; - Emitter.prototype.recordSourceMappingEnd = function (ast) { - if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { - this.sourceMapper.currentMappings.pop(); - var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; - var sourceMapping = siblings[siblings.length - 1]; - sourceMapping.end.emittedColumn = this.emitState.column; - sourceMapping.end.emittedLine = this.emitState.line; - } - }; - Emitter.prototype.Close = function () { - if(this.sourceMapper != null) { - TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); - } - try { - this.outfile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { - if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } - if (typeof emitPrologue === "undefined") { emitPrologue = false; } - if(ast == null) { - return; - } else if(ast.nodeType != TypeScript.NodeType.List) { - this.emitPrologue(emitPrologue); - this.emitJavascript(ast, tokenId, startLine); - } else { - var list = ast; - this.emitParensAndCommentsInPlace(ast, true); - if(list.members.length == 0) { - this.emitParensAndCommentsInPlace(ast, false); - return; - } - var len = list.members.length; - for(var i = 0; i < len; i++) { - if(emitPrologue) { - if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { - this.emitPrologue(requiresExtendsBlock); - emitPrologue = false; - } - } - if(i == 1 && emitClassPropertiesAfterSuperCall) { - var constructorDecl = (this.thisClassNode).constructorDecl; - if(constructorDecl && constructorDecl.arguments) { - var argsLen = constructorDecl.arguments.members.length; - for(var iArg = 0; iArg < argsLen; iArg++) { - var arg = constructorDecl.arguments.members[iArg]; - if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { - this.emitIndent(); - this.recordSourceMappingStart(arg); - this.recordSourceMappingStart(arg.id); - this.writeToOutput("this." + arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeToOutput(" = "); - this.recordSourceMappingStart(arg.id); - this.writeToOutput(arg.id.actualText); - this.recordSourceMappingEnd(arg.id); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(arg); - } - } - } - var nProps = (this.thisClassNode.members).members.length; - for(var iMember = 0; iMember < nProps; iMember++) { - if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = (this.thisClassNode.members).members[iMember]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - this.writeLineToOutput(""); - } - } - } - } - var emitNode = list.members[i]; - var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); - if(onlyStatics ? !isStaticDecl : isStaticDecl) { - continue; - } - this.emitJavascript(emitNode, tokenId, startLine); - if(delimiter && (i < (len - 1))) { - if(startLine) { - this.writeLineToOutput(delimiter); - } else { - this.writeToOutput(delimiter); - } - } else if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { - this.writeLineToOutput(""); - } - } - this.emitParensAndCommentsInPlace(ast, false); - } - }; - Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { - if(ast == null) { - return; - } - if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { - if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { - this.emitIndent(); - } - } - ast.emit(this, tokenId, startLine); - if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { - this.writeToOutput(";"); - } - }; - Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { - if(!(funcDecl.accessorSymbol).hasBeenEmitted) { - var accessorSymbol = funcDecl.accessorSymbol; - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); - this.indenter.increaseIndent(); - if(accessorSymbol.getter) { - var getter = accessorSymbol.getter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(getter); - this.writeToOutput("get: "); - this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); - this.writeLineToOutput(","); - } - if(accessorSymbol.setter) { - var setter = accessorSymbol.setter.declAST; - this.emitIndent(); - this.recordSourceMappingStart(setter); - this.writeToOutput("set: "); - this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); - this.writeLineToOutput(","); - } - this.emitIndent(); - this.writeLineToOutput("enumerable: true,"); - this.emitIndent(); - this.writeLineToOutput("configurable: true"); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("});"); - this.recordSourceMappingEnd(funcDecl); - accessorSymbol.hasBeenEmitted = true; - } - }; - Emitter.prototype.emitPrototypeMember = function (member, className) { - if(member.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = member; - if(funcDecl.isAccessor()) { - this.emitPropertyAccessor(funcDecl, className, true); - } else { - this.emitIndent(); - this.recordSourceMappingStart(funcDecl); - this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); - this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); - this.writeLineToOutput(";"); - } - } else if(member.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = member; - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.recordSourceMappingStart(varDecl.id); - this.writeToOutput(className + ".prototype." + varDecl.id.actualText); - this.recordSourceMappingEnd(varDecl.id); - this.writeToOutput(" = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.recordSourceMappingEnd(varDecl); - this.writeLineToOutput(";"); - } - } - }; - Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { - if(base.members) { - var baseSymbol = base.symbol; - var baseName = baseSymbol.name; - if(baseSymbol.declModule != classDecl.type.symbol.declModule) { - baseName = baseSymbol.fullName(); - } - base.members.allMembers.map(function (key, s, c) { - var sym = s; - if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { - this.recordSourceMappingStart(sym.declAST); - this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); - this.recordSourceMappingEnd(sym.declAST); - } - }, null); - } - if(base.extendsList) { - for(var i = 0, len = base.extendsList.length; i < len; i++) { - this.emitAddBaseMethods(className, base.extendsList[i], classDecl); - } - } - }; - Emitter.prototype.emitJavascriptClass = function (classDecl) { - if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { - var svClassNode = this.thisClassNode; - var i = 0; - this.thisClassNode = classDecl; - var className = classDecl.name.actualText; - this.emitParensAndCommentsInPlace(classDecl, true); - var temp = this.setContainer(EmitContainer.Class); - this.recordSourceMappingStart(classDecl); - if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { - this.writeToOutput("this." + className); - } else { - this.writeToOutput("var " + className); - } - var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; - var baseNameDecl = null; - var baseName = null; - if(hasBaseClass) { - this.writeLineToOutput(" = (function (_super) {"); - } else { - this.writeLineToOutput(" = (function () {"); - } - this.recordSourceMappingNameStart(className); - this.indenter.increaseIndent(); - if(hasBaseClass) { - baseNameDecl = classDecl.extendsList.members[0]; - baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; - this.emitIndent(); - this.writeLineToOutput("__extends(" + className + ", _super);"); - } - this.emitIndent(); - var constrDecl = classDecl.constructorDecl; - if(constrDecl) { - this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); - } else { - var wroteProps = 0; - this.recordSourceMappingStart(classDecl); - this.indenter.increaseIndent(); - this.writeToOutput("function " + classDecl.name.actualText + "() {"); - this.recordSourceMappingNameStart("constructor"); - if(hasBaseClass) { - this.writeLineToOutput(""); - this.emitIndent(); - this.writeLineToOutput("_super.apply(this, arguments);"); - wroteProps++; - } - if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { - this.writeCaptureThisStatement(classDecl); - } - var members = (this.thisClassNode.members).members; - for(var i = 0; i < members.length; i++) { - if(members[i].nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = members[i]; - if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { - this.writeLineToOutput(""); - this.emitIndent(); - this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); - wroteProps++; - } - } - } - if(wroteProps) { - this.writeLineToOutput(""); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.writeLineToOutput("}"); - } else { - this.writeLineToOutput(" }"); - this.indenter.decreaseIndent(); - } - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl); - } - var membersLen = classDecl.members.members.length; - for(var j = 0; j < membersLen; j++) { - var memberDecl = classDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var fn = memberDecl; - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { - if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { - this.emitPrototypeMember(fn, className); - } else { - if(fn.isAccessor()) { - this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); - } else { - this.emitIndent(); - this.recordSourceMappingStart(fn); - this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); - this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); - this.writeLineToOutput(";"); - } - } - } - } else if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = memberDecl; - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { - if(varDecl.init) { - this.emitIndent(); - this.recordSourceMappingStart(varDecl); - this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); - this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); - this.writeLineToOutput(";"); - this.recordSourceMappingEnd(varDecl); - } - } - } else { - throw Error("We want to catch this"); - } - } - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeLineToOutput("return " + className + ";"); - this.recordSourceMappingEnd(classDecl.endingToken); - this.indenter.decreaseIndent(); - this.emitIndent(); - this.recordSourceMappingStart(classDecl.endingToken); - this.writeToOutput("}"); - this.recordSourceMappingNameEnd(); - this.recordSourceMappingEnd(classDecl.endingToken); - this.recordSourceMappingStart(classDecl); - this.writeToOutput(")("); - if(hasBaseClass) { - this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); - } - this.writeToOutput(");"); - this.recordSourceMappingEnd(classDecl); - if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { - this.writeLineToOutput(""); - this.emitIndent(); - var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; - this.recordSourceMappingStart(classDecl); - this.writeToOutput(modName + "." + className + " = " + className + ";"); - this.recordSourceMappingEnd(classDecl); - } - this.emitIndent(); - this.recordSourceMappingEnd(classDecl); - this.emitParensAndCommentsInPlace(classDecl, false); - this.setContainer(temp); - this.thisClassNode = svClassNode; - } - }; - Emitter.prototype.emitPrologue = function (reqInherits) { - if(!this.extendsPrologueEmitted) { - if(reqInherits) { - this.extendsPrologueEmitted = true; - this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); - this.writeLineToOutput(" function __() { this.constructor = d; }"); - this.writeLineToOutput(" __.prototype = b.prototype;"); - this.writeLineToOutput(" d.prototype = new __();"); - this.writeLineToOutput("};"); - } - } - if(!this.globalThisCapturePrologueEmitted) { - if(this.checker.mustCaptureGlobalThis) { - this.globalThisCapturePrologueEmitted = true; - this.writeLineToOutput(this.captureThisStmtString); - } - } - }; - Emitter.prototype.emitSuperReference = function () { - this.writeToOutput("_super.prototype"); - }; - Emitter.prototype.emitSuperCall = function (callEx) { - if(callEx.target.nodeType == TypeScript.NodeType.Dot) { - var dotNode = callEx.target; - if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { - this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); - this.writeToOutput(".call("); - this.emitThis(); - if(callEx.arguments && callEx.arguments.members.length > 0) { - this.writeToOutput(", "); - this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); - } - this.writeToOutput(")"); - return true; - } - } - return false; - }; - Emitter.prototype.emitThis = function () { - if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { - this.writeToOutput("_this"); - } else { - this.writeToOutput("this"); - } - }; - Emitter.shouldCaptureThis = function shouldCaptureThis(func) { - return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); - }; - Emitter.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitOptions.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return Emitter; - })(); - TypeScript.Emitter = Emitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ErrorReporter = (function () { - function ErrorReporter(outfile) { - this.outfile = outfile; - this.parser = null; - this.checker = null; - this.lineCol = { - line: 0, - col: 0 - }; - this.emitAsComments = true; - this.hasErrors = false; - this.pushToErrorSink = false; - this.errorSink = []; - } - ErrorReporter.prototype.getCapturedErrors = function () { - return this.errorSink; - }; - ErrorReporter.prototype.freeCapturedErrors = function () { - this.errorSink = []; - }; - ErrorReporter.prototype.captureError = function (emsg) { - this.errorSink[this.errorSink.length] = emsg; - }; - ErrorReporter.prototype.setErrOut = function (outerr) { - this.outfile = outerr; - this.emitAsComments = false; - }; - ErrorReporter.prototype.emitPrefix = function () { - if(this.emitAsComments) { - this.outfile.Write("// "); - } - this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); - }; - ErrorReporter.prototype.writePrefix = function (ast) { - if(ast) { - this.setError(ast); - } else { - this.lineCol.line = 0; - this.lineCol.col = 0; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.writePrefixFromSym = function (symbol) { - if(symbol && this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); - } else { - this.lineCol.line = -1; - this.lineCol.col = -1; - } - this.emitPrefix(); - }; - ErrorReporter.prototype.setError = function (ast) { - if(ast) { - ast.flags |= TypeScript.ASTFlags.Error; - if(this.checker.locationInfo.lineMap) { - TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); - } - } - }; - ErrorReporter.prototype.reportError = function (ast, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(ast && this.parser.errorRecovery && this.parser.errorCallback) { - var len = (ast.limChar - ast.minChar); - this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefix(ast); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { - if(this.pushToErrorSink) { - this.captureError(message); - return; - } - this.hasErrors = true; - if(this.parser.errorRecovery && this.parser.errorCallback) { - this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); - } else { - this.writePrefixFromSym(symbol); - this.outfile.WriteLine(message); - } - }; - ErrorReporter.prototype.emitterError = function (ast, message) { - this.reportError(ast, message); - throw Error("EmitError"); - }; - ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { - this.reportError(ast, "Duplicate identifier '" + name + "'"); - }; - ErrorReporter.prototype.showRef = function (ast, text, symbol) { - var defLineCol = { - line: -1, - col: -1 - }; - this.parser.getSourceLineCol(defLineCol, symbol.location); - this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); - }; - ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); - }; - ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { - this.reportError(ast, "The name '" + name + "' does not refer to a value"); - }; - ErrorReporter.prototype.styleError = function (ast, msg) { - var bkThrow = this.pushToErrorSink; - this.pushToErrorSink = false; - this.reportError(ast, "STYLE: " + msg); - this.pushToErrorSink = bkThrow; - }; - ErrorReporter.prototype.simpleError = function (ast, msg) { - this.reportError(ast, msg); - }; - ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { - this.reportErrorFromSym(sym, msg); - }; - ErrorReporter.prototype.invalidSuperReference = function (ast) { - this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); - }; - ErrorReporter.prototype.valueCannotBeModified = function (ast) { - this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); - }; - ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { - var targetType = ast.target.type; - var typeName = targetType.getScopedTypeName(scope); - if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { - this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); - } else { - var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; - this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); - } - }; - ErrorReporter.prototype.indexLHS = function (ast, scope) { - var targetType = ast.operand1.type.getScopedTypeName(scope); - var indexType = ast.operand2.type.getScopedTypeName(scope); - this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); - }; - ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { - if(!t1) { - t1 = this.checker.anyType; - } - if(!t2) { - t2 = this.checker.anyType; - } - var reason = comparisonInfo ? comparisonInfo.message : ""; - if(op) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } else { - this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); - } - }; - ErrorReporter.prototype.expectedClassOrInterface = function (ast) { - this.simpleError(ast, "Expected var, class, interface, or module"); - }; - ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { - this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); - }; - return ErrorReporter; - })(); - TypeScript.ErrorReporter = ErrorReporter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeContext) { - TypeContext._map = []; - TypeContext.NoTypes = 0; - TypeContext.ArraySuffix = 1; - TypeContext.Primitive = 2; - TypeContext.Named = 4; - TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; - TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; - })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); - var TypeContext = TypeScript.TypeContext; - var QuickParseResult = (function () { - function QuickParseResult(Script, endLexState) { - this.Script = Script; - this.endLexState = endLexState; - } - return QuickParseResult; - })(); - TypeScript.QuickParseResult = QuickParseResult; - var Parser = (function () { - function Parser() { - this.varLists = []; - this.scopeLists = []; - this.staticsLists = []; - this.scanner = new TypeScript.Scanner(); - this.currentToken = null; - this.needTerminator = false; - this.inFunction = false; - this.inInterfaceDecl = false; - this.currentClassDecl = null; - this.inFncDecl = false; - this.anonId = new TypeScript.Identifier("_anonymous"); - this.style_requireSemi = false; - this.style_funcInLoop = true; - this.incremental = false; - this.errorRecovery = false; - this.outfile = undefined; - this.errorCallback = null; - this.ambientModule = false; - this.ambientClass = false; - this.topLevel = true; - this.allowImportDeclaration = true; - this.currentUnitIndex = (-1); - this.prevIDTok = null; - this.statementInfoStack = new Array(); - this.hasTopLevelImportOrExport = false; - this.strictMode = false; - this.nestingLevel = 0; - this.prevExpr = null; - this.currentClassDefinition = null; - this.parsingClassConstructorDefinition = false; - this.parsingDeclareFile = false; - this.amdDependencies = []; - this.inferPropertiesFromThisAssignment = false; - this.requiresExtendsBlock = false; - this.fname = ""; - } - Parser.prototype.resetStmtStack = function () { - this.statementInfoStack = new Array(); - }; - Parser.prototype.inLoop = function () { - for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { - if(this.statementInfoStack[j].stmt.isLoop()) { - return true; - } - } - return false; - }; - Parser.prototype.pushStmt = function (stmt, labels) { - var info = { - stmt: stmt, - labels: labels - }; - this.statementInfoStack.push(info); - }; - Parser.prototype.popStmt = function () { - return this.statementInfoStack.pop(); - }; - Parser.prototype.resolveJumpTarget = function (jump) { - var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); - var len = this.statementInfoStack.length; - for(var i = len - 1; i >= 0; i--) { - var info = this.statementInfoStack[i]; - if(jump.target) { - if(info.labels && (info.labels.members.length > 0)) { - for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { - var label = info.labels.members[j]; - if(label.id.text == resolvedTarget) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - } else { - if(info.stmt.isLoop()) { - jump.setResolvedTarget(this, info.stmt); - return; - } else if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { - jump.setResolvedTarget(this, info.stmt); - return; - } - } - } - if(jump.target) { - this.reportParseError("could not find enclosing statement with label " + jump.target); - } else { - if(jump.nodeType == TypeScript.NodeType.Break) { - this.reportParseError("break statement requires enclosing loop or switch"); - } else { - this.reportParseError("continue statement requires enclosing loop"); - } - } - }; - Parser.prototype.setErrorRecovery = function (outfile) { - this.outfile = outfile; - this.errorRecovery = true; - }; - Parser.prototype.getSourceLineCol = function (lineCol, minChar) { - TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); - }; - Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { - var id = new TypeScript.Identifier(text, hasEscapeSequence); - id.minChar = minChar; - return id; - }; - Parser.prototype.reportParseStyleError = function (message) { - this.reportParseError("STYLE: " + message); - }; - Parser.prototype.reportParseError = function (message, startPos, pos) { - if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } - if (typeof pos === "undefined") { pos = this.scanner.pos; } - var len = Math.max(1, pos - startPos); - if(this.errorCallback) { - this.errorCallback(startPos, len, message, this.currentUnitIndex); - } else if(this.errorRecovery) { - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, startPos); - if(this.outfile) { - this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); - } - } else { - throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); - } - }; - Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(tokenId, errorRecoverySet, errorText); - }; - Parser.prototype.skip = function (errorRecoverySet) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; - var ersTok = TypeScript.ErrorRecoverySet.None; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - var pendingRightCurlies = 0; - while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { - if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - pendingRightCurlies++; - } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - pendingRightCurlies--; - } - this.currentToken = this.scanner.scan(); - ersTok = TypeScript.ErrorRecoverySet.None; - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if(tokenInfo != undefined) { - ersTok = tokenInfo.ers; - } - } - }; - Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { - if (typeof errorText === "undefined") { errorText = null; } - if(this.currentToken.tokenId != tokenId) { - errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; - this.reportParseError(errorText); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - } - } else { - this.currentToken = this.scanner.scan(); - } - }; - Parser.prototype.pushDeclLists = function () { - this.staticsLists.push(new TypeScript.ASTList()); - this.varLists.push(new TypeScript.ASTList()); - this.scopeLists.push(new TypeScript.ASTList()); - }; - Parser.prototype.popDeclLists = function () { - this.staticsLists.pop(); - this.varLists.pop(); - this.scopeLists.pop(); - }; - Parser.prototype.topVarList = function () { - return this.varLists[this.varLists.length - 1]; - }; - Parser.prototype.topScopeList = function () { - return this.scopeLists[this.scopeLists.length - 1]; - }; - Parser.prototype.topStaticsList = function () { - return this.staticsLists[this.staticsLists.length - 1]; - }; - Parser.prototype.parseComment = function (comment) { - if(comment) { - var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); - c.minChar = comment.startPos; - c.limChar = comment.startPos + comment.value.length; - var lineCol = { - line: -1, - col: -1 - }; - this.getSourceLineCol(lineCol, c.minChar); - c.minLine = lineCol.line; - this.getSourceLineCol(lineCol, c.limChar); - c.limLine = lineCol.line; - if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { - var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); - if(dependencyPath) { - this.amdDependencies.push(dependencyPath); - } - if(TypeScript.getImplicitImport(comment.value)) { - this.hasTopLevelImportOrExport = true; - } - } - return c; - } else { - return null; - } - }; - Parser.prototype.parseCommentsInner = function (comments) { - if(comments) { - var commentASTs = new Array(); - for(var i = 0; i < comments.length; i++) { - commentASTs.push(this.parseComment(comments[i])); - } - return commentASTs; - } else { - return null; - } - }; - Parser.prototype.parseComments = function () { - var comments = this.scanner.getComments(); - return this.parseCommentsInner(comments); - }; - Parser.prototype.parseCommentsForLine = function (line) { - var comments = this.scanner.getCommentsForLine(line); - return this.parseCommentsInner(comments); - }; - Parser.prototype.combineComments = function (comment1, comment2) { - if(comment1 == null) { - return comment2; - } else if(comment2 == null) { - return comment1; - } else { - return comment1.concat(comment2); - } - }; - Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Enum declaration requires identifier"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.startPos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - this.pushDeclLists(); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); - mapDecl.varFlags |= TypeScript.VarFlags.Exported; - mapDecl.varFlags |= TypeScript.VarFlags.Private; - mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); - mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); - members.append(mapDecl); - var lastValue = null; - var memberNames = []; - for(; ; ) { - var minChar = this.scanner.startPos; - var limChar; - var memberName = null; - var memberValue = null; - var preComments = null; - var postComments = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - memberNames.push(memberName); - } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } else { - this.reportParseError("Expected identifer of enum member"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - } - } - limChar = this.scanner.pos; - preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - postComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - this.currentToken = this.scanner.scan(); - memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - lastValue = memberValue; - limChar = memberValue.limChar; - } else { - if(lastValue == null) { - memberValue = new TypeScript.NumberLiteral(0, "0"); - lastValue = memberValue; - } else { - var nextValue = lastValue.value + 1; - memberValue = new TypeScript.NumberLiteral(nextValue, nextValue.toString()); - lastValue = memberValue; - } - var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); - members.append(map); - } - var member = new TypeScript.VarDecl(memberName, this.nestingLevel); - member.minChar = minChar; - member.limChar = limChar; - member.init = memberValue; - member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); - member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); - if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { - member.varFlags |= TypeScript.VarFlags.Constant; - } else if(memberValue.nodeType === TypeScript.NodeType.Lsh) { - var binop = memberValue; - if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { - member.varFlags |= TypeScript.VarFlags.Constant; - } - } else if(memberValue.nodeType === TypeScript.NodeType.Name) { - var nameNode = memberValue; - for(var i = 0; i < memberNames.length; i++) { - var memberName = memberNames[i]; - if(memberName.text === nameNode.text) { - member.varFlags |= TypeScript.VarFlags.Constant; - break; - } - } - } - member.preComments = preComments; - members.append(member); - member.postComments = postComments; - member.varFlags |= TypeScript.VarFlags.Exported; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { - continue; - } - } - break; - } - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - members.limChar = this.scanner.lastTokenLimChar(); - var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), endingToken); - modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; - this.popDeclLists(); - modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return modDecl; - }; - Parser.prototype.parseDottedName = function (enclosedList) { - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.preComments = this.parseComments(); - enclosedList[enclosedList.length] = id; - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - this.parseDottedName(enclosedList); - } - } else { - this.reportParseError("need identifier after '.'"); - } - }; - Parser.prototype.isValidImportPath = function (importPath) { - importPath = TypeScript.stripQuotes(importPath); - if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { - return false; - } - return true; - }; - Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { - var name = null; - var alias = null; - var importDecl = null; - var minChar = this.scanner.startPos; - var isDynamicImport = false; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - name = TypeScript.Identifier.fromToken(this.currentToken); - } else { - this.reportParseError("Expected identifer after 'import'"); - name = new TypeScript.MissingIdentifier(); - } - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - var aliasPreComments = this.parseComments(); - var limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Module) { - limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } else if(!this.allowImportDeclaration) { - this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); - } - var aliasText = this.currentToken.getText(); - alias = TypeScript.Identifier.fromToken(this.currentToken); - alias.minChar = this.scanner.startPos; - alias.limChar = this.scanner.pos; - if(!this.isValidImportPath((alias).text)) { - this.reportParseError("Invalid import path"); - } - isDynamicImport = true; - this.currentToken = this.scanner.scan(); - alias.preComments = aliasPreComments; - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - alias.preComments = aliasPreComments; - } - } - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(alias) { - alias.postComments = this.parseComments(); - } - } - } else { - alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - limChar = this.scanner.pos; - } - } else { - this.reportParseError("Expected module name"); - alias = new TypeScript.MissingIdentifier(); - alias.minChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - alias.limChar = this.scanner.startPos; - } else { - alias.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - alias.flags |= TypeScript.ASTFlags.Error; - limChar = alias.limChar; - } - importDecl = new TypeScript.ImportDeclaration(name, alias); - importDecl.isDynamicImport = isDynamicImport; - importDecl.minChar = minChar; - importDecl.limChar = limChar; - return importDecl; - }; - Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var svAmbient = this.ambientModule; - var svTopLevel = this.topLevel; - this.topLevel = false; - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.ambientModule = true; - } - this.currentToken = this.scanner.scan(); - var name = null; - var enclosedList = null; - this.pushDeclLists(); - var minChar = this.scanner.startPos; - var isDynamicMod = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var nameText = this.currentToken.getText(); - if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - isDynamicMod = true; - if(!this.ambientModule) { - this.reportParseError("Only ambient dynamic modules may have string literal names"); - } - if(!svTopLevel) { - this.reportParseError("Dynamic modules may not be nested within other modules"); - } - } - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { - this.reportParseError("Module name missing"); - name = new TypeScript.Identifier(""); - name.minChar = minChar; - name.limChar = minChar; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - enclosedList = new Array(); - this.parseDottedName(enclosedList); - } - if(name == null) { - name = new TypeScript.MissingIdentifier(); - } - var moduleBody = new TypeScript.ASTList(); - var bodyMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); - if(svTopLevel && isDynamicMod) { - this.allowImportDeclaration = true; - } else { - this.allowImportDeclaration = false; - } - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); - moduleBody.minChar = bodyMinChar; - moduleBody.limChar = this.scanner.pos; - var endingToken = new TypeScript.ASTSpan(); - endingToken.minChar = this.scanner.startPos; - endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var limChar = this.scanner.lastTokenLimChar(); - var moduleDecl; - this.allowImportDeclaration = svTopLevel; - if(enclosedList && (enclosedList.length > 0)) { - var len = enclosedList.length; - var innerName = enclosedList[len - 1]; - var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), endingToken); - innerDecl.preComments = preComments; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - innerDecl.minChar = minChar; - innerDecl.limChar = limChar; - this.popDeclLists(); - var outerModBod; - for(var i = len - 2; i >= 0; i--) { - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - innerName = enclosedList[i]; - innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), endingToken); - outerModBod.minChar = innerDecl.minChar = minChar; - outerModBod.limChar = innerDecl.limChar = limChar; - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - outerModBod = new TypeScript.ASTList(); - outerModBod.append(innerDecl); - outerModBod.minChar = minChar; - outerModBod.limChar = limChar; - moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), endingToken); - } else { - moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), endingToken); - moduleDecl.preComments = preComments; - this.popDeclLists(); - } - if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; - } - if(isDynamicMod) { - moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; - } - this.ambientModule = svAmbient; - this.topLevel = svTopLevel; - moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - moduleDecl.limChar = moduleBody.limChar; - return moduleDecl; - }; - Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { - var result = new TypeScript.TypeReference(term, 0); - result.minChar = minChar; - while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { - this.currentToken = this.scanner.scan(); - result.arrayCount++; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); - } - result.limChar = this.scanner.lastTokenLimChar(); - return result; - }; - Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - var op2 = TypeScript.Identifier.fromToken(this.currentToken); - op2.minChar = this.scanner.startPos; - op2.limChar = this.scanner.pos; - var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); - dotNode.minChar = term.minChar; - dotNode.limChar = op2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); - } else { - this.reportParseError("need identifier after '.'"); - if(this.errorRecovery) { - term.flags |= TypeScript.ASTFlags.DotLHS; - term.limChar = this.scanner.lastTokenLimChar(); - return term; - } else { - var eop2 = new TypeScript.MissingIdentifier(); - eop2.minChar = this.scanner.pos; - eop2.limChar = this.scanner.pos; - var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); - edotNode.flags |= TypeScript.ASTFlags.Error; - edotNode.minChar = term.minChar; - edotNode.limChar = eop2.limChar; - return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); - } - } - } else { - if(tail) { - return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); - } else { - return term; - } - } - }; - Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { - var minChar = this.scanner.startPos; - var isConstructorMember = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Void: - if(!allowVoid) { - this.reportParseError("void not a valid type in this context"); - } - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.String: { - var text = TypeScript.tokenTable[this.currentToken.tokenId].text; - var predefinedIdentifier = new TypeScript.Identifier(text); - predefinedIdentifier.minChar = minChar; - predefinedIdentifier.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); - } - case TypeScript.TokenID.Identifier: - var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); - ident.limChar = this.scanner.pos; - return this.parseNamedType(errorRecoverySet, minChar, ident, true); - case TypeScript.TokenID.OpenBrace: - return this.parseObjectType(minChar, errorRecoverySet); - case TypeScript.TokenID.New: - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { - this.reportParseError("Expected '('"); - } else { - isConstructorMember = true; - } - case TypeScript.TokenID.OpenParen: { - var formals = new TypeScript.ASTList(); - var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); - this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); - var returnType = this.parseTypeReference(errorRecoverySet, true); - var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); - funcDecl.returnTypeAnnotation = returnType; - funcDecl.variableArgList = variableArgList; - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - if(isConstructorMember) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = null; - } - funcDecl.minChar = minChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); - } - default: - this.reportParseError("Expected type name"); - var etr = new TypeScript.TypeReference(null, 0); - etr.flags |= TypeScript.ASTFlags.Error; - etr.minChar = this.scanner.pos; - etr.limChar = this.scanner.pos; - return etr; - } - }; - Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { - this.currentToken = this.scanner.scan(); - var members = new TypeScript.ASTList(); - members.minChar = minChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); - interfaceDecl.minChar = minChar; - interfaceDecl.limChar = members.limChar; - return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); - }; - Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - var savedInFunction = this.inFunction; - this.inFunction = true; - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); - bod.minChar = bodMinChar; - bod.limChar = this.scanner.pos; - this.inFunction = savedInFunction; - if(bod.limChar > bod.minChar) { - var ec = new TypeScript.EndCode(); - ec.minChar = bod.limChar; - ec.limChar = ec.minChar; - bod.append(ec); - } - }; - Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { - this.pushDeclLists(); - var svStmtStack = this.statementInfoStack; - this.resetStmtStack(); - var bod = null; - var wasShorthand = false; - var isAnonLambda = false; - var limChar; - if(requiresSignature) { - limChar = this.scanner.pos; - if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { - this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - } else { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); - } - } else { - bod = new TypeScript.ASTList(); - var bodMinChar = this.scanner.startPos; - if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { - if(isMethod) { - this.reportParseError("'=>' may not be used for class methods"); - } - wasShorthand = true; - this.currentToken = this.scanner.scan(); - } - if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.returnExpression = retExpr; - retStmt.minChar = retExpr.minChar; - retStmt.limChar = retExpr.limChar; - bod.minChar = bodMinChar; - bod.limChar = retExpr.limChar; - bod.append(retStmt); - } else if(this.currentToken.tokenId != TypeScript.TokenID.EndOfFile) { - isAnonLambda = wasShorthand; - this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); - } - limChar = this.scanner.pos; - } - var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); - this.popDeclLists(); - var scopeList = this.topScopeList(); - scopeList.append(funcDecl); - var staticFuncDecl = false; - if(!requiresSignature) { - if(!wasShorthand || isAnonLambda) { - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = this.scanner.startPos; - funcDecl.endingToken.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - if(isAnonLambda) { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - } - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - funcDecl.endingToken = new TypeScript.ASTSpan(); - funcDecl.endingToken.minChar = bod.members[0].minChar; - funcDecl.endingToken.limChar = bod.members[0].limChar; - } - } - funcDecl.minChar = minChar; - funcDecl.limChar = limChar; - if(requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - this.statementInfoStack = svStmtStack; - return funcDecl; - }; - Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { - var _this = this; - var translateBinExOperand = function (operand) { - if(operand.nodeType == TypeScript.NodeType.Comma) { - return _this.transformAnonymousArgsIntoFormals(formals, operand); - } else if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { - var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; - opArg.isParenthesized = false; - var arg = new TypeScript.ArgDecl(opArg); - arg.preComments = opArg.preComments; - arg.postComments = opArg.postComments; - arg.minChar = operand.minChar; - arg.limChar = operand.limChar; - if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - arg.isOptional = true; - } - if(operand.nodeType == TypeScript.NodeType.Asg) { - arg.init = (operand).operand2; - } - formals.append(arg); - return arg.isOptional || arg.init; - } else { - _this.reportParseError("Invalid lambda argument"); - } - return false; - }; - if(argList) { - if(argList.nodeType == TypeScript.NodeType.Comma) { - var commaList = argList; - if(commaList.operand1.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); - } - if(commaList.operand2.isParenthesized) { - this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); - } - var isOptional = translateBinExOperand(commaList.operand1); - isOptional = translateBinExOperand(commaList.operand2) || isOptional; - return isOptional; - } else { - return translateBinExOperand(argList); - } - } - }; - Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { - formals.minChar = this.scanner.startPos; - if(isIndexer) { - this.currentToken = this.scanner.scan(); - } else if(!isLambda) { - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); - } - var sawEllipsis = false; - var firstArg = true; - var hasOptional = false; - var haveFirstArgID = false; - if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { - hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); - formals.minChar = preProcessedLambdaArgs.minChar; - haveFirstArgID = true; - } - while(true) { - var munchedArg = false; - var argFlags = TypeScript.VarFlags.None; - var argMinChar = this.scanner.startPos; - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); - if(this.currentClassDefinition) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { - this.reportParseError("Static properties can not be declared as parameter properties"); - this.currentToken = this.scanner.scan(); - } - if(argFlags != TypeScript.VarFlags.None) { - if(!isClassConstr) { - this.reportParseError("only constructor parameters can be properties"); - } - this.currentToken = this.scanner.scan(); - if(TypeScript.isModifier(this.currentToken)) { - this.reportParseError("Multiple modifiers may not be applied to parameters"); - this.currentToken = this.scanner.scan(); - } - if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { - if(!isClassConstr) { - this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); - } - this.currentToken = this.scanner.scan(); - this.currentToken = this.scanner.scan(); - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - sawEllipsis = true; - this.currentToken = this.scanner.scan(); - if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - sawEllipsis = false; - } - } - var argId = null; - if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - argId = TypeScript.Identifier.fromToken(this.currentToken); - argId.minChar = this.scanner.startPos; - argId.limChar = this.scanner.pos; - } - if(haveFirstArgID || argId) { - munchedArg = true; - var type = null; - var arg = null; - if(haveFirstArgID && formals.members.length) { - arg = formals.members[formals.members.length - 1]; - if(arg.isOptional) { - hasOptional = true; - } - } else { - arg = new TypeScript.ArgDecl(argId); - if(isGetter) { - this.reportParseError("Property getters may not take any arguments"); - } - if(isSetter && !firstArg) { - this.reportParseError("Property setters may only take one argument"); - } - arg.minChar = argMinChar; - arg.preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - arg.isOptional = true; - hasOptional = true; - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - type = this.parseTypeReference(errorRecoverySet, false); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(isSig) { - this.reportParseError("Arguments in signatures may not have default values"); - } - hasOptional = true; - this.currentToken = this.scanner.scan(); - arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); - } - if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { - this.reportParseError("Optional parameters may only be followed by other optional parameters"); - } - if(sawEllipsis && arg.isOptionalArg()) { - this.reportParseError("Varargs may not be optional or have default parameters"); - } - if(sawEllipsis && !type) { - this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); - } - arg.postComments = this.parseComments(); - arg.typeExpr = type; - arg.limChar = this.scanner.lastTokenLimChar(); - arg.varFlags |= argFlags; - if(!haveFirstArgID) { - formals.append(arg); - } else { - haveFirstArgID = false; - } - } - firstArg = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - if((munchedArg) && (!sawEllipsis)) { - this.currentToken = this.scanner.scan(); - continue; - } else { - this.reportParseError("Unexpected ',' in argument list"); - if(this.errorRecovery) { - this.currentToken = this.scanner.scan(); - continue; - } - } - } else { - break; - } - } - if(isIndexer) { - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } else if(expectClosingRParen) { - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); - } - formals.limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); - return sawEllipsis; - }; - Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var prevInConstr = this.parsingClassConstructorDefinition; - this.parsingClassConstructorDefinition = false; - var name = null; - var fnMin = this.scanner.startPos; - var minChar = this.scanner.pos; - var prevNestingLevel = this.nestingLevel; - var preComments = this.parseComments(); - var isLambda = !!lambdaArgContext; - this.nestingLevel = 0; - if((!this.style_funcInLoop) && this.inLoop()) { - this.reportParseStyleError("function declaration in loop"); - } - if(!isMethod && !isStatic && !indexer && !lambdaArgContext && !methodName) { - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - if(isDecl) { - this.reportParseError("Function declaration must include identifier"); - this.nestingLevel = prevNestingLevel; - return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); - } - } else { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } else { - if(methodName) { - name = methodName; - } - } - var args = new TypeScript.ASTList(); - var variableArgList = false; - var isOverload = false; - var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); - var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); - } - var returnType = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { - this.reportParseError("Property setters may not declare a return type"); - } - returnType = this.parseTypeReference(errorRecoverySet, true); - } - if(indexer && args.members.length == 0) { - this.reportParseError("Index signatures require a parameter type to be specified"); - } - if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { - this.reportParseError("Expected '=>'"); - } - if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && !this.ambientModule && !this.ambientClass && !this.inInterfaceDecl && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - isOverload = true; - isDecl = false; - requiresSignature = true; - } - var svInFncDecl = this.inFncDecl; - this.inFncDecl = true; - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); - this.inFncDecl = svInFncDecl; - funcDecl.variableArgList = variableArgList; - funcDecl.isOverload = isOverload; - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(requiresSignature) { - funcDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(indexer) { - funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; - } - funcDecl.returnTypeAnnotation = returnType; - if(isMethod) { - funcDecl.fncFlags |= TypeScript.FncFlags.Method; - funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; - } - funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - this.nestingLevel = prevNestingLevel; - this.parsingClassConstructorDefinition = prevInConstr; - funcDecl.preComments = preComments; - return funcDecl; - }; - Parser.prototype.convertToTypeReference = function (ast) { - var result; - switch(ast.nodeType) { - case TypeScript.NodeType.TypeRef: - return ast; - case TypeScript.NodeType.Name: - result = new TypeScript.TypeReference(ast, 0); - result.minChar = ast.minChar; - result.limChar = ast.limChar; - return result; - case TypeScript.NodeType.Index: { - var expr = ast; - result = this.convertToTypeReference(expr.operand1); - if(result) { - result.arrayCount++; - result.minChar = expr.minChar; - result.limChar = expr.limChar; - return result; - } else { - var etr = new TypeScript.AST(TypeScript.NodeType.Error); - return etr; - } - } - } - return null; - }; - Parser.prototype.parseArgList = function (errorRecoverySet) { - var args = new TypeScript.ASTList(); - args.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { - while(true) { - if(args.members.length > 0xffff) { - this.reportParseError("max number of args exceeded"); - break; - } - var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - args.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - } - args.limChar = this.scanner.pos; - return args; - }; - Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { - var keyword = true; - var currentList = extendsList; - for(; ; ) { - if(keyword) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - currentList = implementsList; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - this.currentToken = this.scanner.scan(); - keyword = false; - } - var baseName = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var minChar = this.scanner.startPos; - baseName = TypeScript.Identifier.fromToken(this.currentToken); - baseName.minChar = minChar; - baseName.limChar = this.scanner.pos; - baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); - } else { - this.reportParseError("Expected base name"); - if(this.errorRecovery) { - baseName = new TypeScript.MissingIdentifier(); - baseName.minChar = this.scanner.pos; - baseName.limChar = this.scanner.pos; - baseName.flags |= TypeScript.ASTFlags.Error; - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - if(isClass) { - this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); - } else { - this.reportParseError("Interfaces may not be extended with a call expression"); - } - } else { - currentList.append(baseName); - } - if(isClass && currentList == extendsList && extendsList.members.length > 1) { - this.reportParseError("A class may only extend one other class"); - } - if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { - this.currentToken = this.scanner.scan(); - continue; - } else if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { - this.requiresExtendsBlock = isClass; - } - currentList = extendsList; - keyword = true; - continue; - } - break; - } - }; - Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - this.reportParseError("const modifier is implicit for class"); - } - if(this.parsingDeclareFile || this.ambientModule) { - modifiers |= TypeScript.Modifiers.Ambient; - modifiers |= TypeScript.Modifiers.Exported; - } - var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; - var svAmbientClass = this.ambientClass; - this.ambientClass = classIsMarkedAsAmbient; - this.currentToken = this.scanner.scan(); - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("class missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - var requiresSignature = false; - if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); - } - var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); - this.currentClassDefinition = classDecl; - this.parseClassElements(classDecl, errorRecoverySet, modifiers); - if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - classDecl.varFlags |= TypeScript.VarFlags.Exported; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - classDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - classDecl.varFlags |= TypeScript.VarFlags.Class; - this.ambientClass = svAmbientClass; - classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return classDecl; - }; - Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { - var modifiers = parentModifiers; - var resetModifiers = false; - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); - this.nestingLevel++; - var currentMemberMinChar = this.scanner.startPos; - var wasGetOrSetId = false; - while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - var scanNext = true; - var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Duplicate 'get' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Getter already marked as a setter"); - } - modifiers |= TypeScript.Modifiers.Getter; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - if(modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Duplicate 'set' declaration in class body"); - } - if(modifiers & TypeScript.Modifiers.Getter) { - this.reportParseError("Setter already marked as a getter"); - } - modifiers |= TypeScript.Modifiers.Setter; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Private; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Public) { - if(modifiers & publicOrPrivateFlags) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Public; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Static) { - if(modifiers & TypeScript.Modifiers.Static) { - this.reportParseError("Multiple modifiers may not be applied to class members"); - } - modifiers |= TypeScript.Modifiers.Static; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { - if(modifiers != parentModifiers) { - this.reportParseError("Constructors may not have modifiers"); - } - this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - resetModifiers = true; - } else if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { - var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); - var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - if(wasGetOrSetId) { - modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); - wasGetOrSetId = false; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); - scanNext = false; - } else { - if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { - this.reportParseError("Property accessors must be functions"); - } - var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); - if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - scanNext = false; - } - } else if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - scanNext = false; - varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Expected ';'"); - scanNext = false; - } - } - resetModifiers = true; - } else if(this.currentToken.tokenId == TypeScript.TokenID.Super) { - this.reportParseError("Base class initializers must be the first statement in a class definition"); - } else if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { - wasGetOrSetId = true; - scanNext = false; - } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); - resetModifiers = true; - } - if(scanNext) { - this.currentToken = this.scanner.scan(); - } - if(resetModifiers) { - modifiers = parentModifiers; - currentMemberMinChar = this.scanner.startPos; - resetModifiers = false; - } - } - var membersLimChar = this.scanner.pos; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - classDecl.endingToken = new TypeScript.ASTSpan(); - classDecl.endingToken.minChar = this.scanner.startPos; - classDecl.endingToken.limChar = this.scanner.pos; - if(!this.currentClassDefinition.members.members.length) { - this.currentClassDefinition.preComments = this.parseComments(); - } - this.currentToken = this.scanner.scan(); - } - this.nestingLevel--; - this.currentClassDefinition.members.minChar = membersMinChar; - this.currentClassDefinition.members.limChar = membersLimChar; - this.currentClassDefinition.limChar = membersLimChar; - this.currentClassDefinition = null; - }; - Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { - this.parsingClassConstructorDefinition = true; - var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - var args = new TypeScript.ASTList(); - var variableArgList = false; - var preComments = this.parseComments(); - var constructorSpan = new TypeScript.ASTSpan(); - constructorSpan.minChar = this.scanner.startPos; - constructorSpan.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); - if(args.members.length > 0) { - var lastArg = args.members[args.members.length - 1]; - } - } - var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; - if(requiresSignature) { - for(var i = 0; i < args.members.length; i++) { - var arg = args.members[i]; - if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { - this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); - } - } - } - if(!requiresSignature) { - this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; - } - var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); - constructorFuncDecl.constructorSpan = constructorSpan; - constructorFuncDecl.preComments = preComments; - if(requiresSignature && !isAmbient) { - constructorFuncDecl.isOverload = true; - } - constructorFuncDecl.variableArgList = variableArgList; - this.currentClassDecl = null; - constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); - constructorFuncDecl.classDecl = this.currentClassDefinition; - if(isAmbient) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(requiresSignature) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; - } - if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; - } - if(this.currentClassDefinition.constructorDecl) { - if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { - this.reportParseError("Duplicate constructor definition"); - } - } - if(isAmbient || !constructorFuncDecl.isSignature()) { - this.currentClassDefinition.constructorDecl = constructorFuncDecl; - } - constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; - this.parsingClassConstructorDefinition = false; - return constructorFuncDecl; - }; - Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.minChar = minChar; - var isStatic = false; - varDecl.preComments = this.parseComments(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(!(modifiers & TypeScript.Modifiers.Static)) { - this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; - } - } else { - varDecl.limChar = this.scanner.pos; - } - if(modifiers & TypeScript.Modifiers.Static) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - isStatic = true; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } else { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - if(isDeclaredInConstructor) { - varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; - } - if(!isDeclaredInConstructor && !isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; - } - this.currentClassDefinition.knownMemberNames[text.actualText] = true; - if(!isDeclaredInConstructor) { - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; - } - varDecl.postComments = this.parseComments(); - return varDecl; - }; - Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); - var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); - errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; - if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { - this.reportParseError("Property accessors may not be declared in ambient classes"); - } - var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } - var funcDecl = ast; - funcDecl.minChar = minChar; - if(funcDecl.bod !== null) { - funcDecl.limChar = funcDecl.bod.limChar; - } - if(modifiers & TypeScript.Modifiers.Private) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); - } - } - funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; - this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; - this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; - return funcDecl; - }; - Parser.prototype.parseTypeMember = function (errorRecoverySet) { - var minChar = this.scanner.startPos; - var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); - if(propertyDecl) { - propertyDecl.minChar = minChar; - if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - } - } - return propertyDecl; - }; - Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; - while(true) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.CloseBrace: - case TypeScript.TokenID.EndOfFile: - members.limChar = this.scanner.pos; - return; - } - var element = this.parseTypeMember(errorRecoverySet); - if(element) { - members.append(element); - } - } - }; - Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - this.currentToken = this.scanner.scan(); - var minChar = this.scanner.pos; - var name = null; - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - name = TypeScript.Identifier.fromToken(this.currentToken); - name.minChar = this.scanner.startPos; - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("interface missing name"); - if(this.errorRecovery) { - name = new TypeScript.MissingIdentifier(); - name.minChar = this.scanner.pos; - name.limChar = this.scanner.pos; - name.flags |= TypeScript.ASTFlags.Error; - } - } - var extendsList = null; - var implementsList = null; - if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { - if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { - this.reportParseError("Expected 'extends'"); - } - extendsList = new TypeScript.ASTList(); - implementsList = new TypeScript.ASTList(); - extendsList.minChar = this.scanner.startPos; - this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); - } - var membersMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); - var members = new TypeScript.ASTList(); - members.minChar = membersMinChar; - var prevInInterfaceDecl = this.inInterfaceDecl; - this.inInterfaceDecl = true; - this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); - this.inInterfaceDecl = prevInInterfaceDecl; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Private; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Public; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; - } - interfaceDecl.limChar = members.limChar; - interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - return interfaceDecl; - }; - Parser.prototype.makeVarDecl = function (id, nest) { - var varDecl = new TypeScript.VarDecl(id, nest); - var currentVarList = this.topVarList(); - if(currentVarList) { - currentVarList.append(varDecl); - } - return varDecl; - }; - Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic, unnamedAmbientFunctionOk) { - var text = null; - var minChar = this.scanner.startPos; - var nameLimChar = minChar; - var isNew = false; - var isIndexer = false; - var wasAccessorID = this.prevIDTok != null; - var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - requireSignature = true; - } - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { - if(!requireSignature && !isStatic) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - text = new TypeScript.MissingIdentifier(); - } - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.New) { - if(requireSignature) { - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { - isNew = true; - } - } - if(!isNew) { - if(!requireSignature) { - this.currentToken = this.scanner.scan(); - } - text = new TypeScript.Identifier("new"); - text.minChar = this.scanner.pos - 3; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - } - } else if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { - isIndexer = true; - text = new TypeScript.Identifier("__item"); - } else if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { - this.reportParseError("Expected identifier in property declaration"); - if(this.errorRecovery) { - var eminChar = this.scanner.startPos; - var curpos = this.scanner.pos; - this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); - if(this.scanner.pos == curpos) { - this.currentToken = this.scanner.scan(); - } - var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - epd.flags |= TypeScript.ASTFlags.Error; - epd.minChar = eminChar; - epd.limChar = this.scanner.lastTokenLimChar(); - return epd; - } - } else { - if(wasAccessorID) { - text = TypeScript.Identifier.fromToken(this.prevIDTok); - text.minChar = this.scanner.lastTokenLimChar() - 3; - text.limChar = this.scanner.lastTokenLimChar(); - nameLimChar = text.limChar; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { - this.currentToken = this.scanner.scan(); - } - this.prevIDTok = null; - } else { - text = TypeScript.Identifier.fromToken(this.currentToken); - text.minChar = this.scanner.startPos; - text.limChar = this.scanner.pos; - nameLimChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - if(this.inInterfaceDecl && text) { - text.flags |= TypeScript.ASTFlags.OptionalName; - } else { - this.reportParseError("Optional properties may only be declared on interface or object types"); - } - this.currentToken = this.scanner.scan(); - } - if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { - var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; - if(isIndexer) { - ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; - } - if(!text && unnamedAmbientFunctionOk && !isIndexer) { - text = new TypeScript.MissingIdentifier(); - } - var ast = this.parseFncDecl(ers, true, requireSignature, this.currentClassDefinition || this.inInterfaceDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); - var funcDecl; - if(ast.nodeType == TypeScript.NodeType.Error) { - return ast; - } else { - funcDecl = ast; - } - if(funcDecl.name) { - funcDecl.name.minChar = minChar; - funcDecl.name.limChar = nameLimChar; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - funcDecl.fncFlags |= TypeScript.FncFlags.Private; - } - if(isStatic) { - funcDecl.fncFlags |= TypeScript.FncFlags.Static; - } - if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; - } - if(isAccessor) { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { - funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; - funcDecl.hint = "get" + funcDecl.name.actualText; - } else { - funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; - funcDecl.hint = "set" + funcDecl.name.actualText; - } - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - if(modifiers & TypeScript.Modifiers.Ambient) { - this.reportParseError("Property accessors may not be declared in ambient types"); - } - } - if(text == null || (text.isMissing() && unnamedAmbientFunctionOk && !isIndexer)) { - if(isNew) { - funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; - funcDecl.hint = "_construct"; - funcDecl.classDecl = this.currentClassDecl; - } else { - funcDecl.hint = "_call"; - funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; - } - } - return funcDecl; - } else { - var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); - varDecl.preComments = this.parseComments(); - varDecl.minChar = minChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { - var typeExpr = (varDecl.typeExpr); - if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { - typeExpr.term.preComments = varDecl.preComments; - } - } - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(requireSignature) { - this.reportParseError("context does not permit variable initializer"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.text; - funcDecl.boundToProperty = varDecl; - } else if(isAccessor) { - this.reportParseError("Accessors may only be functions"); - } - } else { - varDecl.limChar = this.scanner.pos; - } - if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Public; - } - if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { - varDecl.varFlags |= TypeScript.VarFlags.Private; - } - varDecl.varFlags |= TypeScript.VarFlags.Property; - return varDecl; - } - }; - Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { - var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); - var minChar = this.scanner.startPos; - var varDecl = null; - var declList = null; - var multivar = false; - this.currentToken = this.scanner.scan(); - var varDeclPreComments = this.parseComments(); - while(true) { - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { - this.reportParseError("Expected identifier in variable declaration"); - if(this.errorRecovery) { - varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); - varDecl.minChar = minChar; - this.skip(errorRecoverySet); - varDecl.flags |= TypeScript.ASTFlags.Error; - varDecl.limChar = this.scanner.lastTokenLimChar(); - return varDecl; - } - } - var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); - if(this.strictMode && (varDeclName.text == "eval")) { - this.reportParseError("'eval' may not name a variable in strict mode"); - } - varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); - varDecl.id.minChar = this.scanner.startPos; - varDecl.id.limChar = this.scanner.pos; - varDecl.preComments = varDeclPreComments; - if(isStatic) { - varDecl.varFlags |= TypeScript.VarFlags.Static; - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { - varDecl.varFlags |= TypeScript.VarFlags.Readonly; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - varDecl.varFlags |= TypeScript.VarFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - varDecl.varFlags |= TypeScript.VarFlags.Exported; - } - varDecl.minChar = minChar; - if(declList) { - declList.append(varDecl); - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - var prevInFncDecl = this.inFncDecl; - this.inFncDecl = false; - varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); - this.inFncDecl = prevInFncDecl; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { - this.reportParseError("Ambient variable can not have an initializer"); - } - this.currentToken = this.scanner.scan(); - varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); - varDecl.limChar = varDecl.init.limChar; - if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = varDecl.init; - funcDecl.hint = varDecl.id.actualText; - } - } else { - if(isConst) { - this.reportParseError("const declaration requires initializer"); - } - varDecl.limChar = this.scanner.pos; - } - varDecl.postComments = this.parseCommentsForLine(this.scanner.line); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - if(declList) { - declList.limChar = varDecl.limChar; - return declList; - } else { - return varDecl; - } - } - if(!multivar) { - declList = new TypeScript.ASTList(); - declList.minChar = varDecl.minChar; - declList.append(varDecl); - multivar = true; - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.startPos; - } - }; - Parser.prototype.parseMemberList = function (errorRecoverySet) { - var elements = new TypeScript.ASTList(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - return elements; - } - var idHint = null; - var memberName = null; - var memberExpr = null; - var member = null; - var minChar = this.scanner.startPos; - var isSet = false; - var skippedTokenForGetSetId = false; - var getSetTok = null; - var getSetStartPos = 0; - var getSetPos = 0; - for(; ; ) { - var accessorPattern = false; - if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { - isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; - getSetTok = this.currentToken; - getSetStartPos = this.scanner.startPos; - getSetPos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = isSet ? "set" : "get"; - idHint = idHint + this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - accessorPattern = true; - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - } else if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { - this.reportParseError("Expected identifier, string or number as accessor name"); - } else { - skippedTokenForGetSetId = true; - memberName = TypeScript.Identifier.fromToken(getSetTok); - memberName.minChar = getSetStartPos; - memberName.limChar = getSetPos; - } - } else if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { - idHint = this.currentToken.getText(); - memberName = TypeScript.Identifier.fromToken(this.currentToken); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { - idHint = this.currentToken.getText(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { - var ntok = this.currentToken; - idHint = ntok.value.toString(); - memberName = new TypeScript.StringLiteral(idHint); - memberName.minChar = this.scanner.startPos; - memberName.limChar = this.scanner.pos; - } else { - this.reportParseError("Expected identifier, string or number as member name"); - if(this.errorRecovery) { - memberName = new TypeScript.MissingIdentifier(); - memberName.minChar = this.scanner.startPos; - memberName.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); - memberName.limChar = this.scanner.lastTokenLimChar(); - } - } - if(!skippedTokenForGetSetId) { - this.currentToken = this.scanner.scan(); - } else { - skippedTokenForGetSetId = false; - } - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - memberName.flags |= TypeScript.ASTFlags.OptionalName; - this.currentToken = this.scanner.scan(); - } - if(accessorPattern) { - var args = new TypeScript.ASTList(); - this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); - var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); - if(isSet && funcDecl.returnTypeAnnotation) { - this.reportParseError("Property setters may not declare a return type"); - } - funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; - funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - funcDecl.hint = idHint; - memberExpr = funcDecl; - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { - this.currentToken = this.scanner.scan(); - memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { - this.reportParseError("Expected 'new' on array declaration in member definition"); - } - member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); - member.minChar = memberName.minChar; - if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = memberExpr; - funcDecl.hint = idHint; - } - } else { - this.reportParseError("Expected ':' in member definition"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - elements.flags |= TypeScript.ASTFlags.Error; - elements.minChar = minChar; - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - } - } - idHint = null; - elements.append(member); - member.limChar = this.scanner.lastTokenLimChar(); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } else { - this.currentToken = this.scanner.scan(); - } - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { - break; - } - } - if(member) { - elements.limChar = member.limChar; - } - elements.minChar = minChar; - return elements; - }; - Parser.prototype.parseArrayList = function (errorRecoverySet) { - var elements = null; - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - return elements; - } else { - elements = new TypeScript.ASTList(); - elements.minChar = this.scanner.startPos; - } - var arg; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { - arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - } else { - arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); - } - elements.append(arg); - if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { - break; - } - this.currentToken = this.scanner.scan(); - } - elements.limChar = this.scanner.lastTokenLimChar(); - return elements; - }; - Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { - var arrayLiteral = null; - arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); - return arrayLiteral; - }; - Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { - var ast = null; - var sawId = false; - var inNew = false; - var minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var parseAsLambda = false; - var expectlambdaRParen = false; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Number: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Any: - case TypeScript.TokenID.String: - var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); - if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { - ast = new TypeScript.TypeReference(tid, 0); - sawId = true; - } else { - ast = tid; - sawId = true; - } - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.This: - ast = new TypeScript.AST(TypeScript.NodeType.This); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.Super: - ast = new TypeScript.AST(TypeScript.NodeType.Super); - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.True: - ast = new TypeScript.AST(TypeScript.NodeType.True); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - case TypeScript.TokenID.False: - ast = new TypeScript.AST(TypeScript.NodeType.False); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - case TypeScript.TokenID.Null: - ast = new TypeScript.AST(TypeScript.NodeType.Null); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - break; - case TypeScript.TokenID.New: - this.currentToken = this.scanner.scan(); - var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); - if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { - this.reportParseError("Cannot invoke 'new' on this expression"); - } else { - ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); - ast.minChar = minChar; - limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); - inNew = true; - } - break; - case TypeScript.TokenID.Function: - minChar = this.scanner.pos; - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = minChar; - limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - break; - } - if(ast == null) { - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - var idText = this.currentToken.getText(); - ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); - sawId = true; - ast.minChar = minChar; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Question) { - ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; - } - limChar = this.scanner.lastTokenLimChar(); - } - } - if(inCast) { - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - } - if(ast == null) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: - minChar = this.scanner.pos; - var prevTokId = this.scanner.previousToken().tokenId; - this.currentToken = this.scanner.scan(); - var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; - if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - parseAsLambda = true; - expectlambdaRParen = false; - this.currentToken = this.scanner.scan(); - } else if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - parseAsLambda = true; - expectlambdaRParen = true; - } else { - ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); - limChar = this.scanner.lastTokenLimChar(); - parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); - expectlambdaRParen = true; - } - if((ast && !parseAsLambda)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); - break; - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast.isParenthesized = true; - } - break; - case TypeScript.TokenID.NumberLiteral: { - var numTok = this.currentToken; - this.currentToken = this.scanner.scan(); - ast = new TypeScript.NumberLiteral(numTok.value, numTok.text); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - case TypeScript.TokenID.StringLiteral: - ast = new TypeScript.StringLiteral(this.currentToken.getText()); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - case TypeScript.TokenID.RegularExpressionLiteral: { - var rtok = this.currentToken; - ast = new TypeScript.RegexLiteral(rtok.text); - this.currentToken = this.scanner.scan(); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - break; - } - case TypeScript.TokenID.OpenBracket: - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); - ast.minChar = minChar; - limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - case TypeScript.TokenID.OpenBrace: - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - members.minChar = minChar; - members.limChar = limChar; - break; - case TypeScript.TokenID.LessThan: - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); - this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); - (ast).castTerm = term; - break; - default: - if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { - parseAsLambda = true; - ast = this.prevExpr; - } else { - this.reportParseError("Check format of expression term"); - if(this.errorRecovery) { - var ident = new TypeScript.MissingIdentifier(); - ident.minChar = minChar; - ident.flags |= TypeScript.ASTFlags.Error; - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); - this.currentToken = this.scanner.scan(); - limChar = this.scanner.lastTokenLimChar(); - } else { - limChar = this.scanner.lastTokenLimChar(); - } - ast = ident; - } - } - } - } - if(parseAsLambda) { - if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { - ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); - ast.minChar = minChar; - limChar = this.scanner.lastTokenLimChar(); - ast.limChar = limChar; - } else if(ast) { - ast.isParenthesized = true; - } - } - if(sawId && (typeContext != TypeContext.NoTypes)) { - typeContext |= TypeContext.ArraySuffix; - } - var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); - if(postFix) { - if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { - var binExpr = postFix; - if(binExpr.operand2 == null) { - postFix = this.convertToTypeReference(postFix); - } - } - postFix.minChar = minChar; - postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); - return postFix; - } else { - return new TypeScript.AST(TypeScript.NodeType.Error); - } - }; - Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { - var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: lambdaArgs - }, expectClosingRParen); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; - if(!skipNextRParen) { - ast.flags |= TypeScript.ASTFlags.SkipNextRParen; - } - ast.limChar = this.scanner.lastTokenLimChar(); - ; - return ast; - }; - Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { - if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } - var ast = null; - var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - var canAssign = true; - var idHint = null; - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - var exprIsAnonLambda = false; - if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { - canAssign = false; - this.currentToken = this.scanner.scan(); - var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); - ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); - ast.limChar = tempExpr.limChar; - ast.minChar = minChar; - } else { - ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); - var id; - var temp; - if(ast.nodeType == TypeScript.NodeType.Name) { - id = ast; - idHint = id.actualText; - } else if(ast.nodeType == TypeScript.NodeType.Dot) { - var subsumedExpr = false; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { - if((ast).operand2.nodeType == TypeScript.NodeType.Name) { - var op2ID = ((ast).operand2); - if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { - ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); - subsumedExpr = true; - } - } - } - if(!subsumedExpr) { - temp = ast; - while(temp.nodeType == TypeScript.NodeType.Dot) { - var binExpr = temp; - temp = binExpr.operand2; - } - if(temp.nodeType == TypeScript.NodeType.Name) { - id = temp; - idHint = id.actualText; - } - } - } - if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { - canAssign = false; - var operand = ast; - ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); - ast.limChar = this.scanner.pos; - ast.minChar = operand.minChar; - this.currentToken = this.scanner.scan(); - } - } - for(; ; ) { - tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); - if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { - break; - } - if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { - break; - } - if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { - if(tokenInfo.binopPrecedence < minPrecedence) { - break; - } - if(!canAssign) { - this.reportParseError("illegal assignment"); - } - } else if(tokenInfo.binopPrecedence <= minPrecedence) { - break; - } - if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { - exprIsAnonLambda = true; - canAssign = false; - ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); - break; - } - this.currentToken = this.scanner.scan(); - canAssign = false; - if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { - if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { - exprIsAnonLambda = true; - canAssign = true; - } else { - this.prevExpr = ast; - var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - this.prevExpr = null; - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); - ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); - } - } else { - var tc = TypeContext.NoTypes; - var binExpr2; - binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); - if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = binExpr2.operand2; - funcDecl.hint = idHint; - } - binExpr2.minChar = ast.minChar; - binExpr2.limChar = this.scanner.lastTokenLimChar(); - idHint = null; - ast = binExpr2; - } - } - if(canAssign) { - ast.flags |= TypeScript.ASTFlags.Writeable; - } - if(!exprIsAnonLambda) { - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - if(preComments) { - ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; - } - ast.postComments = this.parseCommentsForLine(this.scanner.line); - } - return ast; - }; - Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { - var count = 0; - if(!ast) { - ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); - ast.isParenthesized = true; - } - ast.minChar = lhsMinChar; - ast.limChar = lhsLimChar; - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.OpenParen: - if(inNew) { - var callExpr = ast; - callExpr.arguments = this.parseArgList(errorRecoverySet); - inNew = false; - } else { - if(!allowCall) { - return ast; - } - ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); - ast.minChar = lhsMinChar; - } - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - break; - case TypeScript.TokenID.OpenBracket: - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { - if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { - this.currentToken = this.scanner.scan(); - if(ast.nodeType == TypeScript.NodeType.TypeRef) { - var typeRef = ast; - typeRef.arrayCount++; - } else { - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); - } - ast.limChar = this.scanner.pos; - break; - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); - break; - case TypeScript.TokenID.Dot: { - var name = null; - var curpos = this.scanner.pos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { - ast.flags |= TypeScript.ASTFlags.DotLHS; - name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); - name.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - } else { - this.reportParseError("Expected identifier following dot"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); - return ast; - } else { - name = new TypeScript.MissingIdentifier(); - } - } - ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - } - case TypeScript.TokenID.EqualsGreaterThan: - ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { - preProcessedLambdaArgs: ast - }, false); - (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; - ast.minChar = lhsMinChar; - ast.limChar = this.scanner.lastTokenLimChar(); - break; - default: - return ast; - } - } - }; - Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { - var minChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{'"); - if(this.errorRecovery) { - var etryNode = tryNode; - etryNode.minChar = minChar; - etryNode.limChar = this.scanner.lastTokenLimChar(); - etryNode.flags |= TypeScript.ASTFlags.Error; - return etryNode; - } - } - tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - tryNode.minChar = minChar; - tryNode.limChar = tryNode.body.limChar; - tryNode.preComments = preComments; - tryNode.postComments = this.parseComments(); - return tryNode; - }; - Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { - var catchMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - this.reportParseError("Expected identifier in catch header"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = this.scanner.pos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); - param.id.minChar = this.scanner.startPos; - param.id.limChar = this.scanner.pos; - param.minChar = param.id.minChar; - param.limChar = param.id.limChar; - this.currentToken = this.scanner.scan(); - var statementPos = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start catch body"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); - ecatch.statement.minChar = catchMinChar; - ecatch.statement.limChar = statementPos; - ecatch.minChar = this.scanner.startPos; - ecatch.limChar = this.scanner.pos; - ecatch.flags |= TypeScript.ASTFlags.Error; - return ecatch; - } - } - var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var catchNode = new TypeScript.Catch(param, catchStmt); - catchNode.statement.minChar = catchMinChar; - catchNode.statement.limChar = statementPos; - catchNode.minChar = catchMinChar; - catchNode.limChar = catchStmt.limChar; - catchNode.preComments = preComments; - catchNode.postComments = this.parseComments(); - return catchNode; - }; - Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { - var finMinChar = this.scanner.startPos; - var preComments = this.parseComments(); - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { - this.reportParseError("Expected '{' to start body of finally statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet); - var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); - efin.flags |= TypeScript.ASTFlags.Error; - efin.minChar = this.scanner.startPos; - efin.limChar = this.scanner.pos; - return efin; - } - } - var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); - var fin = new TypeScript.Finally(finBody); - fin.minChar = finMinChar; - fin.limChar = fin.body.limChar; - fin.preComments = preComments; - fin.postComments = this.parseComments(); - return fin; - }; - Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { - var tryPart = new TypeScript.Try(null); - var tryMinChar = this.scanner.startPos; - this.pushStmt(tryPart, labelList); - this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - this.popStmt(); - var tc = null; - var tf = null; - if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { - var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); - tc = new TypeScript.TryCatch(tryPart, catchPart); - tc.minChar = tryPart.minChar; - tc.limChar = catchPart.limChar; - } - if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { - if(tc == null) { - this.reportParseError("try with neither catch nor finally"); - if(this.errorRecovery) { - var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - etf.flags |= TypeScript.ASTFlags.Error; - etf.minChar = this.scanner.startPos; - etf.limChar = this.scanner.pos; - return etf; - } - return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); - } else { - return tc; - } - } else { - if(tc) { - tryPart = tc; - } - var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); - tf = new TypeScript.TryFinally(tryPart, finallyPart); - tf.minChar = tryMinChar; - tf.limChar = finallyPart.limChar; - return tf; - } - }; - Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { - var ast = null; - var labelList = null; - var astList = null; - var temp; - var modifiers = TypeScript.Modifiers.None; - var minChar = this.scanner.startPos; - var forInOk = false; - var needTerminator = false; - var fnOrVar = null; - var preComments = this.parseComments(); - function isAmbient() { - return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); - } - function mayNotBeExported() { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportError("Statement may not be exported"); - } - } - for(; ; ) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.EndOfFile: - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.pos; - break; - case TypeScript.TokenID.Function: - if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { - this.currentToken = this.scanner.scan(); - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false, true); - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - this.reportParseError("function keyword can only introduce function declaration"); - } else if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - ast = fnOrVar; - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported) || this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } else { - ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, false, modifiers, null, true); - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - needTerminator = true; - } - if(this.ambientModule) { - this.reportParseError("function declaration not permitted within ambient module"); - } - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).fncFlags |= TypeScript.FncFlags.Exported; - } - } - break; - case TypeScript.TokenID.Module: - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); - preComments = null; - } - break; - case TypeScript.TokenID.Import: - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("module not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - this.reportParseError("export keyword not permitted on import declaration"); - } - ast = this.parseImportDeclaration(errorRecoverySet, modifiers); - needTerminator = true; - } - break; - case TypeScript.TokenID.Export: - if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("'export' statements are only allowed at the global and module levels"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } - if(this.topLevel) { - this.hasTopLevelImportOrExport = true; - } - modifiers |= TypeScript.Modifiers.Exported; - this.currentToken = this.scanner.scan(); - break; - case TypeScript.TokenID.Private: - modifiers |= TypeScript.Modifiers.Private; - this.currentToken = this.scanner.scan(); - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - minChar = this.scanner.pos; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - case TypeScript.TokenID.Public: - if(this.parsingClassConstructorDefinition) { - if(!this.inferPropertiesFromThisAssignment) { - this.reportParseError("Property declarations are not permitted within constructor bodies"); - } - this.currentToken = this.scanner.scan(); - minChar = this.scanner.pos; - modifiers |= TypeScript.Modifiers.Public; - if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { - this.reportParseError("Expected 'this.' for property declaration"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - this.currentToken = this.scanner.scan(); - var id = TypeScript.Identifier.fromToken(this.currentToken); - id.minChar = this.scanner.startPos; - id.limChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); - } - } else { - if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { - this.reportParseError("'property' statements are only allowed within classes"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - this.prevIDTok = null; - } - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); - if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - } - } - break; - case TypeScript.TokenID.Declare: - if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { - this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); - } - if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { - this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); - } - modifiers |= TypeScript.Modifiers.Ambient; - this.currentToken = this.scanner.scan(); - break; - case TypeScript.TokenID.Class: - if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("class not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); - } - break; - case TypeScript.TokenID.Interface: - if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { - this.reportParseError("interface not allowed in this context"); - this.currentToken = this.scanner.scan(); - ast = new TypeScript.AST(TypeScript.NodeType.Error); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - } else { - ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); - } - break; - case TypeScript.TokenID.Var: - var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); - if(declAst.nodeType == TypeScript.NodeType.VarDecl) { - ast = declAst; - } else { - ast = new TypeScript.Block(declAst, false); - } - needTerminator = true; - break; - case TypeScript.TokenID.Static: - if(this.currentClassDecl == null) { - this.reportParseError("Statics may only be class members"); - } - mayNotBeExported(); - modifiers |= TypeScript.Modifiers.Public; - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.Get) { - this.prevIDTok = this.currentToken; - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Getter; - this.prevIDTok = null; - } - } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { - this.currentToken = this.scanner.scan(); - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("Property accessors are only available when targeting ES5 or greater"); - } - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { - modifiers |= TypeScript.Modifiers.Setter; - } - } - if(isAmbient()) { - modifiers |= TypeScript.Modifiers.Ambient; - } - fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); - var staticsList = this.topStaticsList(); - if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { - staticsList.append(fnOrVar); - } - if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { - needTerminator = true; - } - ast = fnOrVar; - break; - case TypeScript.TokenID.For: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("syntax error: for statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - forInOk = true; - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Var: - temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); - break; - case TypeScript.TokenID.Semicolon: - temp = null; - break; - default: - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); - break; - } - if(this.currentToken.tokenId == TypeScript.TokenID.In) { - if((temp == null) || (!forInOk)) { - this.reportParseError("malformed for statement"); - if(this.errorRecovery) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - ast.flags |= TypeScript.ASTFlags.Error; - } - } else { - this.currentToken = this.scanner.scan(); - var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); - forInStmt.limChar = this.scanner.pos; - forInStmt.statement.minChar = minChar; - forInStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); - this.pushStmt(forInStmt, labelList); - forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forInStmt.minChar = minChar; - ast = forInStmt; - } - } else { - var forStmt = new TypeScript.ForStatement(temp); - forStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - forStmt.cond = null; - } else { - forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { - this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - ast = forStmt; - ast.flags |= TypeScript.ASTFlags.Error; - } - } - this.currentToken = this.scanner.scan(); - if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { - forStmt.incr = null; - } else { - forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - this.pushStmt(forStmt, labelList); - forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - this.popStmt(); - forStmt.limChar = forStmt.body.limChar; - ast = forStmt; - } - break; - case TypeScript.TokenID.With: - { - if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { - this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); - } - if(this.strictMode) { - this.reportParseError("'with' statements are not available in strict mode"); - } - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'with' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); - var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var withStmt = new TypeScript.WithStatement(expr); - withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - withStmt.minChar = minChar; - withStmt.limChar = withStmt.body.limChar; - ast = withStmt; - } - break; - case TypeScript.TokenID.Switch: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'switch' statement does not take modifiers"); - } - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - switchStmt.statement.minChar = minChar; - switchStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); - var caseListMinChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); - switchStmt.defaultCase = null; - switchStmt.caseList = new TypeScript.ASTList(); - var caseStmt = null; - this.pushStmt(switchStmt, labelList); - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { - var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); - caseStmt = new TypeScript.CaseStatement(); - caseStmt.minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if(isDefault) { - switchStmt.defaultCase = caseStmt; - } else { - caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - caseStmt.colonSpan.minChar = this.scanner.startPos; - caseStmt.colonSpan.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - caseStmt.body = new TypeScript.ASTList(); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); - caseStmt.limChar = caseStmt.body.limChar; - switchStmt.caseList.append(caseStmt); - } else { - break; - } - } - switchStmt.caseList.minChar = caseListMinChar; - switchStmt.caseList.limChar = this.scanner.pos; - switchStmt.limChar = switchStmt.caseList.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - this.popStmt(); - ast = switchStmt; - break; - } - case TypeScript.TokenID.While: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'while' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); - var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - whileStmt.minChar = minChar; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(whileStmt, labelList); - whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - whileStmt.limChar = whileStmt.body.limChar; - this.popStmt(); - ast = whileStmt; - break; - } - case TypeScript.TokenID.Do: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("'do' statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var doStmt = new TypeScript.DoWhileStatement(); - doStmt.minChar = minChar; - this.pushStmt(doStmt, labelList); - doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); - this.popStmt(); - doStmt.whileAST = new TypeScript.Identifier("while"); - doStmt.whileAST.minChar = this.scanner.startPos; - this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); - doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; - this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - doStmt.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); - ast = doStmt; - if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { - this.currentToken = this.scanner.scan(); - } - break; - } - case TypeScript.TokenID.If: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("if statement does not take modifiers"); - } - minChar = this.scanner.startPos; - this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); - var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); - ifStmt.minChar = minChar; - ifStmt.statement.minChar = minChar; - ifStmt.statement.limChar = this.scanner.pos; - this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); - this.pushStmt(ifStmt, labelList); - ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.thenBod.limChar; - if(this.currentToken.tokenId == TypeScript.TokenID.Else) { - this.currentToken = this.scanner.scan(); - ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); - ifStmt.limChar = ifStmt.elseBod.limChar; - } - this.popStmt(); - ast = ifStmt; - break; - } - case TypeScript.TokenID.Try: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("try statement does not take modifiers"); - } - minChar = this.scanner.startPos; - ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); - break; - } - case TypeScript.TokenID.OpenBrace: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("block does not take modifiers"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var block = new TypeScript.Block(new TypeScript.ASTList(), true); - this.pushStmt(block, labelList); - this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); - this.popStmt(); - block.statements.minChar = minChar; - block.statements.limChar = this.scanner.pos; - block.minChar = block.statements.minChar; - block.limChar = block.statements.limChar; - this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); - ast = block; - break; - } - case TypeScript.TokenID.Semicolon: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifier can not appear here"); - } - ast = new TypeScript.AST(TypeScript.NodeType.Empty); - this.currentToken = this.scanner.scan(); - break; - case TypeScript.TokenID.Break: - case TypeScript.TokenID.Continue: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before jump statement"); - } - var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { - jump.target = this.currentToken.getText(); - this.currentToken = this.scanner.scan(); - } - this.resolveJumpTarget(jump); - ast = jump; - needTerminator = true; - break; - } - case TypeScript.TokenID.Return: { - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before return statement"); - } - if(!this.inFunction) { - this.reportParseError("return statement outside of function body"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var retStmt = new TypeScript.ReturnStatement(); - retStmt.minChar = minChar; - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } - needTerminator = true; - retStmt.limChar = this.scanner.lastTokenLimChar(); - ast = retStmt; - break; - } - case TypeScript.TokenID.Throw: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before a throw statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { - temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - } else { - this.reportParseError("throw with no target"); - temp = null; - } - ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); - ast.limChar = this.scanner.lastTokenLimChar(); - needTerminator = true; - break; - case TypeScript.TokenID.Enum: - this.currentToken = this.scanner.scan(); - ast = this.parseEnumDecl(errorRecoverySet, modifiers); - ast.minChar = minChar; - ast.limChar = this.scanner.lastTokenLimChar(); - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { - (ast).modFlags |= TypeScript.ModuleFlags.Ambient; - } - if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { - (ast).modFlags |= TypeScript.ModuleFlags.Exported; - } - break; - case TypeScript.TokenID.Debugger: - mayNotBeExported(); - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before debugger statement"); - } - minChar = this.scanner.startPos; - this.currentToken = this.scanner.scan(); - var debuggerStmt = new TypeScript.DebuggerStatement(); - debuggerStmt.minChar = minChar; - needTerminator = true; - debuggerStmt.limChar = this.scanner.lastTokenLimChar(); - ast = debuggerStmt; - break; - default: - if(modifiers != TypeScript.Modifiers.None) { - this.reportParseError("modifiers can not appear before an expression statement or label"); - } - minChar = this.scanner.startPos; - var svPos = this.scanner.pos; - temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); - if(this.scanner.pos == svPos) { - this.currentToken = this.scanner.scan(); - ast = temp; - } else if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { - if(labelList == null) { - labelList = new TypeScript.ASTList(); - } - labelList.append(new TypeScript.Label(temp)); - this.currentToken = this.scanner.scan(); - } else { - ast = temp; - needTerminator = true; - } - } - if(ast) { - break; - } - } - if(needTerminator) { - switch(this.currentToken.tokenId) { - case TypeScript.TokenID.Semicolon: - this.currentToken = this.scanner.scan(); - ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; - break; - case TypeScript.TokenID.EndOfFile: - ast.limChar = this.scanner.pos; - case TypeScript.TokenID.CloseBrace: - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - break; - default: - if(!this.scanner.lastTokenHadNewline()) { - this.reportParseError("Expected ';'"); - } else { - ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; - if(this.style_requireSemi) { - this.reportParseStyleError("no automatic semicolon"); - } - } - break; - } - } - if(labelList) { - ast = new TypeScript.LabeledStatement(labelList, ast); - } - ast.minChar = minChar; - ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); - if(preComments) { - ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; - } - if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { - this.reportParseError("statement not permitted within ambient module"); - } - ast.flags |= TypeScript.ASTFlags.IsStatement; - return ast; - }; - Parser.prototype.okAmbientModuleMember = function (ast) { - var nt = ast.nodeType; - return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).bod == null)); - }; - Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { - var directivePrologue = sourceElms; - statements.minChar = this.scanner.startPos; - var limChar = this.scanner.pos; - var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; - var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; - errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; - var oldStrictMode = this.strictMode; - this.nestingLevel++; - for(; ; ) { - if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { - statements.limChar = limChar; - if(statements.members.length == 0) { - statements.preComments = this.parseComments(); - } else { - statements.postComments = this.parseComments(); - } - this.strictMode = oldStrictMode; - this.nestingLevel--; - return; - } - var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); - if(stmt) { - stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); - statements.append(stmt); - limChar = stmt.limChar; - if(directivePrologue) { - if(stmt.nodeType == TypeScript.NodeType.QString) { - var qstring = stmt; - if(qstring.text == "\"use strict\"") { - statements.flags |= TypeScript.ASTFlags.StrictMode; - this.strictMode = true; - } else { - directivePrologue = false; - } - } else { - directivePrologue = false; - } - } - } - } - }; - Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { - var svGenTarget = TypeScript.moduleGenTarget; - try { - TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; - var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); - return new QuickParseResult(script, this.scanner.lexState); - }finally { - TypeScript.moduleGenTarget = svGenTarget; - } - }; - Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { - if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } - var _this = this; - this.fname = filename; - this.currentUnitIndex = unitIndex; - this.currentToken = null; - this.needTerminator = false; - this.inFunction = false; - this.inInterfaceDecl = false; - this.inFncDecl = false; - this.ambientModule = false; - this.ambientClass = false; - this.topLevel = true; - this.allowImportDeclaration = true; - this.prevIDTok = null; - this.statementInfoStack = new Array(); - this.hasTopLevelImportOrExport = false; - this.strictMode = false; - this.nestingLevel = 0; - this.prevExpr = null; - this.currentClassDefinition = null; - this.parsingClassConstructorDefinition = false; - this.parsingDeclareFile = false; - this.amdDependencies = []; - this.inferPropertiesFromThisAssignment = false; - this.requiresExtendsBlock = false; - this.scanner.resetComments(); - this.scanner.setErrorHandler(function (message) { - return _this.reportParseError(message); - }); - this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var leftCurlyCount = this.scanner.leftCurlyCount; - var rightCurlyCount = this.scanner.rightCurlyCount; - var minChar = this.scanner.pos; - this.currentToken = this.scanner.scan(); - this.pushDeclLists(); - var bod = new TypeScript.ASTList(); - bod.minChar = minChar; - this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); - while(true) { - this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); - if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { - break; - } - var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; - this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); - this.currentToken = this.scanner.scan(); - } - bod.limChar = this.scanner.pos; - var topLevelMod = null; - if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { - var correctedFileName = TypeScript.switchToForwardSlashes(filename); - var id = new TypeScript.Identifier(correctedFileName); - topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), null); - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; - topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; - topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; - if(this.parsingDeclareFile) { - topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; - } - topLevelMod.minChar = minChar; - topLevelMod.limChar = this.scanner.pos; - topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); - topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; - topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - topLevelMod.amdDependencies = this.amdDependencies; - bod = new TypeScript.ASTList(); - bod.minChar = topLevelMod.minChar; - bod.limChar = topLevelMod.limChar; - bod.append(topLevelMod); - } - var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); - script.bod = bod; - this.popDeclLists(); - script.minChar = minChar; - script.limChar = this.scanner.pos; - script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); - script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; - script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; - script.isDeclareFile = this.parsingDeclareFile; - script.topLevelMod = topLevelMod; - script.containsUnicodeChar = this.scanner.seenUnicodeChar; - script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; - script.requiresExtendsBlock = this.requiresExtendsBlock; - return script; - }; - return Parser; - })(); - TypeScript.Parser = Parser; - function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { - var fragment = sourceText.getText(minChar, limChar); - logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); - var quickParser = new Parser(); - quickParser.setErrorRecovery(null); - quickParser.errorCallback = errorCapture; - var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); - quickParser.currentClassDecl = quickClassDecl; - var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); - return result; - } - TypeScript.quickParse = quickParse; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var PrintContext = (function () { - function PrintContext(outfile, parser) { - this.outfile = outfile; - this.parser = parser; - this.builder = ""; - this.indent1 = " "; - this.indentStrings = []; - this.indentAmt = 0; - } - PrintContext.prototype.increaseIndent = function () { - this.indentAmt++; - }; - PrintContext.prototype.decreaseIndent = function () { - this.indentAmt--; - }; - PrintContext.prototype.startLine = function () { - if(this.builder.length > 0) { - TypeScript.CompilerDiagnostics.Alert(this.builder); - } - var indentString = this.indentStrings[this.indentAmt]; - if(indentString === undefined) { - indentString = ""; - for(var i = 0; i < this.indentAmt; i++) { - indentString += this.indent1; - } - this.indentStrings[this.indentAmt] = indentString; - } - this.builder += indentString; - }; - PrintContext.prototype.write = function (s) { - this.builder += s; - }; - PrintContext.prototype.writeLine = function (s) { - this.builder += s; - this.outfile.WriteLine(this.builder); - this.builder = ""; - }; - return PrintContext; - })(); - TypeScript.PrintContext = PrintContext; - function prePrintAST(ast, parent, walker) { - var pc = walker.state; - ast.print(pc); - pc.increaseIndent(); - return ast; - } - TypeScript.prePrintAST = prePrintAST; - function postPrintAST(ast, parent, walker) { - var pc = walker.state; - pc.decreaseIndent(); - return ast; - } - TypeScript.postPrintAST = postPrintAST; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - TypeScript.LexEOF = (-1); - TypeScript.LexCodeNWL = 0x0A; - TypeScript.LexCodeRET = 0x0D; - TypeScript.LexCodeLS = 0x2028; - TypeScript.LexCodePS = 0x2029; - TypeScript.LexCodeTAB = 0x09; - TypeScript.LexCodeVTAB = 0x0B; - TypeScript.LexCode_e = 'e'.charCodeAt(0); - TypeScript.LexCode_E = 'E'.charCodeAt(0); - TypeScript.LexCode_x = 'x'.charCodeAt(0); - TypeScript.LexCode_X = 'X'.charCodeAt(0); - TypeScript.LexCode_a = 'a'.charCodeAt(0); - TypeScript.LexCode_A = 'A'.charCodeAt(0); - TypeScript.LexCode_f = 'f'.charCodeAt(0); - TypeScript.LexCode_F = 'F'.charCodeAt(0); - TypeScript.LexCode_g = 'g'.charCodeAt(0); - TypeScript.LexCode_m = 'm'.charCodeAt(0); - TypeScript.LexCode_i = 'i'.charCodeAt(0); - TypeScript.LexCode_u = 'u'.charCodeAt(0); - TypeScript.LexCode_0 = '0'.charCodeAt(0); - TypeScript.LexCode_9 = '9'.charCodeAt(0); - TypeScript.LexCode_8 = '8'.charCodeAt(0); - TypeScript.LexCode_7 = '7'.charCodeAt(0); - TypeScript.LexCodeBSL = '\\'.charCodeAt(0); - TypeScript.LexCodeSHP = '#'.charCodeAt(0); - TypeScript.LexCodeBNG = '!'.charCodeAt(0); - TypeScript.LexCodeQUO = '"'.charCodeAt(0); - TypeScript.LexCodeAPO = '\''.charCodeAt(0); - TypeScript.LexCodePCT = '%'.charCodeAt(0); - TypeScript.LexCodeAMP = '&'.charCodeAt(0); - TypeScript.LexCodeLPR = '('.charCodeAt(0); - TypeScript.LexCodeRPR = ')'.charCodeAt(0); - TypeScript.LexCodePLS = '+'.charCodeAt(0); - TypeScript.LexCodeMIN = '-'.charCodeAt(0); - TypeScript.LexCodeMUL = '*'.charCodeAt(0); - TypeScript.LexCodeSLH = '/'.charCodeAt(0); - TypeScript.LexCodeXOR = '^'.charCodeAt(0); - TypeScript.LexCodeCMA = ','.charCodeAt(0); - TypeScript.LexCodeDOT = '.'.charCodeAt(0); - TypeScript.LexCodeLT = '<'.charCodeAt(0); - TypeScript.LexCodeEQ = '='.charCodeAt(0); - TypeScript.LexCodeGT = '>'.charCodeAt(0); - TypeScript.LexCodeQUE = '?'.charCodeAt(0); - TypeScript.LexCodeLBR = '['.charCodeAt(0); - TypeScript.LexCodeRBR = ']'.charCodeAt(0); - TypeScript.LexCodeUSC = '_'.charCodeAt(0); - TypeScript.LexCodeLC = '{'.charCodeAt(0); - TypeScript.LexCodeRC = '}'.charCodeAt(0); - TypeScript.LexCodeBAR = '|'.charCodeAt(0); - TypeScript.LexCodeTIL = '~'.charCodeAt(0); - TypeScript.LexCodeCOL = ':'.charCodeAt(0); - TypeScript.LexCodeSMC = ';'.charCodeAt(0); - TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); - TypeScript.LexCodeDollar = '$'.charCodeAt(0); - TypeScript.LexCodeSpace = 32; - TypeScript.LexCodeAtSign = '@'.charCodeAt(0); - TypeScript.LexCodeASCIIChars = 128; - TypeScript.LexKeywordTable = undefined; - var autoToken = new Array(TypeScript.LexCodeASCIIChars); - var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); - var unicodeES3IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 543, - 546, - 563, - 592, - 685, - 688, - 696, - 699, - 705, - 720, - 721, - 736, - 740, - 750, - 750, - 890, - 890, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 974, - 976, - 983, - 986, - 1011, - 1024, - 1153, - 1164, - 1220, - 1223, - 1224, - 1227, - 1228, - 1232, - 1269, - 1272, - 1273, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1569, - 1594, - 1600, - 1610, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1786, - 1788, - 1808, - 1808, - 1810, - 1836, - 1920, - 1957, - 2309, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2699, - 2701, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2784, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2870, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 2997, - 2999, - 3001, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3294, - 3294, - 3296, - 3297, - 3333, - 3340, - 3342, - 3344, - 3346, - 3368, - 3370, - 3385, - 3424, - 3425, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3805, - 3840, - 3840, - 3904, - 3911, - 3913, - 3946, - 3976, - 3979, - 4096, - 4129, - 4131, - 4135, - 4137, - 4138, - 4176, - 4181, - 4256, - 4293, - 4304, - 4342, - 4352, - 4441, - 4447, - 4514, - 4520, - 4601, - 4608, - 4614, - 4616, - 4678, - 4680, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4742, - 4744, - 4744, - 4746, - 4749, - 4752, - 4782, - 4784, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4814, - 4816, - 4822, - 4824, - 4846, - 4848, - 4878, - 4880, - 4880, - 4882, - 4885, - 4888, - 4894, - 4896, - 4934, - 4936, - 4954, - 5024, - 5108, - 5121, - 5740, - 5743, - 5750, - 5761, - 5786, - 5792, - 5866, - 6016, - 6067, - 6176, - 6263, - 6272, - 6312, - 7680, - 7835, - 7840, - 7929, - 7936, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8319, - 8319, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8497, - 8499, - 8505, - 8544, - 8579, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12346, - 12353, - 12436, - 12445, - 12446, - 12449, - 12538, - 12540, - 12542, - 12549, - 12588, - 12593, - 12686, - 12704, - 12727, - 13312, - 19893, - 19968, - 40869, - 40960, - 42124, - 44032, - 55203, - 63744, - 64045, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65138, - 65140, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500, - - ]; - var unicodeES3IdCont = [ - 768, - 846, - 864, - 866, - 1155, - 1158, - 1425, - 1441, - 1443, - 1465, - 1467, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1476, - 1611, - 1621, - 1632, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 2305, - 2307, - 2364, - 2364, - 2366, - 2381, - 2385, - 2388, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2562, - 2562, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2662, - 2673, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2883, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2918, - 2927, - 2946, - 2947, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3047, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3174, - 3183, - 3202, - 3203, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3302, - 3311, - 3330, - 3331, - 3390, - 3395, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3984, - 3991, - 3993, - 4028, - 4038, - 4038, - 4140, - 4146, - 4150, - 4153, - 4160, - 4169, - 4182, - 4185, - 4969, - 4977, - 6068, - 6099, - 6112, - 6121, - 6160, - 6169, - 6313, - 6313, - 8255, - 8256, - 8400, - 8412, - 8417, - 8417, - 12330, - 12335, - 12441, - 12442, - 12539, - 12539, - 64286, - 64286, - 65056, - 65059, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343, - 65381, - 65381, - - ]; - var unicodeES5IdStart = [ - 170, - 170, - 181, - 181, - 186, - 186, - 192, - 214, - 216, - 246, - 248, - 705, - 710, - 721, - 736, - 740, - 748, - 748, - 750, - 750, - 880, - 884, - 886, - 887, - 890, - 893, - 902, - 902, - 904, - 906, - 908, - 908, - 910, - 929, - 931, - 1013, - 1015, - 1153, - 1162, - 1319, - 1329, - 1366, - 1369, - 1369, - 1377, - 1415, - 1488, - 1514, - 1520, - 1522, - 1568, - 1610, - 1646, - 1647, - 1649, - 1747, - 1749, - 1749, - 1765, - 1766, - 1774, - 1775, - 1786, - 1788, - 1791, - 1791, - 1808, - 1808, - 1810, - 1839, - 1869, - 1957, - 1969, - 1969, - 1994, - 2026, - 2036, - 2037, - 2042, - 2042, - 2048, - 2069, - 2074, - 2074, - 2084, - 2084, - 2088, - 2088, - 2112, - 2136, - 2208, - 2208, - 2210, - 2220, - 2308, - 2361, - 2365, - 2365, - 2384, - 2384, - 2392, - 2401, - 2417, - 2423, - 2425, - 2431, - 2437, - 2444, - 2447, - 2448, - 2451, - 2472, - 2474, - 2480, - 2482, - 2482, - 2486, - 2489, - 2493, - 2493, - 2510, - 2510, - 2524, - 2525, - 2527, - 2529, - 2544, - 2545, - 2565, - 2570, - 2575, - 2576, - 2579, - 2600, - 2602, - 2608, - 2610, - 2611, - 2613, - 2614, - 2616, - 2617, - 2649, - 2652, - 2654, - 2654, - 2674, - 2676, - 2693, - 2701, - 2703, - 2705, - 2707, - 2728, - 2730, - 2736, - 2738, - 2739, - 2741, - 2745, - 2749, - 2749, - 2768, - 2768, - 2784, - 2785, - 2821, - 2828, - 2831, - 2832, - 2835, - 2856, - 2858, - 2864, - 2866, - 2867, - 2869, - 2873, - 2877, - 2877, - 2908, - 2909, - 2911, - 2913, - 2929, - 2929, - 2947, - 2947, - 2949, - 2954, - 2958, - 2960, - 2962, - 2965, - 2969, - 2970, - 2972, - 2972, - 2974, - 2975, - 2979, - 2980, - 2984, - 2986, - 2990, - 3001, - 3024, - 3024, - 3077, - 3084, - 3086, - 3088, - 3090, - 3112, - 3114, - 3123, - 3125, - 3129, - 3133, - 3133, - 3160, - 3161, - 3168, - 3169, - 3205, - 3212, - 3214, - 3216, - 3218, - 3240, - 3242, - 3251, - 3253, - 3257, - 3261, - 3261, - 3294, - 3294, - 3296, - 3297, - 3313, - 3314, - 3333, - 3340, - 3342, - 3344, - 3346, - 3386, - 3389, - 3389, - 3406, - 3406, - 3424, - 3425, - 3450, - 3455, - 3461, - 3478, - 3482, - 3505, - 3507, - 3515, - 3517, - 3517, - 3520, - 3526, - 3585, - 3632, - 3634, - 3635, - 3648, - 3654, - 3713, - 3714, - 3716, - 3716, - 3719, - 3720, - 3722, - 3722, - 3725, - 3725, - 3732, - 3735, - 3737, - 3743, - 3745, - 3747, - 3749, - 3749, - 3751, - 3751, - 3754, - 3755, - 3757, - 3760, - 3762, - 3763, - 3773, - 3773, - 3776, - 3780, - 3782, - 3782, - 3804, - 3807, - 3840, - 3840, - 3904, - 3911, - 3913, - 3948, - 3976, - 3980, - 4096, - 4138, - 4159, - 4159, - 4176, - 4181, - 4186, - 4189, - 4193, - 4193, - 4197, - 4198, - 4206, - 4208, - 4213, - 4225, - 4238, - 4238, - 4256, - 4293, - 4295, - 4295, - 4301, - 4301, - 4304, - 4346, - 4348, - 4680, - 4682, - 4685, - 4688, - 4694, - 4696, - 4696, - 4698, - 4701, - 4704, - 4744, - 4746, - 4749, - 4752, - 4784, - 4786, - 4789, - 4792, - 4798, - 4800, - 4800, - 4802, - 4805, - 4808, - 4822, - 4824, - 4880, - 4882, - 4885, - 4888, - 4954, - 4992, - 5007, - 5024, - 5108, - 5121, - 5740, - 5743, - 5759, - 5761, - 5786, - 5792, - 5866, - 5870, - 5872, - 5888, - 5900, - 5902, - 5905, - 5920, - 5937, - 5952, - 5969, - 5984, - 5996, - 5998, - 6000, - 6016, - 6067, - 6103, - 6103, - 6108, - 6108, - 6176, - 6263, - 6272, - 6312, - 6314, - 6314, - 6320, - 6389, - 6400, - 6428, - 6480, - 6509, - 6512, - 6516, - 6528, - 6571, - 6593, - 6599, - 6656, - 6678, - 6688, - 6740, - 6823, - 6823, - 6917, - 6963, - 6981, - 6987, - 7043, - 7072, - 7086, - 7087, - 7098, - 7141, - 7168, - 7203, - 7245, - 7247, - 7258, - 7293, - 7401, - 7404, - 7406, - 7409, - 7413, - 7414, - 7424, - 7615, - 7680, - 7957, - 7960, - 7965, - 7968, - 8005, - 8008, - 8013, - 8016, - 8023, - 8025, - 8025, - 8027, - 8027, - 8029, - 8029, - 8031, - 8061, - 8064, - 8116, - 8118, - 8124, - 8126, - 8126, - 8130, - 8132, - 8134, - 8140, - 8144, - 8147, - 8150, - 8155, - 8160, - 8172, - 8178, - 8180, - 8182, - 8188, - 8305, - 8305, - 8319, - 8319, - 8336, - 8348, - 8450, - 8450, - 8455, - 8455, - 8458, - 8467, - 8469, - 8469, - 8473, - 8477, - 8484, - 8484, - 8486, - 8486, - 8488, - 8488, - 8490, - 8493, - 8495, - 8505, - 8508, - 8511, - 8517, - 8521, - 8526, - 8526, - 8544, - 8584, - 11264, - 11310, - 11312, - 11358, - 11360, - 11492, - 11499, - 11502, - 11506, - 11507, - 11520, - 11557, - 11559, - 11559, - 11565, - 11565, - 11568, - 11623, - 11631, - 11631, - 11648, - 11670, - 11680, - 11686, - 11688, - 11694, - 11696, - 11702, - 11704, - 11710, - 11712, - 11718, - 11720, - 11726, - 11728, - 11734, - 11736, - 11742, - 11823, - 11823, - 12293, - 12295, - 12321, - 12329, - 12337, - 12341, - 12344, - 12348, - 12353, - 12438, - 12445, - 12447, - 12449, - 12538, - 12540, - 12543, - 12549, - 12589, - 12593, - 12686, - 12704, - 12730, - 12784, - 12799, - 13312, - 19893, - 19968, - 40908, - 40960, - 42124, - 42192, - 42237, - 42240, - 42508, - 42512, - 42527, - 42538, - 42539, - 42560, - 42606, - 42623, - 42647, - 42656, - 42735, - 42775, - 42783, - 42786, - 42888, - 42891, - 42894, - 42896, - 42899, - 42912, - 42922, - 43000, - 43009, - 43011, - 43013, - 43015, - 43018, - 43020, - 43042, - 43072, - 43123, - 43138, - 43187, - 43250, - 43255, - 43259, - 43259, - 43274, - 43301, - 43312, - 43334, - 43360, - 43388, - 43396, - 43442, - 43471, - 43471, - 43520, - 43560, - 43584, - 43586, - 43588, - 43595, - 43616, - 43638, - 43642, - 43642, - 43648, - 43695, - 43697, - 43697, - 43701, - 43702, - 43705, - 43709, - 43712, - 43712, - 43714, - 43714, - 43739, - 43741, - 43744, - 43754, - 43762, - 43764, - 43777, - 43782, - 43785, - 43790, - 43793, - 43798, - 43808, - 43814, - 43816, - 43822, - 43968, - 44002, - 44032, - 55203, - 55216, - 55238, - 55243, - 55291, - 63744, - 64109, - 64112, - 64217, - 64256, - 64262, - 64275, - 64279, - 64285, - 64285, - 64287, - 64296, - 64298, - 64310, - 64312, - 64316, - 64318, - 64318, - 64320, - 64321, - 64323, - 64324, - 64326, - 64433, - 64467, - 64829, - 64848, - 64911, - 64914, - 64967, - 65008, - 65019, - 65136, - 65140, - 65142, - 65276, - 65313, - 65338, - 65345, - 65370, - 65382, - 65470, - 65474, - 65479, - 65482, - 65487, - 65490, - 65495, - 65498, - 65500, - - ]; - var unicodeES5IdCont = [ - 768, - 879, - 1155, - 1159, - 1425, - 1469, - 1471, - 1471, - 1473, - 1474, - 1476, - 1477, - 1479, - 1479, - 1552, - 1562, - 1611, - 1641, - 1648, - 1648, - 1750, - 1756, - 1759, - 1764, - 1767, - 1768, - 1770, - 1773, - 1776, - 1785, - 1809, - 1809, - 1840, - 1866, - 1958, - 1968, - 1984, - 1993, - 2027, - 2035, - 2070, - 2073, - 2075, - 2083, - 2085, - 2087, - 2089, - 2093, - 2137, - 2139, - 2276, - 2302, - 2304, - 2307, - 2362, - 2364, - 2366, - 2383, - 2385, - 2391, - 2402, - 2403, - 2406, - 2415, - 2433, - 2435, - 2492, - 2492, - 2494, - 2500, - 2503, - 2504, - 2507, - 2509, - 2519, - 2519, - 2530, - 2531, - 2534, - 2543, - 2561, - 2563, - 2620, - 2620, - 2622, - 2626, - 2631, - 2632, - 2635, - 2637, - 2641, - 2641, - 2662, - 2673, - 2677, - 2677, - 2689, - 2691, - 2748, - 2748, - 2750, - 2757, - 2759, - 2761, - 2763, - 2765, - 2786, - 2787, - 2790, - 2799, - 2817, - 2819, - 2876, - 2876, - 2878, - 2884, - 2887, - 2888, - 2891, - 2893, - 2902, - 2903, - 2914, - 2915, - 2918, - 2927, - 2946, - 2946, - 3006, - 3010, - 3014, - 3016, - 3018, - 3021, - 3031, - 3031, - 3046, - 3055, - 3073, - 3075, - 3134, - 3140, - 3142, - 3144, - 3146, - 3149, - 3157, - 3158, - 3170, - 3171, - 3174, - 3183, - 3202, - 3203, - 3260, - 3260, - 3262, - 3268, - 3270, - 3272, - 3274, - 3277, - 3285, - 3286, - 3298, - 3299, - 3302, - 3311, - 3330, - 3331, - 3390, - 3396, - 3398, - 3400, - 3402, - 3405, - 3415, - 3415, - 3426, - 3427, - 3430, - 3439, - 3458, - 3459, - 3530, - 3530, - 3535, - 3540, - 3542, - 3542, - 3544, - 3551, - 3570, - 3571, - 3633, - 3633, - 3636, - 3642, - 3655, - 3662, - 3664, - 3673, - 3761, - 3761, - 3764, - 3769, - 3771, - 3772, - 3784, - 3789, - 3792, - 3801, - 3864, - 3865, - 3872, - 3881, - 3893, - 3893, - 3895, - 3895, - 3897, - 3897, - 3902, - 3903, - 3953, - 3972, - 3974, - 3975, - 3981, - 3991, - 3993, - 4028, - 4038, - 4038, - 4139, - 4158, - 4160, - 4169, - 4182, - 4185, - 4190, - 4192, - 4194, - 4196, - 4199, - 4205, - 4209, - 4212, - 4226, - 4237, - 4239, - 4253, - 4957, - 4959, - 5906, - 5908, - 5938, - 5940, - 5970, - 5971, - 6002, - 6003, - 6068, - 6099, - 6109, - 6109, - 6112, - 6121, - 6155, - 6157, - 6160, - 6169, - 6313, - 6313, - 6432, - 6443, - 6448, - 6459, - 6470, - 6479, - 6576, - 6592, - 6600, - 6601, - 6608, - 6617, - 6679, - 6683, - 6741, - 6750, - 6752, - 6780, - 6783, - 6793, - 6800, - 6809, - 6912, - 6916, - 6964, - 6980, - 6992, - 7001, - 7019, - 7027, - 7040, - 7042, - 7073, - 7085, - 7088, - 7097, - 7142, - 7155, - 7204, - 7223, - 7232, - 7241, - 7248, - 7257, - 7376, - 7378, - 7380, - 7400, - 7405, - 7405, - 7410, - 7412, - 7616, - 7654, - 7676, - 7679, - 8204, - 8205, - 8255, - 8256, - 8276, - 8276, - 8400, - 8412, - 8417, - 8417, - 8421, - 8432, - 11503, - 11505, - 11647, - 11647, - 11744, - 11775, - 12330, - 12335, - 12441, - 12442, - 42528, - 42537, - 42607, - 42607, - 42612, - 42621, - 42655, - 42655, - 42736, - 42737, - 43010, - 43010, - 43014, - 43014, - 43019, - 43019, - 43043, - 43047, - 43136, - 43137, - 43188, - 43204, - 43216, - 43225, - 43232, - 43249, - 43264, - 43273, - 43302, - 43309, - 43335, - 43347, - 43392, - 43395, - 43443, - 43456, - 43472, - 43481, - 43561, - 43574, - 43587, - 43587, - 43596, - 43597, - 43600, - 43609, - 43643, - 43643, - 43696, - 43696, - 43698, - 43700, - 43703, - 43704, - 43710, - 43711, - 43713, - 43713, - 43755, - 43759, - 43765, - 43766, - 44003, - 44010, - 44012, - 44013, - 44016, - 44025, - 64286, - 64286, - 65024, - 65039, - 65056, - 65062, - 65075, - 65076, - 65101, - 65103, - 65296, - 65305, - 65343, - 65343, - - ]; - function LexLookUpUnicodeMap(code, map) { - var lo = 0; - var hi = map.length; - var mid; - while(lo + 1 < hi) { - mid = lo + (hi - lo) / 2; - mid -= mid % 2; - if(map[mid] <= code && code <= map[mid + 1]) { - return true; - } - if(code < map[mid]) { - hi = mid; - } else { - lo = mid + 2; - } - } - return false; - } - TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; - function LexIsUnicodeDigit(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdCont); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdCont); - } - } - TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; - function LexIsUnicodeIdStart(code) { - if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { - return LexLookUpUnicodeMap(code, unicodeES3IdStart); - } else { - return LexLookUpUnicodeMap(code, unicodeES5IdStart); - } - } - TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; - function LexInitialize() { - TypeScript.initializeStaticTokens(); - autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; - autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; - autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; - autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; - autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; - autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; - autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; - autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; - autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; - autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; - TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); - for(var i in (TypeScript.TokenID)._map) { - if((i) <= TypeScript.TokenID.LimKeyword) { - TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); - } - } - for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { - if(LexIsIdentifierStartChar(j)) { - lexIdStartTable[j] = true; - } else { - lexIdStartTable[j] = false; - } - } - } - TypeScript.LexInitialize = LexInitialize; - function LexAdjustIndent(code, indentAmt) { - if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { - return indentAmt + 1; - } else if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { - return indentAmt - 1; - } else { - return indentAmt; - } - } - TypeScript.LexAdjustIndent = LexAdjustIndent; - function LexIsIdentifierStartChar(code) { - return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); - } - TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; - function LexIsDigit(code) { - return ((code >= 48) && (code <= 57)); - } - TypeScript.LexIsDigit = LexIsDigit; - function LexIsIdentifierChar(code) { - return lexIdStartTable[code] || LexIsDigit(code); - } - TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; - function LexMatchingOpen(code) { - if(code == TypeScript.LexCodeRBR) { - return TypeScript.LexCodeLBR; - } else if(code == TypeScript.LexCodeRC) { - return TypeScript.LexCodeLC; - } else if(code == TypeScript.LexCodeRPR) { - return TypeScript.LexCodeLPR; - } else { - return 0; - } - } - TypeScript.LexMatchingOpen = LexMatchingOpen; - (function (NumberScanState) { - NumberScanState._map = []; - NumberScanState._map[0] = "Start"; - NumberScanState.Start = 0; - NumberScanState._map[1] = "InFraction"; - NumberScanState.InFraction = 1; - NumberScanState._map[2] = "InEmptyFraction"; - NumberScanState.InEmptyFraction = 2; - NumberScanState._map[3] = "InExponent"; - NumberScanState.InExponent = 3; - })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); - var NumberScanState = TypeScript.NumberScanState; - (function (LexState) { - LexState._map = []; - LexState._map[0] = "Start"; - LexState.Start = 0; - LexState._map[1] = "InMultilineComment"; - LexState.InMultilineComment = 1; - LexState._map[2] = "InMultilineSingleQuoteString"; - LexState.InMultilineSingleQuoteString = 2; - LexState._map[3] = "InMultilineDoubleQuoteString"; - LexState.InMultilineDoubleQuoteString = 3; - })(TypeScript.LexState || (TypeScript.LexState = {})); - var LexState = TypeScript.LexState; - (function (LexMode) { - LexMode._map = []; - LexMode._map[0] = "Line"; - LexMode.Line = 0; - LexMode._map[1] = "File"; - LexMode.File = 1; - })(TypeScript.LexMode || (TypeScript.LexMode = {})); - var LexMode = TypeScript.LexMode; - (function (CommentStyle) { - CommentStyle._map = []; - CommentStyle._map[0] = "Line"; - CommentStyle.Line = 0; - CommentStyle._map[1] = "Block"; - CommentStyle.Block = 1; - })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); - var CommentStyle = TypeScript.CommentStyle; - var StringSourceText = (function () { - function StringSourceText(text) { - this.text = text; - } - StringSourceText.prototype.getText = function (start, end) { - return this.text.substring(start, end); - }; - StringSourceText.prototype.getLength = function () { - return this.text.length; - }; - return StringSourceText; - })(); - TypeScript.StringSourceText = StringSourceText; - var SourceTextSegment = (function () { - function SourceTextSegment(segmentStart, segmentEnd, segment) { - this.segmentStart = segmentStart; - this.segmentEnd = segmentEnd; - this.segment = segment; - } - SourceTextSegment.prototype.charCodeAt = function (index) { - return this.segment.charCodeAt(index - this.segmentStart); - }; - SourceTextSegment.prototype.substring = function (start, end) { - return this.segment.substring(start - this.segmentStart, end - this.segmentStart); - }; - return SourceTextSegment; - })(); - TypeScript.SourceTextSegment = SourceTextSegment; - var AggerateSourceTextSegment = (function () { - function AggerateSourceTextSegment(seg1, seg2) { - this.seg1 = seg1; - this.seg2 = seg2; - } - AggerateSourceTextSegment.prototype.charCodeAt = function (index) { - if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { - return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); - } - return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); - }; - AggerateSourceTextSegment.prototype.substring = function (start, end) { - if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { - return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); - } - return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); - }; - return AggerateSourceTextSegment; - })(); - TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; - var ScannerTextStream = (function () { - function ScannerTextStream(sourceText) { - this.sourceText = sourceText; - this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); - this.len = this.sourceText.getLength(); - } - ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); - ScannerTextStream.prototype.max = function (a, b) { - return a >= b ? a : b; - }; - ScannerTextStream.prototype.min = function (a, b) { - return a <= b ? a : b; - }; - ScannerTextStream.prototype.fetchSegment = function (start, end) { - if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg.seg1; - } - if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { - return this.agg; - } - var prev = this.agg.seg1; - var s = prev.segmentEnd; - var e = TypeScript.max(s + 512, end); - e = TypeScript.min(e, this.len); - var src = this.sourceText.getText(s, e); - var newSeg = new SourceTextSegment(s, e, src); - this.agg.seg2 = prev; - this.agg.seg1 = newSeg; - return this.agg; - }; - ScannerTextStream.prototype.charCodeAt = function (index) { - return this.fetchSegment(index, index + 1).charCodeAt(index); - }; - ScannerTextStream.prototype.substring = function (start, end) { - return this.fetchSegment(start, end).substring(start, end); - }; - return ScannerTextStream; - })(); - TypeScript.ScannerTextStream = ScannerTextStream; - var SavedTokens = (function () { - function SavedTokens() { - this.prevToken = null; - this.curSavedToken = null; - this.prevSavedToken = null; - this.prevToken = null; - this.currentToken = 0; - this.tokens = new Array(); - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.lexState = LexState.Start; - this.commentStack = new Array(); - this.lineMap = []; - } - SavedTokens.prototype.previousToken = function () { - return this.prevToken; - }; - SavedTokens.prototype.addToken = function (tok, scanner) { - this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); - }; - SavedTokens.prototype.scan = function () { - this.startLine = this.line; - this.startPos = this.col; - if(this.currentTokenIndex == this.currentTokens.length) { - if(this.line < this.lineMap.length) { - this.line++; - this.col = 0; - this.currentTokenIndex = 0; - this.currentTokens = this.tokensByLine[this.line]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(this.currentTokenIndex < this.currentTokens.length) { - this.prevToken = this.curSavedToken.tok; - this.prevSavedToken = this.curSavedToken; - this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; - var curToken = this.curSavedToken.tok; - this.pos = this.curSavedToken.limChar; - this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); - this.startPos = this.curSavedToken.minChar; - this.prevLine = this.line; - return curToken; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - }; - SavedTokens.prototype.lastTokenLimChar = function () { - if(this.prevSavedToken !== null) { - return this.prevSavedToken.limChar; - } else { - return 0; - } - }; - SavedTokens.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - SavedTokens.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - SavedTokens.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - SavedTokens.prototype.resetComments = function () { - this.commentStack = []; - }; - SavedTokens.prototype.setSourceText = function (newSrc, textMode) { - }; - SavedTokens.prototype.setErrorHandler = function (reportError) { - }; - SavedTokens.prototype.getLookAheadToken = function () { - throw new Error("Invalid operation."); - }; - return SavedTokens; - })(); - TypeScript.SavedTokens = SavedTokens; - var Scanner = (function () { - function Scanner() { - this.prevLine = 1; - this.line = 1; - this.col = 0; - this.pos = 0; - this.startPos = 0; - this.len = 0; - this.lineMap = []; - this.ch = TypeScript.LexEOF; - this.lexState = LexState.Start; - this.mode = LexMode.File; - this.scanComments = true; - this.interveningWhitespace = false; - this.interveningWhitespacePos = 0; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.commentStack = new Array(); - this.saveScan = null; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - this.startCol = this.col; - this.startLine = this.line; - this.lineMap[1] = 0; - if(!TypeScript.LexKeywordTable) { - LexInitialize(); - } - } - Scanner.prototype.previousToken = function () { - return this.prevTok; - }; - Scanner.prototype.setSourceText = function (newSrc, textMode) { - this.mode = textMode; - this.scanComments = (this.mode === LexMode.Line); - this.pos = 0; - this.interveningWhitespacePos = 0; - this.startPos = 0; - this.line = 1; - this.col = 0; - this.startCol = this.col; - this.startLine = this.line; - this.len = 0; - this.src = newSrc.getText(0, newSrc.getLength()); - this.len = this.src.length; - this.lineMap = []; - this.lineMap[1] = 0; - this.commentStack = []; - this.leftCurlyCount = 0; - this.rightCurlyCount = 0; - this.seenUnicodeChar = false; - this.seenUnicodeCharInComment = false; - }; - Scanner.prototype.setErrorHandler = function (reportError) { - this.reportError = reportError; - }; - Scanner.prototype.setText = function (newSrc, textMode) { - this.setSourceText(new StringSourceText(newSrc), textMode); - }; - Scanner.prototype.setScanComments = function (value) { - this.scanComments = value; - }; - Scanner.prototype.tokenStart = function () { - this.startPos = this.pos; - this.startLine = this.line; - this.startCol = this.col; - this.interveningWhitespace = false; - }; - Scanner.prototype.peekChar = function () { - if(this.pos < this.len) { - return this.src.charCodeAt(this.pos); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.peekCharAt = function (index) { - if(index < this.len) { - return this.src.charCodeAt(index); - } else { - return TypeScript.LexEOF; - } - }; - Scanner.prototype.IsHexDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.IsOctalDigit = function (c) { - return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); - }; - Scanner.prototype.scanHexDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseInt(text), text); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanOctalDigits = function () { - var atLeastOneDigit = false; - for(; ; ) { - if(this.IsOctalDigit(this.ch)) { - this.nextChar(); - atLeastOneDigit = true; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseInt(text), text); - } else { - return null; - } - } - } - }; - Scanner.prototype.scanDecimalNumber = function (state) { - var atLeastOneDigit = false; - var svPos = this.pos; - var svCol = this.col; - for(; ; ) { - if(LexIsDigit(this.ch)) { - atLeastOneDigit = true; - if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { - state = NumberScanState.InFraction; - } - this.nextChar(); - } else if(this.ch == TypeScript.LexCodeDOT) { - if(state == NumberScanState.Start) { - this.nextChar(); - state = NumberScanState.InEmptyFraction; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } else if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { - if(state == NumberScanState.Start) { - if(atLeastOneDigit) { - atLeastOneDigit = false; - this.nextChar(); - state = NumberScanState.InExponent; - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { - this.nextChar(); - state = NumberScanState.InExponent; - atLeastOneDigit = false; - } else { - if(atLeastOneDigit) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } - } else if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { - if(state == NumberScanState.InExponent) { - if(!atLeastOneDigit) { - this.nextChar(); - } else { - this.pos = svPos; - this.col = svCol; - return null; - } - } else if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } - } - } else { - if(!atLeastOneDigit) { - this.pos = svPos; - this.col = svCol; - return null; - } else { - var text = this.src.substring(this.startPos, this.pos); - return new TypeScript.NumberLiteralToken(parseFloat(text), text); - } - } - } - }; - Scanner.prototype.scanNumber = function () { - if(this.peekChar() == TypeScript.LexCode_0) { - switch(this.peekCharAt(this.pos + 1)) { - case TypeScript.LexCode_x: - case TypeScript.LexCode_X: - this.advanceChar(2); - return this.scanHexDigits(); - case TypeScript.LexCode_8: - case TypeScript.LexCode_9: - case TypeScript.LexCodeDOT: - return this.scanDecimalNumber(NumberScanState.Start); - default: - return this.scanOctalDigits(); - } - } else { - return this.scanDecimalNumber(NumberScanState.Start); - } - }; - Scanner.prototype.scanFraction = function () { - return this.scanDecimalNumber(NumberScanState.InFraction); - }; - Scanner.prototype.newLine = function () { - this.col = 0; - if(this.mode == LexMode.File) { - this.line++; - this.lineMap[this.line] = this.pos + 1; - } - }; - Scanner.prototype.finishMultilineComment = function () { - var ch2; - this.lexState = LexState.InMultilineComment; - while(this.pos < this.len) { - if(this.ch == TypeScript.LexCodeMUL) { - ch2 = this.peekCharAt(this.pos + 1); - if(ch2 == TypeScript.LexCodeSLH) { - this.advanceChar(2); - if(this.mode == LexMode.File) { - this.tokenStart(); - } - this.lexState = LexState.Start; - return true; - } - } else if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - this.nextChar(); - return false; - } - } else if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - this.nextChar(); - } - return false; - }; - Scanner.prototype.pushComment = function (comment) { - this.commentStack.push(comment); - }; - Scanner.prototype.getComments = function () { - var stack = this.commentStack; - this.commentStack = []; - return stack; - }; - Scanner.prototype.getCommentsForLine = function (line) { - var comments = null; - while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { - if(comments == null) { - comments = [ - this.commentStack.shift() - ]; - } else { - comments = comments.concat([ - this.commentStack.shift() - ]); - } - } - return comments; - }; - Scanner.prototype.resetComments = function () { - this.commentStack = []; - }; - Scanner.prototype.endsLine = function (c) { - return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); - }; - Scanner.prototype.finishSinglelineComment = function () { - while(this.pos < this.len) { - if(this.endsLine(this.ch)) { - break; - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeCharInComment = true; - } - this.nextChar(); - } - if(this.mode == LexMode.File) { - this.tokenStart(); - } - }; - Scanner.prototype.findClosingSLH = function () { - var index = this.pos; - var ch2 = this.src.charCodeAt(index); - var prevCh = 0; - var liveEsc = false; - while(!this.endsLine(ch2) && (index < this.len)) { - if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { - return index; - } - prevCh = ch2; - index++; - if(liveEsc) { - liveEsc = false; - } else { - liveEsc = (prevCh == TypeScript.LexCodeBSL); - } - ch2 = this.src.charCodeAt(index); - } - return -1; - }; - Scanner.prototype.speculateRegex = function () { - if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { - return null; - } - var svPos = this.pos; - var svCol = this.col; - var index = this.findClosingSLH(); - if(index > 0) { - var pattern = this.src.substring(svPos, index); - var flags = ""; - this.pos = index + 1; - this.ch = this.peekChar(); - var flagsStart = this.pos; - while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { - this.nextChar(); - } - if((this.pos - flagsStart) > 3) { - return null; - } else { - flags = this.src.substring(flagsStart, this.pos); - } - var regex = undefined; - try { - regex = new RegExp(pattern, flags); - } catch (regexException) { - } - if(regex) { - this.col = svCol + (this.pos - this.startPos); - return new TypeScript.RegularExpressionLiteralToken(this.src.substring(svPos - 1, this.pos)); - } - } - this.pos = svPos; - this.col = svCol; - return null; - }; - Scanner.prototype.lastTokenHadNewline = function () { - return this.prevLine != this.startLine; - }; - Scanner.prototype.lastTokenLimChar = function () { - return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; - }; - Scanner.prototype.advanceChar = function (amt) { - this.pos += amt; - this.col += amt; - this.ch = this.peekChar(); - }; - Scanner.prototype.nextChar = function () { - this.pos++; - this.col++; - this.ch = this.peekChar(); - }; - Scanner.prototype.getLookAheadToken = function () { - var prevLine = this.prevLine; - var line = this.line; - var col = this.col; - var pos = this.pos; - var startPos = this.startPos; - var startCol = this.startCol; - var startLine = this.startLine; - var ch = this.ch; - var prevTok = this.prevTok; - var lexState = this.lexState; - var interveningWhitespace = this.interveningWhitespace; - var interveningWhitespacePos = this.interveningWhitespacePos; - var leftCurlyCount = this.leftCurlyCount; - var rightCurlyCount = this.rightCurlyCount; - var seenUnicodeChar = this.seenUnicodeChar; - var seenUnicodeCharInComment = this.seenUnicodeCharInComment; - var commentStackLength = this.commentStack.length; - var lookAheadToken = this.scan(); - this.prevLine = prevLine; - this.line = line; - this.col = col; - this.pos = pos; - this.startPos = startPos; - this.startCol = startCol; - this.startLine = startLine; - this.ch = ch; - this.prevTok = prevTok; - this.lexState = lexState; - this.interveningWhitespace = interveningWhitespace; - this.interveningWhitespacePos = interveningWhitespacePos; - this.leftCurlyCount = leftCurlyCount; - this.rightCurlyCount = rightCurlyCount; - this.seenUnicodeChar = seenUnicodeChar; - this.seenUnicodeCharInComment = seenUnicodeCharInComment; - this.commentStack.length = commentStackLength; - return lookAheadToken; - }; - Scanner.prototype.scanInLine = function () { - if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { - this.ch = this.peekChar(); - var commentLine = this.line; - this.finishMultilineComment(); - if(this.startPos < this.pos) { - var commentText = this.src.substring(this.startPos, this.pos); - this.tokenStart(); - return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); - } else { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } else if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { - this.ch = this.peekChar(); - this.lexState = LexState.Start; - return this.scanStringConstant(TypeScript.LexCodeAPO); - } else if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { - this.ch = this.peekChar(); - this.lexState = LexState.Start; - return this.scanStringConstant(TypeScript.LexCodeQUO); - } - this.prevLine = this.line; - var prevTok = this.innerScan(); - if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { - this.prevTok = prevTok; - } - return prevTok; - }; - Scanner.prototype.scan = function () { - this.prevLine = this.line; - this.prevTok = this.innerScan(); - if(this.saveScan) { - this.saveScan.addToken(this.prevTok, this); - } - return this.prevTok; - }; - Scanner.prototype.isValidUnicodeIdentifierChar = function () { - var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); - this.seenUnicodeChar = this.seenUnicodeChar || valid; - return valid; - }; - Scanner.prototype.scanStringConstant = function (endCode) { - scanStringConstantLoop: -for(; ; ) { - switch(this.ch) { - case TypeScript.LexEOF: - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - this.seenUnicodeChar = true; - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: - this.reportScannerError("Unterminated string constant"); - break scanStringConstantLoop; - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: - if(this.ch == endCode) { - this.nextChar(); - break scanStringConstantLoop; - } - break; - case TypeScript.LexCodeBSL: - this.nextChar(); - switch(this.ch) { - case TypeScript.LexCodeAPO: - case TypeScript.LexCodeQUO: - case TypeScript.LexCodeBSL: - this.nextChar(); - continue scanStringConstantLoop; - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - this.seenUnicodeChar = true; - case TypeScript.LexCodeRET: - case TypeScript.LexCodeNWL: - if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { - this.nextChar(); - } - this.newLine(); - if(this.mode == LexMode.Line) { - this.nextChar(); - this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; - break scanStringConstantLoop; - } - break; - case TypeScript.LexCode_x: - case TypeScript.LexCode_u: - var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; - this.nextChar(); - for(var i = 0; i < expectedHexDigits; i++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - break; - } - } - continue scanStringConstantLoop; - } - break; - } - if(this.ch >= TypeScript.LexCodeASCIIChars) { - this.seenUnicodeChar = true; - } - this.nextChar(); - } - return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); - }; - Scanner.prototype.scanIdentifier = function () { - var hasEscape = false; - var isFirstChar = (this.ch == TypeScript.LexCodeBSL); - var hasUnicode = false; - for(; ; ) { - while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { - this.nextChar(); - } - if(this.ch == TypeScript.LexCodeBSL) { - this.nextChar(); - if(this.ch == TypeScript.LexCode_u) { - this.nextChar(); - for(var h = 0; h < 4; h++) { - if(this.IsHexDigit(this.ch)) { - this.nextChar(); - } else { - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } - var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); - if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { - } else { - this.reportScannerError("Invalid identifier character"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - hasEscape = true; - isFirstChar = false; - continue; - } - this.reportScannerError("Invalid Unicode escape sequence"); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - break; - } - var id; - var text = this.src.substring(this.startPos, this.pos); - if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { - return TypeScript.staticTokens[id]; - } else { - return new TypeScript.IdentifierToken(text, hasEscape); - } - }; - Scanner.prototype.innerScan = function () { - var rtok; - this.tokenStart(); - this.ch = this.peekChar(); - start: -while(this.pos < this.len) { - if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { - return this.scanIdentifier(); - } else if(this.ch == TypeScript.LexCodeSpace) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - do { - this.nextChar(); - }while(this.ch == TypeScript.LexCodeSpace); - if(this.mode == LexMode.Line) { - var whitespaceText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); - } else { - this.tokenStart(); - this.interveningWhitespace = true; - } - } else if(this.ch == TypeScript.LexCodeSLH) { - this.nextChar(); - var commentText; - if(this.ch == TypeScript.LexCodeSLH) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.finishSinglelineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else if(this.ch == TypeScript.LexCodeMUL) { - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos - 1; - } - var commentStartPos = this.pos - 1; - var commentStartLine = this.line; - this.nextChar(); - this.finishMultilineComment(); - var commentText = this.src.substring(commentStartPos, this.pos); - var endsLine = this.endsLine(this.peekChar()); - var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); - if(this.scanComments) { - this.startPos = commentStartPos; - return commentToken; - } else { - this.pushComment(commentToken); - } - this.interveningWhitespace = true; - } else { - var regexTok = this.speculateRegex(); - if(regexTok) { - return regexTok; - } else { - if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Slash]; - } - } - } - } else if(this.ch == TypeScript.LexCodeSMC) { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; - } else if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { - var endCode = this.ch; - this.nextChar(); - return this.scanStringConstant(endCode); - } else if(autoToken[this.ch]) { - var atok = autoToken[this.ch]; - if(atok.tokenId == TypeScript.TokenID.OpenBrace) { - this.leftCurlyCount++; - } else if(atok.tokenId == TypeScript.TokenID.CloseBrace) { - this.rightCurlyCount++; - } - this.nextChar(); - return atok; - } else if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { - rtok = this.scanNumber(); - if(rtok) { - return rtok; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Error]; - } - } else { - switch(this.ch) { - case TypeScript.LexCodeTAB: - case TypeScript.LexCodeVTAB: - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - if(this.mode == LexMode.Line) { - do { - this.nextChar(); - }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)); - var wsText = this.src.substring(this.startPos, this.pos); - return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); - } else { - this.interveningWhitespace = true; - } - case 0xFF: - case 0xFE: - case 0xEF: - case 0xBB: - case 0xBF: - case TypeScript.LexCodeLS: - case TypeScript.LexCodePS: - case TypeScript.LexCodeNWL: - case TypeScript.LexCodeRET: - if(this.ch == TypeScript.LexCodeNWL) { - this.newLine(); - if(this.mode == LexMode.Line) { - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - } - } - if(!this.interveningWhitespace) { - this.interveningWhitespacePos = this.pos; - } - this.nextChar(); - this.tokenStart(); - this.interveningWhitespace = true; - break; - case TypeScript.LexCodeDOT: { - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } else { - this.nextChar(); - rtok = this.scanFraction(); - if(rtok) { - return rtok; - } else { - return TypeScript.staticTokens[TypeScript.TokenID.Dot]; - } - } - } - case TypeScript.LexCodeEQ: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; - } - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Equals]; - } - case TypeScript.LexCodeBNG: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; - } - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; - } - case TypeScript.LexCodePLS: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Plus]; - } - case TypeScript.LexCodeMIN: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Minus]; - } - case TypeScript.LexCodeMUL: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; - } - case TypeScript.LexCodePCT: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Percent]; - } - case TypeScript.LexCodeLT: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; - } - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; - } - case TypeScript.LexCodeGT: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; - } else if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { - if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { - this.advanceChar(4); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; - } else { - this.advanceChar(3); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; - } - } else { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; - } - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; - } - case TypeScript.LexCodeXOR: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Caret]; - } - case TypeScript.LexCodeBAR: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.Bar]; - } - case TypeScript.LexCodeAMP: - if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; - } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { - this.advanceChar(2); - return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; - } else { - this.nextChar(); - return TypeScript.staticTokens[TypeScript.TokenID.And]; - } - default: - this.reportScannerError("Invalid character"); - this.nextChar(); - continue start; - } - } - } - return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; - }; - Scanner.prototype.reportScannerError = function (message) { - if(this.reportError) { - this.reportError(message); - } - }; - return Scanner; - })(); - TypeScript.Scanner = Scanner; - function convertTokToIDName(tok) { - return convertTokToIDBase(tok, true, false); - } - TypeScript.convertTokToIDName = convertTokToIDName; - function convertTokToID(tok, strictMode) { - return convertTokToIDBase(tok, false, strictMode); - } - TypeScript.convertTokToID = convertTokToID; - function convertTokToIDBase(tok, identifierName, strictMode) { - if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { - var tokInfo = TypeScript.lookupToken(tok.tokenId); - if(tokInfo != undefined) { - var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; - if(strictMode) { - resFlags |= TypeScript.Reservation.JavascriptFutureStrict; - } - if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { - return true; - } - } else { - return false; - } - } else { - return false; - } - } - function getLineNumberFromPosition(lineMap, position) { - if(position === -1) { - return 0; - } - var min = 0; - var max = lineMap.length - 1; - while(min < max) { - var med = (min + max) >> 1; - if(position < lineMap[med]) { - max = med - 1; - } else if(position < lineMap[med + 1]) { - min = max = med; - } else { - min = med + 1; - } - } - return min; - } - TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; - function getSourceLineColFromMap(lineCol, minChar, lineMap) { - var line = getLineNumberFromPosition(lineMap, minChar); - if(line > 0) { - lineCol.line = line; - lineCol.col = (minChar - lineMap[line]); - } - } - TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; - function getLineColumnFromPosition(script, position) { - var result = { - line: -1, - col: -1 - }; - getSourceLineColFromMap(result, position, script.locationInfo.lineMap); - if(result.col >= 0) { - result.col++; - } - return result; - } - TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; - function getPositionFromLineColumn(script, line, column) { - return script.locationInfo.lineMap[line] + (column - 1); - } - TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; - function isPrimitiveTypeToken(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Any: - case TypeScript.TokenID.Bool: - case TypeScript.TokenID.Number: - case TypeScript.TokenID.String: - return true; - } - return false; - } - TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; - function isModifier(token) { - switch(token.tokenId) { - case TypeScript.TokenID.Public: - case TypeScript.TokenID.Private: - case TypeScript.TokenID.Static: - return true; - } - return false; - } - TypeScript.isModifier = isModifier; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var AssignScopeContext = (function () { - function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { - this.scopeChain = scopeChain; - this.typeFlow = typeFlow; - this.modDeclChain = modDeclChain; - } - return AssignScopeContext; - })(); - TypeScript.AssignScopeContext = AssignScopeContext; - function pushAssignScope(scope, context, type, classType, fnc) { - var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); - chain.thisType = type; - chain.classType = classType; - chain.fnc = fnc; - context.scopeChain = chain; - } - TypeScript.pushAssignScope = pushAssignScope; - function popAssignScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popAssignScope = popAssignScope; - function instanceCompare(a, b) { - if(((a == null) || (!a.isInstanceProperty()))) { - return b; - } else { - return a; - } - } - TypeScript.instanceCompare = instanceCompare; - function instanceFilterStop(s) { - return s.isInstanceProperty(); - } - TypeScript.instanceFilterStop = instanceFilterStop; - var ScopeSearchFilter = (function () { - function ScopeSearchFilter(select, stop) { - this.select = select; - this.stop = stop; - this.result = null; - } - ScopeSearchFilter.prototype.reset = function () { - this.result = null; - }; - ScopeSearchFilter.prototype.update = function (b) { - this.result = this.select(this.result, b); - if(this.result) { - return this.stop(this.result); - } else { - return false; - } - }; - return ScopeSearchFilter; - })(); - TypeScript.ScopeSearchFilter = ScopeSearchFilter; - TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); - function preAssignModuleScopes(ast, context) { - var moduleDecl = ast; - var memberScope = null; - var aggScope = null; - if(moduleDecl.name && moduleDecl.mod) { - moduleDecl.name.sym = moduleDecl.mod.symbol; - } - var mod = moduleDecl.mod; - if(!mod) { - return; - } - memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); - mod.memberScope = memberScope; - context.modDeclChain.push(moduleDecl); - context.typeFlow.checker.currentModDecl = moduleDecl; - aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - mod.containedScope = aggScope; - if(mod.symbol) { - context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); - } - } - TypeScript.preAssignModuleScopes = preAssignModuleScopes; - function preAssignClassScopes(ast, context) { - var classDecl = ast; - var memberScope = null; - var aggScope = null; - if(classDecl.name && classDecl.type) { - classDecl.name.sym = classDecl.type.symbol; - } - var classType = ast.type; - if(classType) { - var classSym = classType.symbol; - memberScope = context.typeFlow.checker.scopeOf(classType); - aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - classType.containedScope = aggScope; - classType.memberScope = memberScope; - var instanceType = classType.instanceType; - memberScope = context.typeFlow.checker.scopeOf(instanceType); - instanceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, instanceType, classType, null); - instanceType.containedScope = aggScope; - } else { - ast.type = context.typeFlow.anyType; - } - } - TypeScript.preAssignClassScopes = preAssignClassScopes; - function preAssignInterfaceScopes(ast, context) { - var interfaceDecl = ast; - var memberScope = null; - var aggScope = null; - if(interfaceDecl.name && interfaceDecl.type) { - interfaceDecl.name.sym = interfaceDecl.type.symbol; - } - var interfaceType = ast.type; - memberScope = context.typeFlow.checker.scopeOf(interfaceType); - interfaceType.memberScope = memberScope; - aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); - aggScope.addParentScope(memberScope); - aggScope.addParentScope(context.scopeChain.scope); - pushAssignScope(aggScope, context, null, null, null); - interfaceType.containedScope = aggScope; - } - TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; - function preAssignWithScopes(ast, context) { - var withStmt = ast; - var withType = withStmt.type; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var withType = new TypeScript.Type(); - var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); - withType.members = members; - withType.ambientMembers = ambientMembers; - withType.symbol = withSymbol; - withType.setHasImplementation(); - withStmt.type = withType; - var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); - pushAssignScope(withScope, context, null, null, null); - withType.containedScope = withScope; - } - TypeScript.preAssignWithScopes = preAssignWithScopes; - function preAssignFuncDeclScopes(ast, context) { - var funcDecl = ast; - var container = null; - var localContainer = null; - if(funcDecl.type) { - localContainer = ast.type.symbol; - } - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isInnerStatic = isStatic && context.scopeChain.fnc != null; - var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; - if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { - var instType = context.scopeChain.thisType; - if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(!funcDecl.isMethod() || isStatic) { - parentScope = instType.constructorScope; - } else { - parentScope = instType.containedScope; - } - } else { - if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { - parentScope = instType.constructorScope; - } else if(isStatic && context.scopeChain.classType) { - parentScope = context.scopeChain.classType.containedScope; - } else { - parentScope = instType.containedScope; - } - } - container = instType.symbol; - } else if(funcDecl.isConstructor && context.scopeChain.thisType) { - container = context.scopeChain.thisType.symbol; - } - if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { - if(context.scopeChain.fnc && context.scopeChain.fnc.type) { - container = context.scopeChain.fnc.type.symbol; - } - var funcScope = null; - var outerFnc = context.scopeChain.fnc; - var nameText = funcDecl.name ? funcDecl.name.actualText : null; - var fgSym = null; - if(isStatic) { - if(outerFnc.type.members == null && container.getType().memberScope) { - outerFnc.type.members = ((container).type.memberScope).valueMembers; - } - funcScope = context.scopeChain.fnc.type.memberScope; - outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; - } else { - funcScope = context.scopeChain.scope; - } - if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { - if(isStatic) { - fgSym = funcScope.findLocal(nameText, false, false); - } else { - fgSym = funcScope.findLocal(nameText, false, false); - } - } - context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); - if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); - } - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; - } - if(funcDecl.name && funcDecl.type) { - funcDecl.name.sym = funcDecl.type.symbol; - } - funcDecl.scopeType = funcDecl.type; - if(funcDecl.isOverload) { - return; - } - var funcTable = new TypeScript.StringHashTable(); - var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); - var ambientFuncTable = new TypeScript.StringHashTable(); - var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); - var funcStaticTable = new TypeScript.StringHashTable(); - var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); - var ambientFuncStaticTable = new TypeScript.StringHashTable(); - var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); - funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; - var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); - var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); - if(funcDecl.isConstructor && context.scopeChain.thisType) { - context.scopeChain.thisType.constructorScope = locals; - } - funcDecl.symbols = funcTable; - if(!funcDecl.isSpecialFn()) { - var group = funcDecl.type; - var signature = funcDecl.signature; - if(!funcDecl.isConstructor) { - group.containedScope = locals; - locals.container = group.symbol; - group.memberScope = statics; - statics.container = group.symbol; - } - funcDecl.enclosingFnc = context.scopeChain.fnc; - group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; - var fgSym = ast.type.symbol; - if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { - context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); - context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); - } - if(signature.parameters) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); - } - } - context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); - } - if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; - pushAssignScope(locals, context, thisType, null, funcDecl); - } - if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isAccessor()) { - if(funcDecl.name.sym) { - funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); - } - } - } - TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; - function preAssignCatchScopes(ast, context) { - var catchBlock = ast; - if(catchBlock.param) { - var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); - catchBlock.containedScope = catchLocals; - pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); - } - } - TypeScript.preAssignCatchScopes = preAssignCatchScopes; - function preAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.List) { - var list = ast; - list.enclosingScope = context.scopeChain.scope; - } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - preAssignModuleScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - preAssignClassScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - preAssignInterfaceScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.With) { - preAssignWithScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - preAssignFuncDeclScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.Catch) { - preAssignCatchScopes(ast, context); - } else if(ast.nodeType == TypeScript.NodeType.TypeRef) { - go = false; - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preAssignScopes = preAssignScopes; - function postAssignScopes(ast, parent, walker) { - var context = walker.state; - var go = true; - if(ast) { - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var prevModDecl = ast; - popAssignScope(context); - context.modDeclChain.pop(); - if(context.modDeclChain.length >= 1) { - context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; - } - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - popAssignScope(context); - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - popAssignScope(context); - } else if(ast.nodeType == TypeScript.NodeType.With) { - popAssignScope(context); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { - popAssignScope(context); - } - } else if(ast.nodeType == TypeScript.NodeType.Catch) { - var catchBlock = ast; - if(catchBlock.param) { - popAssignScope(context); - } - } else { - go = false; - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.postAssignScopes = postAssignScopes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var TypeCollectionContext = (function () { - function TypeCollectionContext(scopeChain, checker) { - this.scopeChain = scopeChain; - this.checker = checker; - this.script = null; - } - return TypeCollectionContext; - })(); - TypeScript.TypeCollectionContext = TypeCollectionContext; - var MemberScopeContext = (function () { - function MemberScopeContext(flow, pos, matchFlag) { - this.flow = flow; - this.pos = pos; - this.matchFlag = matchFlag; - this.type = null; - this.ast = null; - this.options = new TypeScript.AstWalkOptions(); - } - return MemberScopeContext; - })(); - TypeScript.MemberScopeContext = MemberScopeContext; - var EnclosingScopeContext = (function () { - function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { - this.logger = logger; - this.script = script; - this.text = text; - this.pos = pos; - this.isMemberCompletion = isMemberCompletion; - this.scopeGetter = null; - this.objectLiteralScopeGetter = null; - this.scopeStartAST = null; - this.skipNextFuncDeclForClass = false; - this.deepestModuleDecl = null; - this.enclosingClassDecl = null; - this.enclosingObjectLit = null; - this.publicsOnly = true; - this.useFullAst = false; - } - EnclosingScopeContext.prototype.getScope = function () { - return this.scopeGetter(); - }; - EnclosingScopeContext.prototype.getObjectLiteralScope = function () { - return this.objectLiteralScopeGetter(); - }; - EnclosingScopeContext.prototype.getScopeAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScopePosition = function () { - return this.scopeStartAST.minChar; - }; - EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { - return this.scopeStartAST; - }; - EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { - return this.getScriptFragmentStartAST().minChar; - }; - EnclosingScopeContext.prototype.getScriptFragment = function () { - if(this.scriptFragment == null) { - var ast = this.getScriptFragmentStartAST(); - var minChar = ast.minChar; - var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); - this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; - } - return this.scriptFragment; - }; - return EnclosingScopeContext; - })(); - TypeScript.EnclosingScopeContext = EnclosingScopeContext; - function preFindMemberScope(ast, parent, walker) { - var memScope = walker.state; - if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { - memScope.ast = ast; - if((ast.type == null) && (memScope.pos >= 0)) { - memScope.flow.inScopeTypeCheck(ast, memScope.scope); - } - memScope.type = ast.type; - memScope.options.stopWalk(); - } - return ast; - } - TypeScript.preFindMemberScope = preFindMemberScope; - function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { - var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); - var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); - chain.thisType = thisType; - chain.classType = classType; - chain.moduleDecl = moduleDecl; - context.scopeChain = chain; - } - TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; - function popTypeCollectionScope(context) { - context.scopeChain = context.scopeChain.previous; - } - TypeScript.popTypeCollectionScope = popTypeCollectionScope; - function preFindEnclosingScope(ast, parent, walker) { - var context = walker.state; - var minChar = ast.minChar; - var limChar = ast.limChar; - if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { - limChar = context.pos; - } - if((minChar <= context.pos) && (limChar >= context.pos)) { - switch(ast.nodeType) { - case TypeScript.NodeType.Script: - var script = ast; - context.scopeGetter = function () { - return script.bod === null ? null : script.bod.enclosingScope; - }; - context.scopeStartAST = script; - break; - case TypeScript.NodeType.ClassDeclaration: - context.scopeGetter = function () { - return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; - }; - context.scopeStartAST = ast; - context.enclosingClassDecl = ast; - break; - case TypeScript.NodeType.ObjectLit: - var objectLit = ast; - if(objectLit.targetType) { - context.scopeGetter = function () { - return objectLit.targetType.containedScope; - }; - context.objectLiteralScopeGetter = function () { - return objectLit.targetType.memberScope; - }; - context.enclosingObjectLit = objectLit; - } - break; - case TypeScript.NodeType.ModuleDeclaration: - context.deepestModuleDecl = ast; - context.scopeGetter = function () { - return ast.type === null ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - case TypeScript.NodeType.InterfaceDeclaration: - context.scopeGetter = function () { - return (ast.type === null) ? null : ast.type.containedScope; - }; - context.scopeStartAST = ast; - break; - case TypeScript.NodeType.FuncDecl: - { - var funcDecl = ast; - if(context.skipNextFuncDeclForClass) { - context.skipNextFuncDeclForClass = false; - } else { - context.scopeGetter = function () { - if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - if(ast.type && ast.type.enclosingType) { - return ast.type.enclosingType.constructorScope; - } - } - if(funcDecl.scopeType) { - return funcDecl.scopeType.containedScope; - } - if(funcDecl.type) { - return funcDecl.type.containedScope; - } - return null; - }; - context.scopeStartAST = ast; - } - } - break; - } - walker.options.goChildren = true; - } else { - walker.options.goChildren = false; - } - return ast; - } - TypeScript.preFindEnclosingScope = preFindEnclosingScope; - function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { - var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); - TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); - if(context.scopeStartAST === null) { - return null; - } - return context; - } - TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Signature = (function () { - function Signature() { - this.hasVariableArgList = false; - this.parameters = null; - this.declAST = null; - this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - this.nonOptionalParameterCount = 0; - } - Signature.prototype.specializeType = function (pattern, replacement, checker) { - var result = new Signature(); - if(this.hasVariableArgList) { - result.hasVariableArgList = true; - } - result.returnType = new TypeScript.TypeLink(); - if(this.returnType.type) { - result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); - } else { - result.returnType.type = checker.anyType; - } - if(this.parameters) { - result.parameters = []; - for(var i = 0, len = this.parameters.length; i < len; i++) { - var oldSym = this.parameters[i]; - var paramDef = new TypeScript.ValueLocation(); - var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); - paramSym.declAST = this.declAST; - paramDef.symbol = paramSym; - paramDef.typeLink = new TypeScript.TypeLink(); - result.parameters[i] = paramSym; - var oldType = oldSym.getType(); - if(oldType) { - paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); - } else { - paramDef.typeLink.type = checker.anyType; - } - } - } - result.nonOptionalParameterCount = this.nonOptionalParameterCount; - result.declAST = this.declAST; - return result; - }; - Signature.prototype.toString = function () { - return this.toStringHelper(false, false, null); - }; - Signature.prototype.toStringHelper = function (shortform, brackets, scope) { - return this.toStringHelperEx(shortform, brackets, scope).toString(); - }; - Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { - if (typeof prefix === "undefined") { prefix = ""; } - var builder = new TypeScript.MemberNameArray(); - if(brackets) { - builder.prefix = prefix + "["; - } else { - builder.prefix = prefix + "("; - } - var paramLen = this.parameters.length; - var len = this.hasVariableArgList ? paramLen - 1 : paramLen; - for(var i = 0; i < len; i++) { - builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - if(i < paramLen - 1) { - builder.add(TypeScript.MemberName.create(", ")); - } - } - if(this.hasVariableArgList) { - builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); - builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); - } - if(shortform) { - if(brackets) { - builder.add(TypeScript.MemberName.create("] => ")); - } else { - builder.add(TypeScript.MemberName.create(") => ")); - } - } else { - if(brackets) { - builder.add(TypeScript.MemberName.create("]: ")); - } else { - builder.add(TypeScript.MemberName.create("): ")); - } - } - if(this.returnType.type) { - builder.add(this.returnType.type.getScopedTypeNameEx(scope)); - } else { - builder.add(TypeScript.MemberName.create("any")); - } - return builder; - }; - return Signature; - })(); - TypeScript.Signature = Signature; - var SignatureGroup = (function () { - function SignatureGroup() { - this.signatures = []; - this.hasImplementation = true; - this.definitionSignature = null; - this.hasBeenTypechecked = false; - this.flags = TypeScript.SignatureFlags.None; - } - SignatureGroup.prototype.addSignature = function (signature) { - if(this.signatures == null) { - this.signatures = new Array(); - } - this.signatures[this.signatures.length] = signature; - if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Signature)) { - this.definitionSignature = signature; - } - }; - SignatureGroup.prototype.toString = function () { - return this.signatures.toString(); - }; - SignatureGroup.prototype.toStrings = function (prefix, shortform, scope, getPrettyTypeName, useSignature) { - var _this = this; - var result = []; - var len = this.signatures.length; - if(!getPrettyTypeName && len > 1) { - shortform = false; - } - var getMemberNameOfSignature = function (signature) { - if(_this.flags & TypeScript.SignatureFlags.IsIndexer) { - return signature.toStringHelperEx(shortform, true, scope); - } else { - return signature.toStringHelperEx(shortform, false, scope, prefix); - } - }; - if(useSignature) { - result.push(getMemberNameOfSignature(useSignature)); - } else { - for(var i = 0; i < len; i++) { - if(len > 1 && this.signatures[i] == this.definitionSignature) { - continue; - } - result.push(getMemberNameOfSignature(this.signatures[i])); - if(getPrettyTypeName) { - break; - } - } - } - if(getPrettyTypeName && len > 1) { - var lastMemberName = result[result.length - 1]; - var overloadString = " (+ " + ((this.definitionSignature != null) ? len - 2 : len - 1) + " overload(s))"; - lastMemberName.add(TypeScript.MemberName.create(overloadString)); - } - return result; - }; - SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { - var result = new SignatureGroup(); - if(this.signatures) { - for(var i = 0, len = this.signatures.length; i < len; i++) { - result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); - } - } - return result; - }; - SignatureGroup.prototype.verifySignatures = function (checker) { - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - for(var j = i + 1; j < len; j++) { - if(this.signatures[i].declAST && this.signatures[j].declAST && (TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Signature) && TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Signature)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); - } - } - if(this.definitionSignature) { - if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); - } - } - } - } - }; - SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { - if(this.hasBeenTypechecked) { - return; - } - this.hasBeenTypechecked = true; - var len = 0; - if(this.signatures && ((len = this.signatures.length) > 0)) { - for(var i = 0; i < len; i++) { - if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { - checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); - } - if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); - } - checker.typeFlow.typeCheck(this.signatures[i].declAST); - } - this.verifySignatures(checker); - } - }; - return SignatureGroup; - })(); - TypeScript.SignatureGroup = SignatureGroup; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TypeCheckStatus) { - TypeCheckStatus._map = []; - TypeCheckStatus._map[0] = "NotStarted"; - TypeCheckStatus.NotStarted = 0; - TypeCheckStatus._map[1] = "Started"; - TypeCheckStatus.Started = 1; - TypeCheckStatus._map[2] = "Finished"; - TypeCheckStatus.Finished = 2; - })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); - var TypeCheckStatus = TypeScript.TypeCheckStatus; - function aLexicallyEnclosesB(a, b) { - if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; - } else { - return false; - } - } - TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; - function aEnclosesB(a, b) { - while(a.container) { - if(a == b || aLexicallyEnclosesB(a.container, b)) { - return true; - } - a = a.container; - } - return false; - } - TypeScript.aEnclosesB = aEnclosesB; - var Symbol = (function () { - function Symbol(name, location, length, unitIndex) { - this.name = name; - this.location = location; - this.length = length; - this.unitIndex = unitIndex; - this.bound = false; - this.flags = TypeScript.SymbolFlags.None; - this.isObjectLitField = false; - this.declAST = null; - this.declModule = null; - this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; - } - Symbol.prototype.instanceScope = function () { - return null; - }; - Symbol.prototype.isVariable = function () { - return false; - }; - Symbol.prototype.isMember = function () { - return false; - }; - Symbol.prototype.isInferenceSymbol = function () { - return false; - }; - Symbol.prototype.isWith = function () { - return false; - }; - Symbol.prototype.writeable = function () { - return false; - }; - Symbol.prototype.isType = function () { - return false; - }; - Symbol.prototype.getType = function () { - return null; - }; - Symbol.prototype.isAccessor = function () { - return false; - }; - Symbol.prototype.isInstanceProperty = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); - }; - Symbol.prototype.getTypeName = function (scope) { - return this.getTypeNameEx(scope).toString(); - }; - Symbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.toString()); - }; - Symbol.prototype.getOptionalNameString = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; - }; - Symbol.prototype.pathToRoot = function () { - var path = new Array(); - var node = this; - while(node && (node.name != TypeScript.globalId)) { - path[path.length] = node; - node = node.container; - } - return path; - }; - Symbol.prototype.findCommonAncestorPath = function (b) { - if(this.container == null) { - return new Array(); - } - var aPath = this.container.pathToRoot(); - var bPath; - if(b) { - bPath = b.pathToRoot(); - } else { - bPath = new Array(); - } - var commonNodeIndex = -1; - for(var i = 0, aLen = aPath.length; i < aLen; i++) { - var aNode = aPath[i]; - for(var j = 0, bLen = bPath.length; j < bLen; j++) { - var bNode = bPath[j]; - if(aNode == bNode) { - commonNodeIndex = i; - break; - } - } - if(commonNodeIndex >= 0) { - break; - } - } - if(commonNodeIndex >= 0) { - return aPath.slice(0, commonNodeIndex); - } else { - return aPath; - } - }; - Symbol.prototype.getPrettyName = function (scopeSymbol) { - return this.name; - }; - Symbol.prototype.scopeRelativeName = function (scope) { - if(scope == null) { - return this.getPrettyName(null) + this.getOptionalNameString(); - } - var lca = this.findCommonAncestorPath(scope.container); - var builder = ""; - for(var i = 0, len = lca.length; i < len; i++) { - var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); - builder = prettyName + "." + builder; - } - builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); - return builder; - }; - Symbol.prototype.fullName = function (scope) { - var scopeSymbol = !scope ? null : scope.container; - var scopeRootPath = !scopeSymbol ? [] : scopeSymbol.pathToRoot(); - var dynamicModuleRoot = null; - if(scopeRootPath.length > 0 && scopeRootPath[scopeRootPath.length - 1].declAST && scopeRootPath[scopeRootPath.length - 1].declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (scopeRootPath[scopeRootPath.length - 1].declAST).isWholeFile()) { - dynamicModuleRoot = scopeRootPath[scopeRootPath.length - 1]; - } - var builder = this.getPrettyName(scopeSymbol); - var ancestor = this.container; - while(ancestor && (ancestor.name != TypeScript.globalId) && ancestor != dynamicModuleRoot) { - builder = ancestor.getPrettyName(scopeSymbol) + "." + builder; - ancestor = ancestor.container; - } - return builder; - }; - Symbol.prototype.isExternallyVisible = function (checker) { - if(this == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return false; - } - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - return this.container == checker.gloMod; - } - return this.container.isExternallyVisible(checker); - }; - Symbol.prototype.visible = function (scope, checker) { - if(checker == null || this.container == checker.gloMod) { - return true; - } - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { - if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { - return true; - } else { - return aEnclosesB(this, scope.container); - } - } else { - return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); - } - } else { - var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - var isMethod = isFunction && (this.declAST).isMethod(); - var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); - var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); - var isAlias = this.isType() && (this).aliasLink; - if(this.isMember() || isMethod || isStaticFunction || isAlias) { - if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { - if(scope.container == null && this.container != scope.container) { - return false; - } else { - return this.container == null ? true : aEnclosesB(scope.container, this.container); - } - } else { - return true; - } - } else if(this.container) { - return aEnclosesB(this, scope.container); - } else { - return true; - } - } - }; - Symbol.prototype.addRef = function (identifier) { - if(!this.refs) { - this.refs = []; - } - this.refs[this.refs.length] = identifier; - }; - Symbol.prototype.toString = function () { - if(this.name) { - return this.name; - } else { - return "_anonymous"; - } - }; - Symbol.prototype.print = function (outfile) { - outfile.Write(this.toString()); - }; - Symbol.prototype.specializeType = function (pattern, replacement, checker) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.setType = function (type) { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.kind = function () { - throw new Error("please implement in derived class"); - }; - Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { - if(this.declAST != null) { - if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.declAST; - } else if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - return this.container.declAST; - } - } - return null; - }; - Symbol.prototype.getVarDeclFromSymbol = function () { - if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { - return this.declAST; - } - return null; - }; - Symbol.prototype.getDocComments = function () { - if(this.declAST != null) { - return this.declAST.getDocComments(); - } - return []; - }; - Symbol.prototype.isStatic = function () { - return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); - }; - return Symbol; - })(); - TypeScript.Symbol = Symbol; - var ValueLocation = (function () { - function ValueLocation() { } - return ValueLocation; - })(); - TypeScript.ValueLocation = ValueLocation; - var InferenceSymbol = (function (_super) { - __extends(InferenceSymbol, _super); - function InferenceSymbol(name, location, length, unitIndex) { - _super.call(this, name, location, length, unitIndex); - this.typeCheckStatus = TypeCheckStatus.NotStarted; - } - InferenceSymbol.prototype.isInferenceSymbol = function () { - return true; - }; - InferenceSymbol.prototype.transferVarFlags = function (varFlags) { - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { - this.flags |= TypeScript.SymbolFlags.Ambient; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { - this.flags |= TypeScript.SymbolFlags.Constant; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { - this.flags |= TypeScript.SymbolFlags.Static; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { - this.flags |= TypeScript.SymbolFlags.Property; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { - this.flags |= TypeScript.SymbolFlags.Private; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { - this.flags |= TypeScript.SymbolFlags.Public; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { - this.flags |= TypeScript.SymbolFlags.Readonly; - } - if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { - this.flags |= TypeScript.SymbolFlags.Exported; - } - }; - return InferenceSymbol; - })(Symbol); - TypeScript.InferenceSymbol = InferenceSymbol; - var TypeSymbol = (function (_super) { - __extends(TypeSymbol, _super); - function TypeSymbol(locName, location, length, unitIndex, type) { - _super.call(this, locName, location, length, unitIndex); - this.type = type; - this.expansions = []; - this.expansionsDeclAST = []; - this.isDynamic = false; - this.isMethod = false; - this.aliasLink = null; - this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; - this.prettyName = this.name; - } - TypeSymbol.prototype.addLocation = function (loc) { - if(this.additionalLocations == null) { - this.additionalLocations = []; - } - this.additionalLocations[this.additionalLocations.length] = loc; - }; - TypeSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Type; - }; - TypeSymbol.prototype.isType = function () { - return true; - }; - TypeSymbol.prototype.getType = function () { - return this.type; - }; - TypeSymbol.prototype.getTypeNameEx = function (scope) { - return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); - }; - TypeSymbol.prototype.instanceScope = function () { - if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { - return this.type.instanceType.constructorScope; - } else { - return this.type.containedScope; - } - }; - TypeSymbol.prototype.toString = function () { - var result = this.type.getTypeName(); - if(this.name) { - result = this.name + ":" + result; - } - return result; - }; - TypeSymbol.prototype.isClass = function () { - return this.instanceType != null; - }; - TypeSymbol.prototype.isFunction = function () { - return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; - }; - TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { - if(this.type == pattern) { - return replacement.symbol; - } else { - var replType = this.type.specializeType(pattern, replacement, checker, false); - if(replType != this.type) { - var result = new TypeSymbol(this.name, -1, 0, -1, replType); - return result; - } else { - return this; - } - } - }; - TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { - if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { - var symbolPath = scopeSymbol.pathToRoot(); - var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); - if(prettyName != null) { - return prettyName.name; - } - } - return this.prettyName; - }; - TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { - var scopeSymbolPathLength = scopeSymbolPath.length; - var externalSymbol = null; - if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { - if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - if(externalSymbol == null) { - var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); - externalSymbol = moduleType.findDynamicModuleName(this.type); - } - } - return externalSymbol; - }; - TypeSymbol.prototype.getDocComments = function () { - var comments = []; - if(this.declAST != null) { - comments = comments.concat(this.declAST.getDocComments()); - } - for(var i = 0; i < this.expansionsDeclAST.length; i++) { - comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); - } - return comments; - }; - return TypeSymbol; - })(InferenceSymbol); - TypeScript.TypeSymbol = TypeSymbol; - var WithSymbol = (function (_super) { - __extends(WithSymbol, _super); - function WithSymbol(location, unitIndex, withType) { - _super.call(this, "with", location, 4, unitIndex, withType); - } - WithSymbol.prototype.isWith = function () { - return true; - }; - return WithSymbol; - })(TypeSymbol); - TypeScript.WithSymbol = WithSymbol; - var FieldSymbol = (function (_super) { - __extends(FieldSymbol, _super); - function FieldSymbol(name, location, unitIndex, canWrite, field) { - _super.call(this, name, location, name.length, unitIndex); - this.canWrite = canWrite; - this.field = field; - this.getter = null; - this.setter = null; - this.hasBeenEmitted = false; - this.name = name; - this.location = location; - } - FieldSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Field; - }; - FieldSymbol.prototype.writeable = function () { - return this.isAccessor() ? this.setter != null : this.canWrite; - }; - FieldSymbol.prototype.getType = function () { - return this.field.typeLink.type; - }; - FieldSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.field.typeLink.type ? this.field.typeLink.type.getScopedTypeNameEx(scope) : TypeScript.MemberName.create("any"), this.name + this.getOptionalNameString() + ": ", ""); - }; - FieldSymbol.prototype.isMember = function () { - return true; - }; - FieldSymbol.prototype.setType = function (type) { - this.field.typeLink.type = type; - }; - FieldSymbol.prototype.isAccessor = function () { - return this.getter != null || this.setter != null; - }; - FieldSymbol.prototype.isVariable = function () { - return true; - }; - FieldSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); - if(rType != this.field.typeLink.type) { - var fieldDef = new ValueLocation(); - var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); - result.flags = this.flags; - fieldDef.symbol = result; - fieldDef.typeLink = new TypeScript.TypeLink(); - result.setType(rType); - result.typeCheckStatus = TypeCheckStatus.Finished; - return result; - } else { - return this; - } - }; - FieldSymbol.prototype.getDocComments = function () { - if(this.getter != null || this.setter != null) { - var comments = []; - if(this.getter != null) { - comments = comments.concat(this.getter.getDocComments()); - } - if(this.setter != null) { - comments = comments.concat(this.setter.getDocComments()); - } - return comments; - } else if(this.declAST != null) { - return this.declAST.getDocComments(); - } - return []; - }; - return FieldSymbol; - })(InferenceSymbol); - TypeScript.FieldSymbol = FieldSymbol; - var ParameterSymbol = (function (_super) { - __extends(ParameterSymbol, _super); - function ParameterSymbol(name, location, unitIndex, parameter) { - _super.call(this, name, location, name.length, unitIndex); - this.parameter = parameter; - this.paramDocComment = null; - this.funcDecl = null; - this.argsOffset = (-1); - this.name = name; - this.location = location; - } - ParameterSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Parameter; - }; - ParameterSymbol.prototype.writeable = function () { - return true; - }; - ParameterSymbol.prototype.getType = function () { - return this.parameter.typeLink.type; - }; - ParameterSymbol.prototype.setType = function (type) { - this.parameter.typeLink.type = type; - }; - ParameterSymbol.prototype.isVariable = function () { - return true; - }; - ParameterSymbol.prototype.isOptional = function () { - if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { - return (this.parameter.symbol.declAST).isOptional; - } else { - return false; - } - }; - ParameterSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); - }; - ParameterSymbol.prototype.toString = function () { - return this.getTypeNameEx(null).toString(); - }; - ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { - var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); - if(this.parameter.typeLink.type != rType) { - var paramDef = new ValueLocation(); - var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); - paramDef.symbol = result; - result.setType(rType); - return result; - } else { - return this; - } - }; - ParameterSymbol.prototype.getParameterDocComments = function () { - if(!this.paramDocComment) { - var parameterComments = []; - if(this.funcDecl) { - var fncDocComments = this.funcDecl.getDocComments(); - var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); - if(paramComment != "") { - parameterComments.push(paramComment); - } - } - var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); - if(docComments != "") { - parameterComments.push(docComments); - } - this.paramDocComment = parameterComments.join("\n"); - } - return this.paramDocComment; - }; - ParameterSymbol.prototype.fullName = function () { - return this.name; - }; - return ParameterSymbol; - })(InferenceSymbol); - TypeScript.ParameterSymbol = ParameterSymbol; - var VariableSymbol = (function (_super) { - __extends(VariableSymbol, _super); - function VariableSymbol(name, location, unitIndex, variable) { - _super.call(this, name, location, name.length, unitIndex); - this.variable = variable; - } - VariableSymbol.prototype.kind = function () { - return TypeScript.SymbolKind.Variable; - }; - VariableSymbol.prototype.writeable = function () { - return true; - }; - VariableSymbol.prototype.getType = function () { - return this.variable.typeLink.type; - }; - VariableSymbol.prototype.getTypeNameEx = function (scope) { - return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); - }; - VariableSymbol.prototype.setType = function (type) { - this.variable.typeLink.type = type; - }; - VariableSymbol.prototype.isVariable = function () { - return true; - }; - return VariableSymbol; - })(InferenceSymbol); - TypeScript.VariableSymbol = VariableSymbol; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopedMembers = (function () { - function ScopedMembers(dualMembers) { - this.dualMembers = dualMembers; - this.allMembers = this.dualMembers; - this.publicMembers = this.dualMembers.primaryTable; - this.privateMembers = this.dualMembers.secondaryTable; - } - ScopedMembers.prototype.addPublicMember = function (key, data) { - return this.dualMembers.primaryTable.add(key, data); - }; - ScopedMembers.prototype.addPrivateMember = function (key, data) { - return this.dualMembers.secondaryTable.add(key, data); - }; - return ScopedMembers; - })(); - TypeScript.ScopedMembers = ScopedMembers; - (function (SymbolKind) { - SymbolKind._map = []; - SymbolKind._map[0] = "None"; - SymbolKind.None = 0; - SymbolKind._map[1] = "Type"; - SymbolKind.Type = 1; - SymbolKind._map[2] = "Field"; - SymbolKind.Field = 2; - SymbolKind._map[3] = "Parameter"; - SymbolKind.Parameter = 3; - SymbolKind._map[4] = "Variable"; - SymbolKind.Variable = 4; - })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); - var SymbolKind = TypeScript.SymbolKind; - var SymbolScope = (function () { - function SymbolScope(container) { - this.container = container; - } - SymbolScope.prototype.printLabel = function () { - return "base"; - }; - SymbolScope.prototype.getAllSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllTypeSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.getAllValueSymbolNames = function (members) { - return [ - "please", - "implement", - "in", - "derived", - "classes" - ]; - }; - SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.find = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { - return null; - }; - SymbolScope.prototype.print = function (outfile) { - if(this.container) { - outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); - } else { - outfile.WriteLine(this.printLabel() + " scope..."); - } - }; - SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { - throw new Error("please implement in derived class"); - }; - SymbolScope.prototype.getTable = function () { - throw new Error("please implement in derived class"); - }; - return SymbolScope; - })(); - TypeScript.SymbolScope = SymbolScope; - function symbolCanBeUsed(sym, publicOnly) { - return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; - } - var SymbolAggregateScope = (function (_super) { - __extends(SymbolAggregateScope, _super); - function SymbolAggregateScope(container) { - _super.call(this, container); - this.valueCache = null; - this.valueImplCache = null; - this.valueAmbientCache = null; - this.typeCache = null; - this.typeImplCache = null; - this.typeAmbientCache = null; - this.parents = null; - this.container = container; - } - SymbolAggregateScope.prototype.printLabel = function () { - return "agg"; - }; - SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var sym = this.parents[i].search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - } - return filter.result; - }; - SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - var parentResult = this.parents[i].getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - } - return result; - }; - SymbolAggregateScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.parents) { - for(var i = 0; i < this.parents.length; i++) { - this.parents[i].print(outfile); - } - } - }; - SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var implCache = this.valueImplCache; - if(typespace) { - implCache = this.typeImplCache; - } - if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findImplementation(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(implCache) { - if(typespace) { - this.typeImplCache = new TypeScript.StringHashTable(); - implCache = this.typeImplCache; - } else { - this.valueImplCache = new TypeScript.StringHashTable(); - implCache = this.valueImplCache; - } - } - implCache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueCache; - if(typespace) { - cache = this.typeCache; - } - if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].find(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeCache = new TypeScript.StringHashTable(); - cache = this.typeCache; - } else { - this.valueCache = new TypeScript.StringHashTable(); - cache = this.valueCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var i = 0; - var cache = this.valueAmbientCache; - if(typespace) { - cache = this.typeAmbientCache; - } - if(cache && ((sym = cache.lookup(name)) != null)) { - return sym; - } - if(this.parents) { - for(i = 0; i < this.parents.length; i++) { - sym = this.parents[i].findAmbient(name, publicOnly, typespace); - if(sym) { - break; - } - } - } - if(cache == null) { - if(typespace) { - this.typeAmbientCache = new TypeScript.StringHashTable(); - cache = this.typeAmbientCache; - } else { - this.valueAmbientCache = new TypeScript.StringHashTable(); - cache = this.valueAmbientCache; - } - } - cache.add(name, sym); - return sym; - }; - SymbolAggregateScope.prototype.addParentScope = function (parent) { - if(this.parents == null) { - this.parents = new Array(); - } - this.parents[this.parents.length] = parent; - }; - return SymbolAggregateScope; - })(SymbolScope); - TypeScript.SymbolAggregateScope = SymbolAggregateScope; - var SymbolTableScope = (function (_super) { - __extends(SymbolTableScope, _super); - function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.container = container; - } - SymbolTableScope.prototype.printLabel = function () { - return "table"; - }; - SymbolTableScope.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - return result; - }; - SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - filter.update(sym); - return filter.result; - }; - SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { - var table = null; - var ambientTable = null; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } else { - table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - if(table) { - var s = table.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - var s = ambientTable.lookup(name); - if(s) { - return s; - } - } - return null; - }; - SymbolTableScope.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, sym, context) { - outfile.WriteLine(" " + key); - }, null); - } - }; - SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { - var sym = this.find(name, publicOnly, typespace); - if(sym) { - if(sym.kind() == SymbolKind.Type) { - var typeSym = sym; - if(!typeSym.type.hasImplementation()) { - sym = null; - } - } else if(sym.container) { - if(sym.container.kind() == SymbolKind.Type) { - var ctypeSym = sym.container; - if(!ctypeSym.type.hasImplementation()) { - sym = null; - } - } - } - } - return sym; - }; - SymbolTableScope.prototype.getTable = function () { - return this.valueMembers.publicMembers; - }; - return SymbolTableScope; - })(SymbolScope); - TypeScript.SymbolTableScope = SymbolTableScope; - var SymbolScopeBuilder = (function (_super) { - __extends(SymbolScopeBuilder, _super); - function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { - _super.call(this, container); - this.valueMembers = valueMembers; - this.ambientValueMembers = ambientValueMembers; - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.parent = parent; - this.container = container; - } - SymbolScopeBuilder.prototype.printLabel = function () { - return "builder"; - }; - SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { - var result = this.getAllTypeSymbolNames(members); - return result.concat(this.getAllValueSymbolNames(members)); - }; - SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { - var result = []; - if(this.ambientEnclosedTypes) { - result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); - } - if(this.enclosedTypes) { - result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllTypeSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { - var result = []; - if(this.ambientValueMembers) { - result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); - } - if(this.valueMembers) { - result = result.concat(this.valueMembers.allMembers.getAllKeys()); - } - if(!members && this.parent) { - var parentResult = this.parent.getAllValueSymbolNames(members); - if(parentResult) { - result = result.concat(parentResult); - } - } - return result; - }; - SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(filter.update(sym)) { - return sym; - } - } - } - if(this.parent) { - sym = this.parent.search(filter, name, publicOnly, typespace); - if(sym) { - if(filter.update(sym)) { - return sym; - } - } - } - return filter.result; - }; - SymbolScopeBuilder.prototype.print = function (outfile) { - _super.prototype.print.call(this, outfile); - if(this.ambientValueMembers) { - this.ambientValueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.valueMembers) { - this.valueMembers.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.ambientEnclosedTypes) { - this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.enclosedTypes) { - this.enclosedTypes.allMembers.map(function (key, s, context) { - var sym = s; - outfile.WriteLine(" " + key); - }, null); - } - if(this.parent) { - this.parent.print(outfile); - } - }; - SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(table && ((sym = table.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.find(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { - var sym = null; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { - return sym; - } - if(this.parent) { - return this.parent.findAmbient(name, publicOnly, typespace); - } - return null; - }; - SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = null; - var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; - var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; - if(typespace) { - table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; - ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; - } - if(table) { - if((sym = table.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - if(ambientTable) { - if((sym = ambientTable.lookup(name)) != null) { - if(sym) { - return sym; - } - } - } - return null; - }; - SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { - var table = null; - if(ambient) { - if(typespace) { - table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; - } else { - table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; - } - } else { - if(typespace) { - table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; - } else { - table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; - } - } - if(table) { - if(!table.add(symbol.name, symbol)) { - errorReporter.duplicateIdentifier(ast, symbol.name); - } - } else { - TypeScript.CompilerDiagnostics.Alert("YYYYY"); - } - symbol.container = container; - }; - SymbolScopeBuilder.prototype.getTable = function () { - return this.valueMembers.allMembers; - }; - return SymbolScopeBuilder; - })(SymbolScope); - TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; - var FilteredSymbolScope = (function (_super) { - __extends(FilteredSymbolScope, _super); - function FilteredSymbolScope(scope, container, filter) { - _super.call(this, container); - this.scope = scope; - this.filter = filter; - } - FilteredSymbolScope.prototype.print = function (outfile) { - this.scope.print(outfile); - }; - FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { - this.filter.reset(); - return this.scope.search(this.filter, name, publicOnly, typespace); - }; - FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { - return this.scope.findLocal(name, publicOnly, typespace); - }; - return FilteredSymbolScope; - })(SymbolScope); - TypeScript.FilteredSymbolScope = FilteredSymbolScope; - var FilteredSymbolScopeBuilder = (function (_super) { - __extends(FilteredSymbolScopeBuilder, _super); - function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { - _super.call(this, valueMembers, null, null, null, parent, container); - this.filter = filter; - } - FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return sym; - }; - FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { - throw new Error("please implement"); - }; - FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { - var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); - if(sym) { - if(!this.filter(sym)) { - return null; - } - } - return _super.prototype.find.call(this, name, publicOnly, typespace); - }; - return FilteredSymbolScopeBuilder; - })(SymbolScopeBuilder); - TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (TokenID) { - TokenID._map = []; - TokenID._map[0] = "Any"; - TokenID.Any = 0; - TokenID._map[1] = "Bool"; - TokenID.Bool = 1; - TokenID._map[2] = "Break"; - TokenID.Break = 2; - TokenID._map[3] = "Case"; - TokenID.Case = 3; - TokenID._map[4] = "Catch"; - TokenID.Catch = 4; - TokenID._map[5] = "Class"; - TokenID.Class = 5; - TokenID._map[6] = "Const"; - TokenID.Const = 6; - TokenID._map[7] = "Continue"; - TokenID.Continue = 7; - TokenID._map[8] = "Debugger"; - TokenID.Debugger = 8; - TokenID._map[9] = "Default"; - TokenID.Default = 9; - TokenID._map[10] = "Delete"; - TokenID.Delete = 10; - TokenID._map[11] = "Do"; - TokenID.Do = 11; - TokenID._map[12] = "Else"; - TokenID.Else = 12; - TokenID._map[13] = "Enum"; - TokenID.Enum = 13; - TokenID._map[14] = "Export"; - TokenID.Export = 14; - TokenID._map[15] = "Extends"; - TokenID.Extends = 15; - TokenID._map[16] = "Declare"; - TokenID.Declare = 16; - TokenID._map[17] = "False"; - TokenID.False = 17; - TokenID._map[18] = "Finally"; - TokenID.Finally = 18; - TokenID._map[19] = "For"; - TokenID.For = 19; - TokenID._map[20] = "Function"; - TokenID.Function = 20; - TokenID._map[21] = "Constructor"; - TokenID.Constructor = 21; - TokenID._map[22] = "Get"; - TokenID.Get = 22; - TokenID._map[23] = "If"; - TokenID.If = 23; - TokenID._map[24] = "Implements"; - TokenID.Implements = 24; - TokenID._map[25] = "Import"; - TokenID.Import = 25; - TokenID._map[26] = "In"; - TokenID.In = 26; - TokenID._map[27] = "InstanceOf"; - TokenID.InstanceOf = 27; - TokenID._map[28] = "Interface"; - TokenID.Interface = 28; - TokenID._map[29] = "Let"; - TokenID.Let = 29; - TokenID._map[30] = "Module"; - TokenID.Module = 30; - TokenID._map[31] = "New"; - TokenID.New = 31; - TokenID._map[32] = "Number"; - TokenID.Number = 32; - TokenID._map[33] = "Null"; - TokenID.Null = 33; - TokenID._map[34] = "Package"; - TokenID.Package = 34; - TokenID._map[35] = "Private"; - TokenID.Private = 35; - TokenID._map[36] = "Protected"; - TokenID.Protected = 36; - TokenID._map[37] = "Public"; - TokenID.Public = 37; - TokenID._map[38] = "Return"; - TokenID.Return = 38; - TokenID._map[39] = "Set"; - TokenID.Set = 39; - TokenID._map[40] = "Static"; - TokenID.Static = 40; - TokenID._map[41] = "String"; - TokenID.String = 41; - TokenID._map[42] = "Super"; - TokenID.Super = 42; - TokenID._map[43] = "Switch"; - TokenID.Switch = 43; - TokenID._map[44] = "This"; - TokenID.This = 44; - TokenID._map[45] = "Throw"; - TokenID.Throw = 45; - TokenID._map[46] = "True"; - TokenID.True = 46; - TokenID._map[47] = "Try"; - TokenID.Try = 47; - TokenID._map[48] = "TypeOf"; - TokenID.TypeOf = 48; - TokenID._map[49] = "Var"; - TokenID.Var = 49; - TokenID._map[50] = "Void"; - TokenID.Void = 50; - TokenID._map[51] = "With"; - TokenID.With = 51; - TokenID._map[52] = "While"; - TokenID.While = 52; - TokenID._map[53] = "Yield"; - TokenID.Yield = 53; - TokenID._map[54] = "Semicolon"; - TokenID.Semicolon = 54; - TokenID._map[55] = "OpenParen"; - TokenID.OpenParen = 55; - TokenID._map[56] = "CloseParen"; - TokenID.CloseParen = 56; - TokenID._map[57] = "OpenBracket"; - TokenID.OpenBracket = 57; - TokenID._map[58] = "CloseBracket"; - TokenID.CloseBracket = 58; - TokenID._map[59] = "OpenBrace"; - TokenID.OpenBrace = 59; - TokenID._map[60] = "CloseBrace"; - TokenID.CloseBrace = 60; - TokenID._map[61] = "Comma"; - TokenID.Comma = 61; - TokenID._map[62] = "Equals"; - TokenID.Equals = 62; - TokenID._map[63] = "PlusEquals"; - TokenID.PlusEquals = 63; - TokenID._map[64] = "MinusEquals"; - TokenID.MinusEquals = 64; - TokenID._map[65] = "AsteriskEquals"; - TokenID.AsteriskEquals = 65; - TokenID._map[66] = "SlashEquals"; - TokenID.SlashEquals = 66; - TokenID._map[67] = "PercentEquals"; - TokenID.PercentEquals = 67; - TokenID._map[68] = "AmpersandEquals"; - TokenID.AmpersandEquals = 68; - TokenID._map[69] = "CaretEquals"; - TokenID.CaretEquals = 69; - TokenID._map[70] = "BarEquals"; - TokenID.BarEquals = 70; - TokenID._map[71] = "LessThanLessThanEquals"; - TokenID.LessThanLessThanEquals = 71; - TokenID._map[72] = "GreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanEquals = 72; - TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; - TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; - TokenID._map[74] = "Question"; - TokenID.Question = 74; - TokenID._map[75] = "Colon"; - TokenID.Colon = 75; - TokenID._map[76] = "BarBar"; - TokenID.BarBar = 76; - TokenID._map[77] = "AmpersandAmpersand"; - TokenID.AmpersandAmpersand = 77; - TokenID._map[78] = "Bar"; - TokenID.Bar = 78; - TokenID._map[79] = "Caret"; - TokenID.Caret = 79; - TokenID._map[80] = "And"; - TokenID.And = 80; - TokenID._map[81] = "EqualsEquals"; - TokenID.EqualsEquals = 81; - TokenID._map[82] = "ExclamationEquals"; - TokenID.ExclamationEquals = 82; - TokenID._map[83] = "EqualsEqualsEquals"; - TokenID.EqualsEqualsEquals = 83; - TokenID._map[84] = "ExclamationEqualsEquals"; - TokenID.ExclamationEqualsEquals = 84; - TokenID._map[85] = "LessThan"; - TokenID.LessThan = 85; - TokenID._map[86] = "LessThanEquals"; - TokenID.LessThanEquals = 86; - TokenID._map[87] = "GreaterThan"; - TokenID.GreaterThan = 87; - TokenID._map[88] = "GreaterThanEquals"; - TokenID.GreaterThanEquals = 88; - TokenID._map[89] = "LessThanLessThan"; - TokenID.LessThanLessThan = 89; - TokenID._map[90] = "GreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThan = 90; - TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; - TokenID.GreaterThanGreaterThanGreaterThan = 91; - TokenID._map[92] = "Plus"; - TokenID.Plus = 92; - TokenID._map[93] = "Minus"; - TokenID.Minus = 93; - TokenID._map[94] = "Asterisk"; - TokenID.Asterisk = 94; - TokenID._map[95] = "Slash"; - TokenID.Slash = 95; - TokenID._map[96] = "Percent"; - TokenID.Percent = 96; - TokenID._map[97] = "Tilde"; - TokenID.Tilde = 97; - TokenID._map[98] = "Exclamation"; - TokenID.Exclamation = 98; - TokenID._map[99] = "PlusPlus"; - TokenID.PlusPlus = 99; - TokenID._map[100] = "MinusMinus"; - TokenID.MinusMinus = 100; - TokenID._map[101] = "Dot"; - TokenID.Dot = 101; - TokenID._map[102] = "DotDotDot"; - TokenID.DotDotDot = 102; - TokenID._map[103] = "Error"; - TokenID.Error = 103; - TokenID._map[104] = "EndOfFile"; - TokenID.EndOfFile = 104; - TokenID._map[105] = "EqualsGreaterThan"; - TokenID.EqualsGreaterThan = 105; - TokenID._map[106] = "Identifier"; - TokenID.Identifier = 106; - TokenID._map[107] = "StringLiteral"; - TokenID.StringLiteral = 107; - TokenID._map[108] = "RegularExpressionLiteral"; - TokenID.RegularExpressionLiteral = 108; - TokenID._map[109] = "NumberLiteral"; - TokenID.NumberLiteral = 109; - TokenID._map[110] = "Whitespace"; - TokenID.Whitespace = 110; - TokenID._map[111] = "Comment"; - TokenID.Comment = 111; - TokenID._map[112] = "Lim"; - TokenID.Lim = 112; - TokenID.LimFixed = TokenID.EqualsGreaterThan; - TokenID.LimKeyword = TokenID.Yield; - })(TypeScript.TokenID || (TypeScript.TokenID = {})); - var TokenID = TypeScript.TokenID; - TypeScript.tokenTable = new Array(); - TypeScript.nodeTypeTable = new Array(); - TypeScript.nodeTypeToTokTable = new Array(); - TypeScript.noRegexTable = new Array(); - TypeScript.noRegexTable[TokenID.Identifier] = true; - TypeScript.noRegexTable[TokenID.StringLiteral] = true; - TypeScript.noRegexTable[TokenID.NumberLiteral] = true; - TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; - TypeScript.noRegexTable[TokenID.This] = true; - TypeScript.noRegexTable[TokenID.PlusPlus] = true; - TypeScript.noRegexTable[TokenID.MinusMinus] = true; - TypeScript.noRegexTable[TokenID.CloseParen] = true; - TypeScript.noRegexTable[TokenID.CloseBracket] = true; - TypeScript.noRegexTable[TokenID.CloseBrace] = true; - TypeScript.noRegexTable[TokenID.True] = true; - TypeScript.noRegexTable[TokenID.False] = true; - (function (OperatorPrecedence) { - OperatorPrecedence._map = []; - OperatorPrecedence._map[0] = "None"; - OperatorPrecedence.None = 0; - OperatorPrecedence._map[1] = "Comma"; - OperatorPrecedence.Comma = 1; - OperatorPrecedence._map[2] = "Assignment"; - OperatorPrecedence.Assignment = 2; - OperatorPrecedence._map[3] = "Conditional"; - OperatorPrecedence.Conditional = 3; - OperatorPrecedence._map[4] = "LogicalOr"; - OperatorPrecedence.LogicalOr = 4; - OperatorPrecedence._map[5] = "LogicalAnd"; - OperatorPrecedence.LogicalAnd = 5; - OperatorPrecedence._map[6] = "BitwiseOr"; - OperatorPrecedence.BitwiseOr = 6; - OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; - OperatorPrecedence.BitwiseExclusiveOr = 7; - OperatorPrecedence._map[8] = "BitwiseAnd"; - OperatorPrecedence.BitwiseAnd = 8; - OperatorPrecedence._map[9] = "Equality"; - OperatorPrecedence.Equality = 9; - OperatorPrecedence._map[10] = "Relational"; - OperatorPrecedence.Relational = 10; - OperatorPrecedence._map[11] = "Shift"; - OperatorPrecedence.Shift = 11; - OperatorPrecedence._map[12] = "Additive"; - OperatorPrecedence.Additive = 12; - OperatorPrecedence._map[13] = "Multiplicative"; - OperatorPrecedence.Multiplicative = 13; - OperatorPrecedence._map[14] = "Unary"; - OperatorPrecedence.Unary = 14; - OperatorPrecedence._map[15] = "Lim"; - OperatorPrecedence.Lim = 15; - })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); - var OperatorPrecedence = TypeScript.OperatorPrecedence; - (function (Reservation) { - Reservation._map = []; - Reservation.None = 0; - Reservation.Javascript = 1; - Reservation.JavascriptFuture = 2; - Reservation.TypeScript = 4; - Reservation.JavascriptFutureStrict = 8; - Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; - Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; - Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; - })(TypeScript.Reservation || (TypeScript.Reservation = {})); - var Reservation = TypeScript.Reservation; - var TokenInfo = (function () { - function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - this.tokenId = tokenId; - this.reservation = reservation; - this.binopPrecedence = binopPrecedence; - this.binopNodeType = binopNodeType; - this.unopPrecedence = unopPrecedence; - this.unopNodeType = unopNodeType; - this.text = text; - this.ers = ers; - } - return TokenInfo; - })(); - TypeScript.TokenInfo = TokenInfo; - function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { - if(tokenId !== undefined) { - TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); - if(binopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[binopNodeType] = text; - TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; - } - if(unopNodeType != TypeScript.NodeType.None) { - TypeScript.nodeTypeTable[unopNodeType] = text; - } - } - } - setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); - setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); - setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); - setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); - setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); - setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); - setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); - setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); - setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); - setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); - setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); - setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); - setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); - setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); - setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); - setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); - setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); - setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); - setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); - setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); - setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); - setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); - setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); - setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); - setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); - setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); - setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); - setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); - setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); - setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); - setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); - function lookupToken(tokenId) { - return TypeScript.tokenTable[tokenId]; - } - TypeScript.lookupToken = lookupToken; - (function (TokenClass) { - TokenClass._map = []; - TokenClass._map[0] = "Punctuation"; - TokenClass.Punctuation = 0; - TokenClass._map[1] = "Keyword"; - TokenClass.Keyword = 1; - TokenClass._map[2] = "Operator"; - TokenClass.Operator = 2; - TokenClass._map[3] = "Comment"; - TokenClass.Comment = 3; - TokenClass._map[4] = "Whitespace"; - TokenClass.Whitespace = 4; - TokenClass._map[5] = "Identifier"; - TokenClass.Identifier = 5; - TokenClass._map[6] = "NumberLiteral"; - TokenClass.NumberLiteral = 6; - TokenClass._map[7] = "StringLiteral"; - TokenClass.StringLiteral = 7; - TokenClass._map[8] = "RegExpLiteral"; - TokenClass.RegExpLiteral = 8; - })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); - var TokenClass = TypeScript.TokenClass; - var SavedToken = (function () { - function SavedToken(tok, minChar, limChar) { - this.tok = tok; - this.minChar = minChar; - this.limChar = limChar; - } - return SavedToken; - })(); - TypeScript.SavedToken = SavedToken; - var Token = (function () { - function Token(tokenId) { - this.tokenId = tokenId; - } - Token.prototype.toString = function () { - return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; - }; - Token.prototype.print = function (line, outfile) { - outfile.WriteLine(this.toString() + ",on line" + line); - }; - Token.prototype.getText = function () { - return TypeScript.tokenTable[this.tokenId].text; - }; - Token.prototype.classification = function () { - if(this.tokenId <= TokenID.LimKeyword) { - return TokenClass.Keyword; - } else { - var tokenInfo = lookupToken(this.tokenId); - if(tokenInfo != undefined) { - if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { - return TokenClass.Operator; - } - } - } - return TokenClass.Punctuation; - }; - return Token; - })(); - TypeScript.Token = Token; - var NumberLiteralToken = (function (_super) { - __extends(NumberLiteralToken, _super); - function NumberLiteralToken(value, text) { - _super.call(this, TokenID.NumberLiteral); - this.value = value; - this.text = text; - } - NumberLiteralToken.prototype.getText = function () { - return this.text; - }; - NumberLiteralToken.prototype.classification = function () { - return TokenClass.NumberLiteral; - }; - return NumberLiteralToken; - })(Token); - TypeScript.NumberLiteralToken = NumberLiteralToken; - var StringLiteralToken = (function (_super) { - __extends(StringLiteralToken, _super); - function StringLiteralToken(value) { - _super.call(this, TokenID.StringLiteral); - this.value = value; - } - StringLiteralToken.prototype.getText = function () { - return this.value; - }; - StringLiteralToken.prototype.classification = function () { - return TokenClass.StringLiteral; - }; - return StringLiteralToken; - })(Token); - TypeScript.StringLiteralToken = StringLiteralToken; - var IdentifierToken = (function (_super) { - __extends(IdentifierToken, _super); - function IdentifierToken(value, hasEscapeSequence) { - _super.call(this, TokenID.Identifier); - this.value = value; - this.hasEscapeSequence = hasEscapeSequence; - } - IdentifierToken.prototype.getText = function () { - return this.value; - }; - IdentifierToken.prototype.classification = function () { - return TokenClass.Identifier; - }; - return IdentifierToken; - })(Token); - TypeScript.IdentifierToken = IdentifierToken; - var WhitespaceToken = (function (_super) { - __extends(WhitespaceToken, _super); - function WhitespaceToken(tokenId, value) { - _super.call(this, tokenId); - this.value = value; - } - WhitespaceToken.prototype.getText = function () { - return this.value; - }; - WhitespaceToken.prototype.classification = function () { - return TokenClass.Whitespace; - }; - return WhitespaceToken; - })(Token); - TypeScript.WhitespaceToken = WhitespaceToken; - var CommentToken = (function (_super) { - __extends(CommentToken, _super); - function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { - _super.call(this, tokenID); - this.value = value; - this.isBlock = isBlock; - this.startPos = startPos; - this.line = line; - this.endsLine = endsLine; - } - CommentToken.prototype.getText = function () { - return this.value; - }; - CommentToken.prototype.classification = function () { - return TokenClass.Comment; - }; - return CommentToken; - })(Token); - TypeScript.CommentToken = CommentToken; - var RegularExpressionLiteralToken = (function (_super) { - __extends(RegularExpressionLiteralToken, _super); - function RegularExpressionLiteralToken(text) { - _super.call(this, TokenID.RegularExpressionLiteral); - this.text = text; - } - RegularExpressionLiteralToken.prototype.getText = function () { - return this.text; - }; - RegularExpressionLiteralToken.prototype.classification = function () { - return TokenClass.RegExpLiteral; - }; - return RegularExpressionLiteralToken; - })(Token); - TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; - TypeScript.staticTokens = new Array(); - function initializeStaticTokens() { - for(var i = 0; i <= TokenID.LimFixed; i++) { - TypeScript.staticTokens[i] = new Token(i); - } - } - TypeScript.initializeStaticTokens = initializeStaticTokens; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ArrayCache = (function () { - function ArrayCache() { - this.arrayBase = null; - } - ArrayCache.prototype.specialize = function (arrInstType, checker) { - if(this.arrayBase == null) { - this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); - } - return this.arrayBase; - }; - return ArrayCache; - })(); - TypeScript.ArrayCache = ArrayCache; - var TypeComparisonInfo = (function () { - function TypeComparisonInfo() { - this.onlyCaptureFirstError = false; - this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; - this.message = ""; - } - TypeComparisonInfo.prototype.addMessageToFront = function (message) { - if(!this.onlyCaptureFirstError) { - this.message = this.message ? message + ":\n\t" + this.message : message; - } else { - this.setMessage(message); - } - }; - TypeComparisonInfo.prototype.setMessage = function (message) { - this.message = message; - }; - return TypeComparisonInfo; - })(); - TypeScript.TypeComparisonInfo = TypeComparisonInfo; - (function (TypeCheckCollectionMode) { - TypeCheckCollectionMode._map = []; - TypeCheckCollectionMode._map[0] = "Resident"; - TypeCheckCollectionMode.Resident = 0; - TypeCheckCollectionMode._map[1] = "Transient"; - TypeCheckCollectionMode.Transient = 1; - })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); - var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; - var PersistentGlobalTypeState = (function () { - function PersistentGlobalTypeState(errorReporter) { - this.errorReporter = errorReporter; - this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.globals = null; - this.globalTypes = null; - this.ambientGlobals = null; - this.ambientGlobalTypes = null; - this.residentGlobalValues = new TypeScript.StringHashTable(); - this.residentGlobalTypes = new TypeScript.StringHashTable(); - this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); - this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); - this.residentTypeCheck = true; - this.mod = null; - this.gloMod = null; - this.wildElm = null; - this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); - this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); - this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); - this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); - this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); - var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); - var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); - var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); - this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); - this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); - this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); - this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); - this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); - this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); - this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); - this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); - this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); - this.setCollectionMode(TypeCheckCollectionMode.Resident); - this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); - this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); - this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); - this.mod.members = dualGlobalScopedMembers; - this.mod.ambientMembers = dualGlobalScopedAmbientMembers; - this.mod.containedScope = this.globalScope; - this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); - this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); - this.defineGlobalValue("undefined", this.undefinedType); - } - PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { - var primitive = new TypeScript.Type(); - primitive.primitiveTypeClass = flags; - var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); - symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - primitive.symbol = symbol; - this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); - return primitive; - }; - PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { - this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; - }; - PersistentGlobalTypeState.prototype.refreshPersistentState = function () { - this.globals = new TypeScript.StringHashTable(); - this.globalTypes = new TypeScript.StringHashTable(); - this.ambientGlobals = new TypeScript.StringHashTable(); - this.ambientGlobalTypes = new TypeScript.StringHashTable(); - this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); - this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); - this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); - this.globalTypes.add("number", this.doubleType.symbol); - this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); - this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); - this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); - this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); - this.dualGlobalValues.secondaryTable = this.globals; - this.dualGlobalTypes.secondaryTable = this.globalTypes; - this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; - this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; - }; - PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { - var valueLocation = new TypeScript.ValueLocation(); - valueLocation.typeLink = new TypeScript.TypeLink(); - var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); - sym.setType(type); - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - sym.container = this.gloMod; - this.importedGlobalsTable.addPublicMember(name, sym); - }; - return PersistentGlobalTypeState; - })(); - TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; - var ContextualTypeContext = (function () { - function ContextualTypeContext(contextualType, provisional, contextID) { - this.contextualType = contextualType; - this.provisional = provisional; - this.contextID = contextID; - this.targetSig = null; - this.targetThis = null; - this.targetAccessorType = null; - } - return ContextualTypeContext; - })(); - TypeScript.ContextualTypeContext = ContextualTypeContext; - var ContextualTypingContextStack = (function () { - function ContextualTypingContextStack(checker) { - this.checker = checker; - this.contextStack = []; - this.hadProvisionalErrors = false; - } - ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; - ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { - this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); - this.checker.errorReporter.pushToErrorSink = provisional; - }; - ContextualTypingContextStack.prototype.popContextualType = function () { - var tc = this.contextStack.pop(); - this.checker.errorReporter.pushToErrorSink = this.isProvisional(); - this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); - this.checker.errorReporter.freeCapturedErrors(); - return tc; - }; - ContextualTypingContextStack.prototype.getContextualType = function () { - return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); - }; - ContextualTypingContextStack.prototype.getContextID = function () { - return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); - }; - ContextualTypingContextStack.prototype.isProvisional = function () { - return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); - }; - return ContextualTypingContextStack; - })(); - TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; - var TypeChecker = (function () { - function TypeChecker(persistentState) { - this.persistentState = persistentState; - this.errorReporter = null; - this.checkControlFlow = false; - this.printControlFlowGraph = false; - this.checkControlFlowUseDef = false; - this.styleSettings = null; - this.units = null; - this.anon = "_anonymous"; - this.locationInfo = null; - this.typeFlow = null; - this.currentCompareA = null; - this.currentCompareB = null; - this.currentModDecl = null; - this.inBind = false; - this.inWith = false; - this.errorsOnWith = true; - this.currentContextualTypeContext = null; - this.resolvingBases = false; - this.canCallDefinitionSignature = false; - this.assignableCache = { - }; - this.subtypeCache = { - }; - this.identicalCache = { - }; - this.provisionalStartedTypecheckObjects = []; - this.mustCaptureGlobalThis = false; - this.voidType = this.persistentState.voidType; - this.booleanType = this.persistentState.booleanType; - this.numberType = this.persistentState.doubleType; - this.stringType = this.persistentState.stringType; - this.anyType = this.persistentState.anyType; - this.nullType = this.persistentState.nullType; - this.undefinedType = this.persistentState.undefinedType; - this.globals = this.persistentState.dualGlobalValues; - this.globalTypes = this.persistentState.dualGlobalTypes; - this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; - this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; - this.gloModType = this.persistentState.mod; - this.gloMod = this.persistentState.gloMod; - this.wildElm = this.persistentState.wildElm; - this.globalScope = this.persistentState.globalScope; - this.typingContextStack = new ContextualTypingContextStack(this); - } - TypeChecker.prototype.setStyleOptions = function (style) { - this.styleSettings = style; - }; - TypeChecker.prototype.setContextualType = function (type, provisional) { - this.typingContextStack.pushContextualType(type, provisional); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.unsetContextualType = function () { - var lastTC = this.typingContextStack.popContextualType(); - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - return lastTC; - }; - TypeChecker.prototype.hadProvisionalErrors = function () { - return this.typingContextStack.hadProvisionalErrors; - }; - TypeChecker.prototype.resetProvisionalErrors = function () { - if(!this.typingContextStack.getContextualType()) { - this.typingContextStack.hadProvisionalErrors = false; - } - }; - TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { - if(condition) { - this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); - } - this.typeFlow.typeCheck(ast); - if(condition) { - this.unsetContextualType(); - } - }; - TypeChecker.prototype.resetTargetType = function () { - this.currentContextualTypeContext = this.typingContextStack.getContextualType(); - }; - TypeChecker.prototype.killCurrentContextualType = function () { - this.currentContextualTypeContext = null; - this.errorReporter.pushToErrorSink = false; - }; - TypeChecker.prototype.hasTargetType = function () { - return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; - }; - TypeChecker.prototype.getTargetTypeContext = function () { - return this.currentContextualTypeContext; - }; - TypeChecker.prototype.inProvisionalTypecheckMode = function () { - return this.typingContextStack.isProvisional(); - }; - TypeChecker.prototype.getTypeCheckFinishedStatus = function () { - if(this.inProvisionalTypecheckMode()) { - return this.typingContextStack.getContextID(); - } - return TypeScript.TypeCheckStatus.Finished; - }; - TypeChecker.prototype.typeStatusIsFinished = function (status) { - return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); - }; - TypeChecker.prototype.addStartedPTO = function (pto) { - if(this.inProvisionalTypecheckMode()) { - this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; - } - }; - TypeChecker.prototype.cleanStartedPTO = function () { - for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { - if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { - this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; - } - } - this.provisionalStartedTypecheckObjects = []; - }; - TypeChecker.prototype.collectTypes = function (ast) { - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - this.locationInfo = script.locationInfo; - } - var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); - var context = new TypeScript.TypeCollectionContext(globalChain, this); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); - }; - TypeChecker.prototype.makeArrayType = function (type) { - if(type.arrayCache == null) { - type.arrayCache = new ArrayCache(); - type.arrayCache.arrayType = new TypeScript.Type(); - type.arrayCache.arrayType.elementType = type; - type.arrayCache.arrayType.symbol = type.symbol; - } - return type.arrayCache.arrayType; - }; - TypeChecker.prototype.getParameterList = function (funcDecl, container) { - var args = funcDecl.arguments; - var parameterTable = null; - var parameterBuilder = null; - var len = args.members.length; - var nonOptionalParams = 0; - var result = []; - if(len > 0) { - parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); - for(var i = 0; i < len; i++) { - var parameter = args.members[i]; - var paramDef = new TypeScript.ValueLocation(); - var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); - parameterSymbol.declAST = parameter; - parameterSymbol.funcDecl = funcDecl; - parameter.id.sym = parameterSymbol; - parameter.sym = parameterSymbol; - paramDef.symbol = parameterSymbol; - paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); - parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); - result[result.length] = parameterSymbol; - if(!parameter.isOptionalArg()) { - nonOptionalParams++; - } - } - } - return { - parameters: result, - nonOptionalParameterCount: nonOptionalParams - }; - }; - TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isDefinition = !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature); - var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var isGlobal = container == this.gloMod; - var signature = new TypeScript.Signature(); - var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; - if(funcDecl.returnTypeAnnotation || isDefinition) { - signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); - } else { - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = this.anyType; - } - signature.hasVariableArgList = funcDecl.variableArgList; - var sigData = this.getParameterList(funcDecl, container); - signature.parameters = sigData.parameters; - signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; - funcDecl.signature = signature; - signature.declAST = funcDecl; - var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); - if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); - } - var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); - if(isConstructor) { - if(groupType.construct == null) { - groupType.construct = new TypeScript.SignatureGroup(); - } - groupType.construct.addSignature(signature); - groupType.construct.hasImplementation = !(funcDecl.isSignature()); - if(groupType.construct.hasImplementation) { - groupType.setHasImplementation(); - } - } else if(funcDecl.isIndexerMember()) { - if(groupType.index == null) { - groupType.index = new TypeScript.SignatureGroup(); - groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; - } - groupType.index.addSignature(signature); - groupType.index.hasImplementation = !(funcDecl.isSignature()); - if(groupType.index.hasImplementation) { - groupType.setHasImplementation(); - } - } else { - if(groupType.call == null) { - groupType.call = new TypeScript.SignatureGroup(); - } - groupType.call.addSignature(signature); - groupType.call.hasImplementation = !(funcDecl.isSignature()); - if(groupType.call.hasImplementation) { - groupType.setHasImplementation(); - } - } - var instanceType = groupType.instanceType; - var funcName = null; - var usedHint = false; - if(funcDecl.name && !funcDecl.name.isMissing()) { - funcName = funcDecl.name.text; - } else if(funcDecl.hint) { - funcName = funcDecl.hint; - usedHint = true; - } - if(groupType.symbol == null) { - groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); - if(!useOverloadGroupSym) { - groupType.symbol.declAST = funcDecl; - } - } - if(isStatic) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Static; - } - if(isAmbient) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; - } - if(isPrivate) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Private; - } - groupType.symbol.isMethod = funcDecl.isMethod(); - if(groupType.symbol.isMethod) { - groupType.symbol.flags |= TypeScript.SymbolFlags.Property; - } - funcDecl.type = groupType; - if(!isConstructor) { - if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { - if(addToScope) { - if(funcDecl.isMethod() && isStatic) { - if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { - this.errorReporter.duplicateIdentifier(funcDecl, funcName); - } - groupType.symbol.container = container; - } else if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { - scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); - } - } else if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } else if(!funcDecl.isSpecialFn()) { - groupType.symbol.container = container; - } - } - if(useOverloadGroupSym) { - var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; - var classType = groupType; - if(classType != overloadGroupType) { - if(classType.construct == null) { - if(overloadGroupType && overloadGroupType.construct) { - classType.construct = overloadGroupType.construct; - } else { - classType.construct = new TypeScript.SignatureGroup(); - } - } else if(overloadGroupType) { - if(overloadGroupType.construct) { - classType.construct.signatures.concat(overloadGroupType.construct.signatures); - } - } - if(overloadGroupType) { - if(classType.call == null) { - classType.call = overloadGroupType.call; - } else if(overloadGroupType.call) { - classType.call.signatures.concat(overloadGroupType.call.signatures); - } - if(!isStatic) { - if(classType.instanceType == null) { - classType.instanceType = overloadGroupType.instanceType; - } - var instanceType = classType.instanceType; - if(instanceType) { - if(instanceType.call == null) { - instanceType.call = overloadGroupType.call; - } else if(overloadGroupType.call) { - instanceType.call.signatures.concat(overloadGroupType.call.signatures); - } - } - } - if(classType.index == null) { - classType.index = overloadGroupType.index; - } else if(overloadGroupType.index) { - classType.index.signatures.concat(overloadGroupType.index.signatures); - } - } - } - } - return signature; - }; - TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { - var accessorSym = null; - var sig = funcDecl.signature; - var nameText = funcDecl.name.text; - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - if(fgSym == null) { - var field = new TypeScript.ValueLocation(); - accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); - field.symbol = accessorSym; - accessorSym.declAST = funcDecl; - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = sig.declAST.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = sig.declAST.type.symbol; - } - field.typeLink = TypeScript.getTypeLink(null, this, false); - if(addToMembers) { - if(enclosingClass) { - if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { - this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); - } - accessorSym.container = enclosingClass.symbol; - } else { - this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); - } - } else { - scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); - } - if(isClassProperty) { - accessorSym.flags |= TypeScript.SymbolFlags.Property; - } - if(isStatic) { - accessorSym.flags |= TypeScript.SymbolFlags.Static; - } - if(isPrivate) { - accessorSym.flags |= TypeScript.SymbolFlags.Private; - } else { - accessorSym.flags |= TypeScript.SymbolFlags.Public; - } - } else { - accessorSym = (fgSym); - if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { - this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - if(accessorSym.getter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); - } - accessorSym.getter = funcDecl.type.symbol; - } else { - if(accessorSym.setter) { - this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); - } - accessorSym.setter = funcDecl.type.symbol; - } - } - return accessorSym; - }; - TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { - resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); - var i = 0; - var parent; - if(type.extendsList) { - for(var len = type.extendsList.length; i < len; i++) { - parent = type.extendsList[i]; - if(baseContext.baseId == parent.typeID) { - this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); - parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - break; - } - this.addBases(resultScope, parent, baseContext); - } - } - }; - TypeChecker.prototype.scopeOf = function (type) { - var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); - var baseContext = { - base: type.symbol && type.symbol.name ? type.symbol.name : "{}", - baseId: type.typeID - }; - this.addBases(resultScope, type, baseContext); - return resultScope; - }; - TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { - var symbol = null; - if(containingType.containedScope) { - symbol = containingType.containedScope.find(name, false, true); - } else if(containingType.members) { - symbol = containingType.members.allMembers.lookup(name); - if(symbol == null && containingType.ambientMembers) { - symbol = containingType.ambientMembers.allMembers.lookup(name); - } - } - if(symbol == null || !symbol.isType()) { - var typeMembers = containingType.getAllEnclosedTypes(); - var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); - if(typeMembers) { - symbol = typeMembers.allMembers.lookup(name); - if(symbol == null && ambientTypeMembers) { - symbol = ambientTypeMembers.allMembers.lookup(name); - } - } - } - if(symbol && symbol.isType()) { - return symbol; - } else { - return null; - } - }; - TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { - var originalIdText = idText; - var symbol = search(idText); - if(symbol == null) { - if(!symbol) { - idText = TypeScript.swapQuotes(originalIdText); - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".str"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; - symbol = search(idText); - } - if(!symbol) { - idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; - symbol = search(idText); - } - if(!symbol && !TypeScript.isRelative(originalIdText)) { - idText = originalIdText; - var strippedIdText = TypeScript.stripQuotes(idText); - var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); - while(symbol == null && path != "") { - idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); - symbol = search(idText); - if(symbol == null) { - idText = TypeScript.changePathToSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDTS(idText); - symbol = search(idText); - } - if(symbol == null) { - idText = TypeScript.changePathToDSTR(idText); - symbol = search(idText); - } - if(symbol == null) { - if(path === '/') { - path = ''; - } else { - path = TypeScript.normalizePath(path + ".."); - path = path && path != '/' ? path + '/' : path; - } - } - } - } - } - return symbol; - }; - TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { - var lhs = dotNode.operand1; - var rhs = dotNode.operand2; - var resultType = this.anyType; - var lhsType = this.anyType; - if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { - if(lhs.nodeType == TypeScript.NodeType.Dot) { - lhsType = this.resolveTypeMember(scope, lhs); - } else if(lhs.nodeType == TypeScript.NodeType.Name) { - var identifier = lhs; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else if(symbol.isType()) { - var typeSymbol = symbol; - if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { - var modPath = (typeSymbol.aliasLink.alias).text; - var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { - return scope.find(id, false, true); - }); - if(modSym) { - typeSymbol.type = modSym.getType(); - } - } - if(TypeScript.optimizeModuleCodeGen && symbol) { - var symType = symbol.getType(); - if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; - } - } - } - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - lhsType = symbol.getType(); - identifier.sym = symbol; - } else { - this.errorReporter.simpleError(lhs, "Expected type"); - } - } - if(!lhsType) { - lhsType = this.anyType; - } - if(lhsType != this.anyType) { - var rhsIdentifier = rhs; - var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); - if(resultSymbol == null) { - resultType = this.anyType; - this.errorReporter.simpleError(dotNode, "Expected type"); - } else { - resultType = resultSymbol.getType(); - if(!resultSymbol.visible(scope, this)) { - this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); - } - } - rhsIdentifier.sym = resultType.symbol; - } - } - if(resultType.isClass()) { - resultType = resultType.instanceType; - } - return resultType; - }; - TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { - var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; - var signatures; - if(funcDecl.isConstructMember()) { - signatures = functionGroupSymbol.type.construct.signatures; - } else if(funcDecl.isIndexerMember()) { - signatures = functionGroupSymbol.type.getInstanceType().index.signatures; - } else { - signatures = functionGroupSymbol.type.call.signatures; - } - var signature = signatures[signatures.length - 1]; - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var paramSym = signature.parameters[i]; - this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); - } - if(len && funcDecl.variableArgList) { - if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { - this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); - signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); - } - } - this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); - return functionGroupSymbol; - }; - TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = varDecl; - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); - this.resolveTypeLink(scope, field.typeLink, true); - varDecl.sym = fieldSymbol; - varDecl.type = field.typeLink.type; - return fieldSymbol; - }; - TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { - var arrayCount = 0; - if(typeLink.type == null) { - var ast = typeLink.ast; - if(ast) { - while(typeLink.type == null) { - switch(ast.nodeType) { - case TypeScript.NodeType.Name: - var identifier = ast; - var symbol = scope.find(identifier.text, false, true); - if(symbol == null) { - typeLink.type = this.anyType; - this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); - } else if(symbol.isType()) { - if(!symbol.visible(scope, this)) { - this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); - } - identifier.sym = symbol; - typeLink.type = symbol.getType(); - if(typeLink.type) { - if(typeLink.type.isClass()) { - typeLink.type = typeLink.type.instanceType; - } - } else { - typeLink.type = this.anyType; - } - } else { - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - } - break; - case TypeScript.NodeType.Dot: - typeLink.type = this.resolveTypeMember(scope, ast); - break; - case TypeScript.NodeType.TypeRef: - var typeRef = ast; - arrayCount = typeRef.arrayCount; - ast = typeRef.term; - if(ast == null) { - typeLink.type = this.anyType; - } - break; - case TypeScript.NodeType.InterfaceDeclaration: - var interfaceDecl = ast; - var interfaceType = new TypeScript.Type(); - var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); - interfaceType.containedScope.container = interfaceSymbol; - interfaceType.memberScope = interfaceType.containedScope; - var memberList = interfaceDecl.members; - var props = memberList.members; - var propsLen = props.length; - for(var j = 0; j < propsLen; j++) { - var propDecl = props[j]; - var propSym = null; - var addMember = true; - var id = null; - if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = propDecl; - id = funcDecl.name; - propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); - addMember = (propSym == null); - if(funcDecl.isSpecialFn()) { - addMember = false; - propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); - } else { - propSym = this.resolveFuncDecl(funcDecl, scope, propSym); - } - funcDecl.type = (propSym).type; - } else { - id = (propDecl).id; - propSym = this.resolveVarDecl(propDecl, scope); - addMember = !id.isMissing(); - } - if(addMember) { - if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { - propSym.flags |= TypeScript.SymbolFlags.Optional; - } - if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { - this.errorReporter.duplicateIdentifier(ast, propSym.name); - } - } - } - ast.type = interfaceType; - typeLink.type = interfaceType; - break; - case TypeScript.NodeType.FuncDecl: - var tsym = this.resolveFuncDecl(ast, scope, null); - typeLink.type = tsym.type; - break; - default: - typeLink.type = this.anyType; - this.errorReporter.simpleError(ast, "Expected type"); - break; - } - } - } - for(var count = arrayCount; count > 0; count--) { - typeLink.type = this.makeArrayType(typeLink.type); - } - if(supplyVar && (typeLink.type == null)) { - typeLink.type = this.anyType; - } - if(typeLink.ast) { - typeLink.ast.type = typeLink.type; - } - } - }; - TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { - this.resolvingBases = true; - this.resolveTypeLink(scope, typeLink, true); - this.resolvingBases = false; - var extendsType = null; - if(typeLink.type.isClass()) { - extendsType = typeLink.type.instanceType; - } else { - extendsType = typeLink.type; - } - return extendsType; - }; - TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { - if(signatures.length == 1) { - return { - sig: signatures[0].signature, - ambiguous: false - }; - } - var best = signatures[0]; - var Q = null; - var AType = null; - var PType = null; - var QType = null; - var ambiguous = false; - for(var qSig = 1; qSig < signatures.length; qSig++) { - Q = signatures[qSig]; - var i = 0; - for(i = 0; args && i < args.members.length; i++) { - AType = args.members[i].type; - PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; - QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; - if(this.typesAreIdentical(PType, QType)) { - continue; - } else if(this.typesAreIdentical(AType, PType)) { - break; - } else if(this.typesAreIdentical(AType, QType)) { - best = Q; - break; - } else if(this.sourceIsSubtypeOfTarget(PType, QType)) { - break; - } else if(this.sourceIsSubtypeOfTarget(QType, PType)) { - best = Q; - break; - } else if(Q.hadProvisionalErrors) { - break; - } else if(best.hadProvisionalErrors) { - best = Q; - break; - } - } - if(!args || i == args.members.length) { - var collection = { - getLength: function () { - return 2; - }, - setTypeAtIndex: function (index, type) { - }, - getTypeAtIndex: function (index) { - return index ? Q.signature.returnType.type : best.signature.returnType.type; - } - }; - var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); - ambiguous = !bct; - } else { - ambiguous = false; - } - } - return { - sig: best.signature, - ambiguous: ambiguous - }; - }; - TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { - var applicableSigs = []; - var memberType = null; - var miss = false; - var cxt = null; - var hadProvisionalErrors = false; - for(var i = 0; i < signatures.length; i++) { - miss = false; - for(var j = 0; j < args.members.length; j++) { - if(j >= signatures[i].parameters.length) { - continue; - } - memberType = signatures[i].parameters[j].getType(); - if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { - memberType = memberType.elementType; - } - if(memberType == this.anyType) { - continue; - } else if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { - if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { - continue; - } - if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { - if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { - this.typeFlow.typeCheck(args.members[j]); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - break; - } - } else { - break; - } - } else { - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } else if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { - if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - miss = true; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } else if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { - if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { - continue; - } - this.typeCheckWithContextualType(memberType, true, true, args.members[j]); - this.cleanStartedPTO(); - hadProvisionalErrors = this.hadProvisionalErrors(); - if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); - } - break; - } - this.resetProvisionalErrors(); - if(miss) { - break; - } - } - } - if(j == args.members.length) { - applicableSigs[applicableSigs.length] = { - signature: signatures[i], - hadProvisionalErrors: hadProvisionalErrors - }; - } - hadProvisionalErrors = false; - } - return applicableSigs; - }; - TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { - if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { - return false; - } - beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); - if(!beStringent) { - return true; - } - if(!funcDecl.signature) { - this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); - this.typeFlow.typeCheck(funcDecl); - } - var signature = funcDecl.signature; - var paramLen = signature.parameters.length; - for(var i = 0; i < paramLen; i++) { - var param = signature.parameters[i]; - var symbol = param; - var argDecl = symbol.declAST; - if(beStringent && argDecl.typeExpr) { - return false; - } - } - if(candidateType.construct && candidateType.call) { - return false; - } - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - if(!candidateSigs || candidateSigs.signatures.length > 1) { - return false; - } - return true; - }; - TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { - if(targetType == this.typeFlow.objectInterfaceType) { - return true; - } - var memberDecls = objectLit.operand; - if(!(memberDecls && targetType.memberScope)) { - return false; - } - var id = null; - var targetMember = null; - var text = ""; - var foundSyms = { - }; - for(var i = 0; i < memberDecls.members.length; i++) { - id = (memberDecls.members[i]).operand1; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - return false; - } - targetMember = targetType.memberScope.find(text, true, false); - if(!targetMember) { - return false; - } - foundSyms[text] = true; - } - var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); - for(var i = 0; i < targetMembers.length; i++) { - var memberName = targetMembers[i]; - var memberSym = targetType.memberScope.find(memberName, true, false); - if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.widenType = function (t) { - if(t == this.undefinedType || t == this.nullType) { - return this.anyType; - } - return t; - }; - TypeChecker.prototype.isNullOrUndefinedType = function (t) { - return t == this.undefinedType || t == this.nullType; - }; - TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { - var i = 0; - var len = collection.getLength(); - var nlastChecked = 0; - var bestCommonType = initialType; - if(targetType) { - bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; - } - var convergenceType = bestCommonType; - while(nlastChecked < len) { - for(i = 0; i < len; i++) { - if(i == nlastChecked) { - continue; - } - if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { - convergenceType = bestCommonType; - } - if(bestCommonType == this.anyType || bestCommonType == null) { - break; - } else if(targetType) { - collection.setTypeAtIndex(i, targetType); - } - } - if(convergenceType && bestCommonType) { - break; - } - nlastChecked++; - if(nlastChecked < len) { - convergenceType = collection.getTypeAtIndex(nlastChecked); - } - } - return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); - }; - TypeChecker.prototype.typesAreIdentical = function (t1, t2) { - if(t1 == t2) { - return true; - } - if(!t1 || !t2) { - return false; - } - if(t1.isClass() || t1.isClassInstance()) { - return false; - } - var comboId = (t2.typeID << 16) | t1.typeID; - if(this.identicalCache[comboId]) { - return true; - } - if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(t1.isArray() || t2.isArray()) { - if(!(t1.isArray() && t2.isArray())) { - return false; - } - this.identicalCache[comboId] = false; - var ret = this.typesAreIdentical(t1.elementType, t2.elementType); - if(ret) { - this.subtypeCache[comboId] = true; - } else { - this.subtypeCache[comboId] = undefined; - } - return ret; - } - if(t1.primitiveTypeClass != t2.primitiveTypeClass) { - return false; - } - this.identicalCache[comboId] = false; - if(t1.memberScope && t2.memberScope) { - var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); - var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); - if(t1MemberKeys.length != t2MemberKeys.length) { - this.identicalCache[comboId] = undefined; - return false; - } - var t1MemberSymbol = null; - var t2MemberSymbol = null; - var t1MemberType = null; - var t2MemberType = null; - for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { - if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); - t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); - if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { - this.identicalCache[comboId] = undefined; - return false; - } - t1MemberType = t1MemberSymbol.getType(); - t2MemberType = t2MemberSymbol.getType(); - if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { - continue; - } - if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { - this.identicalCache[comboId] = undefined; - return false; - } - } - } else if(t1.memberScope || t2.memberScope) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { - this.identicalCache[comboId] = undefined; - return false; - } - if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { - this.identicalCache[comboId] = undefined; - return false; - } - this.identicalCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { - if(sg1 == sg2) { - return true; - } - if(!sg1 || !sg2) { - return false; - } - if(sg1.signatures.length != sg2.signatures.length) { - return false; - } - var sig1 = null; - var sig2 = null; - var sigsMatch = false; - for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { - sig1 = sg1.signatures[iSig1]; - for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { - sig2 = sg2.signatures[iSig2]; - if(this.signaturesAreIdentical(sig1, sig2)) { - sigsMatch = true; - break; - } - } - if(sigsMatch) { - sigsMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { - if(s1.hasVariableArgList != s2.hasVariableArgList) { - return false; - } - if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { - return false; - } - if(s1.parameters.length != s2.parameters.length) { - return false; - } - if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { - return false; - } - for(var iParam = 0; iParam < s1.parameters.length; iParam++) { - if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { - return false; - } - } - return true; - }; - TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { - return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { - return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { - return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); - }; - TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { - if(source == target) { - return true; - } - if(!(source && target)) { - return true; - } - var comboId = (source.typeID << 16) | target.typeID; - if(comparisonCache[comboId] != undefined) { - return true; - } - if(assignableTo) { - if(source == this.anyType || target == this.anyType) { - return true; - } - } else { - if(target == this.anyType) { - return true; - } - } - if(source == this.undefinedType) { - return true; - } - if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { - return true; - } - if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return true; - } - if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { - return false; - } - if(source.isArray() || target.isArray()) { - if(!(source.isArray() && target.isArray())) { - return false; - } - comparisonCache[comboId] = false; - var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); - if(ret) { - comparisonCache[comboId] = true; - } else { - comparisonCache[comboId] = undefined; - } - return ret; - } - if(source.primitiveTypeClass != target.primitiveTypeClass) { - if(target.primitiveTypeClass == TypeScript.Primitive.None) { - if(source == this.numberType && this.typeFlow.numberInterfaceType) { - source = this.typeFlow.numberInterfaceType; - } else if(source == this.stringType && this.typeFlow.stringInterfaceType) { - source = this.typeFlow.stringInterfaceType; - } else if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { - source = this.typeFlow.booleanInterfaceType; - } else { - return false; - } - } else { - return false; - } - } - comparisonCache[comboId] = false; - if(source.hasBase(target)) { - comparisonCache[comboId] = true; - return true; - } - if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { - return true; - } - if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { - return true; - } - if(target.isClass() || target.isClassInstance()) { - comparisonCache[comboId] = undefined; - return false; - } - if(target.memberScope && source.memberScope) { - var mPropKeys = target.memberScope.getAllValueSymbolNames(true); - var mProp = null; - var nProp = null; - var mPropType = null; - var nPropType = null; - var inferenceSymbol = null; - for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { - mProp = target.memberScope.find(mPropKeys[iMProp], false, false); - nProp = source.memberScope.find(mPropKeys[iMProp], false, false); - if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { - continue; - } - if(mProp.isInferenceSymbol()) { - inferenceSymbol = mProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(mProp.declAST); - } - } - mPropType = mProp.getType(); - if(!nProp) { - if(this.typeFlow.objectInterfaceType) { - nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { - nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); - } - if(!nProp) { - if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; - comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); - } - return false; - } else { - continue; - } - } - } - } - if(nProp.isInferenceSymbol()) { - inferenceSymbol = nProp; - if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - this.typeFlow.typeCheck(nProp.declAST); - } - } - nPropType = nProp.getType(); - if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { - continue; - } - if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { - comparisonCache[comboId] = undefined; - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; - comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } - return false; - } - } - } - if(source.call || target.call) { - if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.call && target.call) { - comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.call ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(source.construct || target.construct) { - if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - if(source.construct && target.construct) { - comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - } else { - var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); - var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); - comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); - } - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - if(target.index) { - var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; - var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; - if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; - } - comparisonCache[comboId] = undefined; - return false; - } - } - comparisonCache[comboId] = true; - return true; - }; - TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { - if(sourceSG == targetSG) { - return true; - } - if(!(sourceSG && targetSG)) { - return false; - } - var mSig = null; - var nSig = null; - var foundMatch = false; - for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { - mSig = targetSG.signatures[iMSig]; - for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { - nSig = sourceSG.signatures[iNSig]; - if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { - foundMatch = true; - break; - } - } - if(foundMatch) { - foundMatch = false; - continue; - } - return false; - } - return true; - }; - TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { - if(!sourceSig.parameters || !targetSig.parameters) { - return false; - } - var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; - var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; - if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; - comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); - } - return false; - } - var sourceReturnType = sourceSig.returnType.type; - var targetReturnType = targetSig.returnType.type; - if(targetReturnType != this.voidType) { - if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; - } - return false; - } - } - var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; - var sourceParamType = null; - var targetParamType = null; - var sourceParamName = ""; - var targetParamName = ""; - for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { - if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } else if(iSource == sourceVarArgCount) { - sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; - if(sourceParamType.elementType) { - sourceParamType = sourceParamType.elementType; - } - sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; - } - if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } else if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { - targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; - if(targetParamType.elementType) { - targetParamType = targetParamType.elementType; - } - targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; - } - if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { - if(comparisonInfo) { - comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; - } - return false; - } - } - return true; - }; - return TypeChecker; - })(); - TypeScript.TypeChecker = TypeChecker; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var Continuation = (function () { - function Continuation(normalBlock) { - this.normalBlock = normalBlock; - this.exceptionBlock = -1; - } - return Continuation; - })(); - TypeScript.Continuation = Continuation; - function getBaseTypeLinks(bases, baseTypeLinks) { - if(bases) { - var len = bases.members.length; - if(baseTypeLinks == null) { - baseTypeLinks = new Array(); - } - for(var i = 0; i < len; i++) { - var baseExpr = bases.members[i]; - var name = baseExpr; - var typeLink = new TypeScript.TypeLink(); - typeLink.ast = name; - baseTypeLinks[baseTypeLinks.length] = typeLink; - } - } - return baseTypeLinks; - } - function getBases(type, typeDecl) { - type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); - type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); - } - function addPrototypeField(classType, ast, context) { - var field = new TypeScript.ValueLocation(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.ast = ast; - field.typeLink.type = classType.instanceType; - var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - classType.members.addPublicMember("prototype", fieldSymbol); - } - function createNewConstructGroupForType(type) { - var signature = new TypeScript.Signature(); - signature.returnType = new TypeScript.TypeLink(); - signature.returnType.type = type.instanceType; - signature.parameters = []; - type.construct = new TypeScript.SignatureGroup(); - type.construct.addSignature(signature); - } - TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; - function cloneParentConstructGroupForChildType(child, parent) { - child.construct = new TypeScript.SignatureGroup(); - var sig = null; - if(!parent.construct) { - createNewConstructGroupForType(parent); - } - for(var i = 0; i < parent.construct.signatures.length; i++) { - sig = new TypeScript.Signature(); - sig.parameters = parent.construct.signatures[i].parameters; - sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; - sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; - sig.declAST = parent.construct.signatures[i].declAST; - sig.returnType = new TypeScript.TypeLink(); - sig.returnType.type = child.instanceType; - child.construct.addSignature(sig); - } - } - TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; - TypeScript.globalId = "__GLO"; - function findTypeSymbolInScopeChain(name, scopeChain) { - var symbol = scopeChain.scope.find(name, false, true); - if(symbol == null && scopeChain.previous) { - symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); - } - return symbol; - } - function findSymbolFromAlias(alias, context) { - var symbol = null; - switch(alias.nodeType) { - case TypeScript.NodeType.Name: - var name = (alias).text; - var isDynamic = TypeScript.isQuoted(name); - var findSym = function (id) { - if(context.members) { - return context.members.lookup(name); - } else { - return findTypeSymbolInScopeChain(name, context.topLevelScope); - } - }; - if(isDynamic) { - symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); - } else { - symbol = findSym(name); - } - break; - case TypeScript.NodeType.Dot: - var dottedExpr = alias; - var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); - if(op1Sym && op1Sym.getType()) { - symbol = findSymbolFromAlias(dottedExpr.operand2, context); - } - break; - default: - break; - } - if(symbol) { - var symType = symbol.getType(); - if(symType) { - var members = symType.members; - if(members) { - context.members = members.publicMembers; - } - } - } - return symbol; - } - function preCollectImportTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var typeSymbol = null; - var modType = null; - var importDecl = ast; - var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { - topLevelScope: scopeChain, - members: null, - tcContext: context - }); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - if(aliasedModSymbol) { - var aliasedModType = aliasedModSymbol.getType(); - if(aliasedModType) { - modType = aliasedModType; - } - } - typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); - typeSymbol.aliasLink = importDecl; - if(context.scopeChain.moduleDecl) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = importDecl; - importDecl.id.sym = typeSymbol; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); - return true; - } - TypeScript.preCollectImportTypes = preCollectImportTypes; - function preCollectModuleTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var moduleDecl = ast; - var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); - var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); - var modName = (moduleDecl.name).text; - var isDynamic = TypeScript.isQuoted(modName); - var symbol = scopeChain.scope.findLocal(modName, false, false); - var typeSymbol = null; - var modType = null; - if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { - context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); - symbol = null; - modName = ""; - } - if(symbol) { - var modDeclAST = symbol.declAST; - var modDeclASTIsExported = TypeScript.hasFlag(modDeclAST.modFlags, TypeScript.ModuleFlags.Exported); - if((modDeclASTIsExported && !isExported) || (!modDeclASTIsExported && isExported)) { - context.checker.errorReporter.simpleError(moduleDecl, 'All contributions to a module must be "export" or none'); - } - } - if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { - if(modType == null) { - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - modType.setHasImplementation(); - } - typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); - typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); - if(context.scopeChain.moduleDecl) { - typeSymbol.declModule = context.scopeChain.moduleDecl; - } - typeSymbol.declAST = moduleDecl; - typeSymbol.prettyName = moduleDecl.prettyName; - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - modType.symbol = typeSymbol; - } else { - typeSymbol = symbol; - var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; - var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; - var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; - var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; - var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); - var publicMembers = typeSymbol.type.members.publicMembers; - var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; - var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); - var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; - var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; - var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); - modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); - if(isEnum) { - modType.typeFlags |= TypeScript.TypeFlags.IsEnum; - } - modType.members = members; - modType.ambientMembers = ambientMembers; - modType.setHasImplementation(); - modType.symbol = typeSymbol; - typeSymbol.addLocation(moduleDecl.minChar); - typeSymbol.expansions.push(modType); - typeSymbol.expansionsDeclAST.push(moduleDecl); - } - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - moduleDecl.mod = modType; - TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); - return true; - } - TypeScript.preCollectModuleTypes = preCollectModuleTypes; - function preCollectClassTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var classDecl = ast; - var classType; - var instanceType; - var typeSymbol = null; - var className = (classDecl.name).text; - var alreadyInScope = false; - var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var containerMod = scopeChain.container; - var foundValSymbol = false; - typeSymbol = scopeChain.scope.findLocal(className, false, true); - if(!typeSymbol) { - var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); - if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { - typeSymbol = valTypeSymbol; - foundValSymbol = true; - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - } - } - if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { - typeSymbol = null; - } - if(typeSymbol == null) { - var valueSymbol = scopeChain.scope.findLocal(className, false, false); - classType = new TypeScript.Type(); - classType.setHasImplementation(); - instanceType = new TypeScript.Type(); - instanceType.setHasImplementation(); - classType.instanceType = instanceType; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - addPrototypeField(classType, classDecl, context); - instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); - typeSymbol.declAST = classDecl; - typeSymbol.instanceType = instanceType; - classType.symbol = typeSymbol; - instanceType.symbol = typeSymbol; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - typeSymbol.declModule = context.scopeChain.moduleDecl; - typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(isExported) { - typeSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(isAmbient) { - typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; - } - ast.type = classType; - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); - if(valueSymbol == null) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); - } - } else { - classType = typeSymbol.type; - if(classType.instanceType == null) { - classType.instanceType = new TypeScript.Type(); - classType.instanceType.setHasImplementation(); - classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.instanceType.symbol = classType.symbol; - classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - } - instanceType = classType.instanceType; - ast.type = classType; - } - if(!classDecl.constructorDecl) { - if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { - context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); - } - createNewConstructGroupForType(classDecl.type); - } - classType.typeFlags |= TypeScript.TypeFlags.IsClass; - instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; - getBases(instanceType, classDecl); - TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); - return true; - } - TypeScript.preCollectClassTypes = preCollectClassTypes; - function preCollectInterfaceTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var interfaceDecl = ast; - var interfaceSymbol = null; - var interfaceType = null; - var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var alreadyInScope = true; - alreadyInScope = false; - var interfaceName = (interfaceDecl.name).text; - interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); - if(interfaceSymbol == null) { - interfaceType = new TypeScript.Type(); - interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); - interfaceType.symbol = interfaceSymbol; - interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - interfaceSymbol.declAST = interfaceDecl; - interfaceSymbol.declModule = context.scopeChain.moduleDecl; - } else { - alreadyInScope = true; - interfaceType = interfaceSymbol.type; - } - if(!interfaceType) { - interfaceType = context.checker.anyType; - } - ast.type = interfaceType; - getBases(interfaceType, interfaceDecl); - if(isExported) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(context.scopeChain.moduleDecl) { - interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - } - if(!alreadyInScope) { - context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); - } - TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); - return true; - } - TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; - function preCollectArgDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var argDecl = ast; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { - var field = new TypeScript.ValueLocation(); - var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); - var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); - fieldSymbol.transferVarFlags(argDecl.varFlags); - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - argDecl.parameterPropertySym = fieldSymbol; - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); - field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); - argDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; - function preCollectVarDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - var varDecl = ast; - var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); - var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); - var isGlobal = context.scopeChain.container == context.checker.gloMod; - var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); - var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); - var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); - var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { - if(isAmbient) { - var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); - if(existingSym) { - varDecl.sym = existingSym; - return false; - } - } - if(varDecl.id == null) { - context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); - return false; - } - var field = new TypeScript.ValueLocation(); - var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); - fieldSymbol.transferVarFlags(varDecl.varFlags); - if(isOptional) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; - } - field.symbol = fieldSymbol; - fieldSymbol.declAST = ast; - if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; - fieldSymbol.declModule = context.scopeChain.moduleDecl; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { - if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { - context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); - } - fieldSymbol.container = context.scopeChain.classType.symbol; - } else { - context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { - fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; - } - field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); - varDecl.sym = fieldSymbol; - } - return false; - } - TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; - function preCollectFuncDeclTypes(ast, parent, context) { - var scopeChain = context.scopeChain; - if(context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - var funcDecl = ast; - var fgSym = null; - var nameText = funcDecl.getNameText(); - var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); - var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); - var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); - var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; - var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); - var containerScope = context.scopeChain.scope; - var isGlobal = containerSym == context.checker.gloMod; - var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); - var go = false; - var foundSymbol = false; - if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - containerSym = containerSym.container; - containerScope = scopeChain.previous.scope; - } - funcDecl.unitIndex = context.checker.locationInfo.unitIndex; - if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { - return go; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { - var instType = context.scopeChain.thisType; - if(nameText && nameText != "__missing") { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - fgSym = containerScope.findLocal(nameText, false, false); - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, true); - } - } - if(fgSym) { - foundSymbol = true; - if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { - fgSym = null; - } - } - } - if(fgSym == null) { - if(!(funcDecl.isSpecialFn())) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; - } else { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; - } - if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { - fgSym.declAST = ast; - } - } else { - if((fgSym.kind() == TypeScript.SymbolKind.Type)) { - fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; - } else { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - } - } - if(funcDecl.isSpecialFn() && !isStatic) { - funcDecl.type = instType ? instType : fgSym.type; - } else { - funcDecl.type = fgSym.type; - } - } else { - if(nameText) { - if(isStatic) { - fgSym = containerSym.type.members.allMembers.lookup(nameText); - } else { - if(funcDecl.isConstructor && context.scopeChain.previous) { - fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); - } - if(fgSym == null) { - fgSym = containerScope.findLocal(nameText, false, false); - } - } - if(fgSym) { - foundSymbol = true; - if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { - fgSym = null; - foundSymbol = false; - } - } - } - if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); - } - if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { - context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); - fgSym.type = context.checker.anyType; - } - if(fgSym && !fgSym.isAccessor() && funcDecl.isAccessor()) { - fgSym = null; - } - var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); - if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { - funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); - } - funcDecl.type.symbol.declAST = ast; - if(funcDecl.isConstructor) { - go = true; - } - ; - } - if(isExported) { - if(funcDecl.type.call) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; - } - if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { - fgSym.flags |= TypeScript.SymbolFlags.Exported; - } - } - if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { - funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; - funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; - } - if(fgSym && isOptional) { - fgSym.flags |= TypeScript.SymbolFlags.Optional; - } - return go; - } - TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; - function preCollectTypes(ast, parent, walker) { - var context = walker.state; - var go = false; - var scopeChain = context.scopeChain; - if(ast.nodeType == TypeScript.NodeType.Script) { - var script = ast; - context.script = script; - go = true; - } else if(ast.nodeType == TypeScript.NodeType.List) { - go = true; - } else if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { - go = preCollectImportTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.With) { - go = false; - } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - go = preCollectModuleTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - go = preCollectClassTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.Block) { - go = true; - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - go = preCollectInterfaceTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - go = preCollectArgDeclTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.VarDecl) { - go = preCollectVarDeclTypes(ast, parent, context); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - go = preCollectFuncDeclTypes(ast, parent, context); - } else { - if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { - context.scopeChain.moduleDecl.recordNonInterface(); - } - } - walker.options.goChildren = go; - return ast; - } - TypeScript.preCollectTypes = preCollectTypes; - function postCollectTypes(ast, parent, walker) { - var context = walker.state; - if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { - TypeScript.popTypeCollectionScope(context); - } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - TypeScript.popTypeCollectionScope(context); - } - return ast; - } - TypeScript.postCollectTypes = postCollectTypes; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var ScopeChain = (function () { - function ScopeChain(container, previous, scope) { - this.container = container; - this.previous = previous; - this.scope = scope; - } - return ScopeChain; - })(); - TypeScript.ScopeChain = ScopeChain; - var BBUseDefInfo = (function () { - function BBUseDefInfo(bb) { - this.bb = bb; - this.defsBySymbol = new Array(); - this.useIndexBySymbol = new Array(); - } - BBUseDefInfo.prototype.updateTop = function () { - var temp = new BitVector(this.top.bitCount); - for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { - var succ = this.bb.successors[i]; - if(succ.useDef) { - temp.union(succ.useDef.top); - } - } - temp.difference(this.kill); - temp.union(this.gen); - var changed = temp.notEq(this.top); - this.top = temp; - return changed; - }; - BBUseDefInfo.prototype.initialize = function (useDefContext) { - var _this = this; - var defSym = function (sym, context) { - if(context.isLocalSym(sym)) { - var index = context.getSymbolIndex(sym); - _this.useIndexBySymbol[index] = new Array(); - _this.defsBySymbol[index] = true; - } - }; - var useSym = function (sym, context, ast) { - if(context.isLocalSym(sym)) { - var symIndex = context.getSymbolIndex(sym); - if(_this.useIndexBySymbol[symIndex] == undefined) { - _this.useIndexBySymbol[symIndex] = new Array(); - } - var symUses = _this.useIndexBySymbol[symIndex]; - var astIndex = context.getUseIndex(ast); - context.addUse(symIndex, astIndex); - symUses.push(astIndex); - } - }; - function initUseDefPre(cur, parent, walker) { - var context = walker.state; - if(cur == null) { - cur = null; - } - if(cur.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = cur; - if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { - defSym(varDecl.sym, context); - } - } else if(cur.nodeType == TypeScript.NodeType.Name) { - if(parent) { - if(parent.nodeType == TypeScript.NodeType.Asg) { - var asg = parent; - if(asg.operand1 == cur) { - return cur; - } - } else if(parent.nodeType == TypeScript.NodeType.VarDecl) { - var parentDecl = parent; - if(parentDecl.id == cur) { - return cur; - } - } - } - var id = cur; - useSym(id.sym, context, cur); - } else if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { - var asg = cur; - if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { - var id = asg.operand1; - defSym(id.sym, context); - } - } else if(cur.nodeType == TypeScript.NodeType.FuncDecl) { - walker.options.goChildren = false; - } - return cur; - } - var options = new TypeScript.AstWalkOptions(); - options.reverseSiblings = true; - TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); - }; - BBUseDefInfo.prototype.initializeGen = function (useDefContext) { - var symbolLen = this.useIndexBySymbol.length; - var bitCount = useDefContext.uses.length; - this.gen = new BitVector(bitCount); - for(var s = 0; s < symbolLen; s++) { - var symUses = this.useIndexBySymbol[s]; - if((symUses != undefined) && (symUses.length > 0)) { - for(var u = 0, uLen = symUses.length; u < uLen; u++) { - this.gen.set(symUses[u], true); - } - } - } - this.top = this.gen; - }; - BBUseDefInfo.prototype.initializeKill = function (useDefContext) { - this.kill = new BitVector(this.gen.bitCount); - for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { - if(this.defsBySymbol[s]) { - var globalSymUses = useDefContext.useIndexBySymbol[s]; - if(globalSymUses) { - for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { - this.kill.set(globalSymUses[u], true); - } - } - } - } - }; - return BBUseDefInfo; - })(); - TypeScript.BBUseDefInfo = BBUseDefInfo; - var UseDefContext = (function () { - function UseDefContext() { - this.useIndexBySymbol = new Array(); - this.uses = new Array(); - this.symbols = new Array(); - this.symbolMap = new TypeScript.StringHashTable(); - this.symbolCount = 0; - } - UseDefContext.prototype.getSymbolIndex = function (sym) { - var name = sym.name; - var index = (this.symbolMap.lookup(name)); - if(index == null) { - index = this.symbolCount++; - this.symbols[index] = sym; - this.symbolMap.add(name, index); - } - return index; - }; - UseDefContext.prototype.addUse = function (symIndex, astIndex) { - var useBySym = this.useIndexBySymbol[symIndex]; - if(useBySym == undefined) { - useBySym = new Array(); - this.useIndexBySymbol[symIndex] = useBySym; - } - useBySym[useBySym.length] = astIndex; - }; - UseDefContext.prototype.getUseIndex = function (ast) { - this.uses[this.uses.length] = ast; - return this.uses.length - 1; - }; - UseDefContext.prototype.isLocalSym = function (sym) { - return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); - }; - UseDefContext.prototype.killSymbol = function (sym, bbUses) { - var index = this.symbolMap.lookup(sym.name); - var usesOfSym = this.useIndexBySymbol[index]; - for(var k = 0, len = usesOfSym.length; k < len; k++) { - bbUses.set(usesOfSym[k], true); - } - }; - return UseDefContext; - })(); - TypeScript.UseDefContext = UseDefContext; - var BitVector = (function () { - function BitVector(bitCount) { - this.bitCount = bitCount; - this.firstBits = 0; - this.restOfBits = null; - if(this.bitCount > BitVector.packBits) { - this.restOfBits = new Array(); - var len = Math.floor(this.bitCount / BitVector.packBits); - for(var i = 0; i < len; i++) { - this.restOfBits[i] = 0; - } - } - } - BitVector.packBits = 30; - BitVector.prototype.set = function (bitIndex, value) { - if(bitIndex < BitVector.packBits) { - if(value) { - this.firstBits |= (1 << bitIndex); - } else { - this.firstBits &= (~(1 << bitIndex)); - } - } else { - var offset = Math.floor(bitIndex / BitVector.packBits) - 1; - var localIndex = bitIndex % BitVector.packBits; - if(value) { - this.restOfBits[offset] |= (1 << localIndex); - } else { - this.restOfBits[offset] &= (~(1 << localIndex)); - } - } - }; - BitVector.prototype.map = function (fn) { - var k; - for(k = 0; k < BitVector.packBits; k++) { - if(k == this.bitCount) { - return; - } - if(((1 << k) & this.firstBits) != 0) { - fn(k); - } - } - if(this.restOfBits) { - var len; - var cumu = BitVector.packBits; - for(k = 0 , len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - for(var j = 0; j < BitVector.packBits; j++) { - if(((1 << j) & myBits) != 0) { - fn(cumu); - } - cumu++; - if(cumu == this.bitCount) { - return; - } - } - } - } - }; - BitVector.prototype.union = function (b) { - this.firstBits |= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits | bBits; - } - } - }; - BitVector.prototype.intersection = function (b) { - this.firstBits &= b.firstBits; - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] = myBits & bBits; - } - } - }; - BitVector.prototype.notEq = function (b) { - if(this.firstBits != b.firstBits) { - return true; - } - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - if(myBits != bBits) { - return true; - } - } - } - return false; - }; - BitVector.prototype.difference = function (b) { - var oldFirstBits = this.firstBits; - this.firstBits &= (~b.firstBits); - if(this.restOfBits) { - for(var k = 0, len = this.restOfBits.length; k < len; k++) { - var myBits = this.restOfBits[k]; - var bBits = b.restOfBits[k]; - this.restOfBits[k] &= (~bBits); - } - } - }; - return BitVector; - })(); - TypeScript.BitVector = BitVector; - var BasicBlock = (function () { - function BasicBlock() { - this.predecessors = new Array(); - this.index = -1; - this.markValue = 0; - this.successors = new Array(); - this.useDef = null; - this.content = new TypeScript.ASTList(); - } - BasicBlock.prototype.marked = function (markBase) { - return this.markValue > markBase; - }; - BasicBlock.prototype.mark = function () { - this.markValue++; - }; - BasicBlock.prototype.addSuccessor = function (successor) { - this.successors[this.successors.length] = successor; - successor.predecessors[successor.predecessors.length] = this; - }; - return BasicBlock; - })(); - TypeScript.BasicBlock = BasicBlock; - var ControlFlowContext = (function () { - function ControlFlowContext(current, exit) { - this.current = current; - this.exit = exit; - this.entry = null; - this.unreachable = null; - this.noContinuation = false; - this.statementStack = new Array(); - this.currentSwitch = new Array(); - this.markBase = 0; - this.linearBBs = new Array(); - this.entry = this.current; - } - ControlFlowContext.prototype.walk = function (ast, parent) { - return this.walker.walk(ast, parent); - }; - ControlFlowContext.prototype.pushSwitch = function (bb) { - this.currentSwitch.push(bb); - }; - ControlFlowContext.prototype.popSwitch = function () { - return this.currentSwitch.pop(); - }; - ControlFlowContext.prototype.reportUnreachable = function (er) { - if(this.unreachable && (this.unreachable.length > 0)) { - var len = this.unreachable.length; - for(var i = 0; i < len; i++) { - var unreachableAST = this.unreachable[i]; - if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { - er.simpleError(unreachableAST, "unreachable code"); - } - } - } - }; - ControlFlowContext.prototype.printAST = function (ast, outfile) { - var printContext = new TypeScript.PrintContext(outfile, null); - printContext.increaseIndent(); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); - printContext.decreaseIndent(); - }; - ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { - var content = bb.content; - for(var i = 0, len = content.members.length; i < len; i++) { - var ast = content.members[i]; - this.printAST(ast, outfile); - } - }; - ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { - var markValue = this.markBase++; - var q = new Array(); - q[q.length] = this.entry; - while(q.length > 0) { - var bb = q.pop(); - if(!(bb.marked(markValue))) { - bb.mark(); - if(nodeFunc) { - nodeFunc(bb); - } - var succLen = bb.successors.length; - if(succLen > 0) { - if(preEdges) { - preEdges(); - } - for(var j = succLen - 1; j >= 0; j--) { - var successor = bb.successors[j]; - if(!(successor.marked(this.markBase))) { - if(edgeFunc) { - edgeFunc(bb, successor); - } - q[q.length] = successor; - } - } - if(postEdges) { - postEdges(); - } - } - } - } - }; - ControlFlowContext.prototype.useDef = function (er, funcSym) { - var _this = this; - var useDefContext = new UseDefContext(); - useDefContext.func = funcSym; - var useDefInit = function (bb) { - bb.useDef = new BBUseDefInfo(bb); - bb.useDef.initialize(useDefContext); - _this.linearBBs[_this.linearBBs.length] = bb; - }; - this.bfs(useDefInit, null, null, null); - var i, bbLen; - for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { - this.linearBBs[i].useDef.initializeGen(useDefContext); - this.linearBBs[i].useDef.initializeKill(useDefContext); - } - var changed = true; - while(changed) { - changed = false; - for(i = 0; i < bbLen; i++) { - changed = this.linearBBs[i].useDef.updateTop() || changed; - } - } - var top = this.entry.useDef.top; - top.map(function (index) { - var ast = useDefContext.uses[index]; - er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); - }); - }; - ControlFlowContext.prototype.print = function (outfile) { - var _this = this; - var index = 0; - var node = function (bb) { - if(bb.index < 0) { - bb.index = index++; - } - if(bb == _this.exit) { - outfile.WriteLine("Exit block with index " + bb.index); - } else { - outfile.WriteLine("Basic block with index " + bb.index); - _this.printBlockContent(bb, outfile); - } - }; - function preEdges() { - outfile.Write(" Branches to "); - } - function postEdges() { - outfile.WriteLine(""); - } - function edge(node1, node2) { - if(node2.index < 0) { - node2.index = index++; - } - outfile.Write(node2.index + " "); - } - this.bfs(node, edge, preEdges, postEdges); - if(this.unreachable != null) { - for(var i = 0, len = this.unreachable.length; i < len; i++) { - outfile.WriteLine("Unreachable basic block ..."); - this.printAST(this.unreachable[i], outfile); - } - } - }; - ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { - this.statementStack.push({ - stmt: stmt, - continueBB: continueBB, - breakBB: breakBB - }); - }; - ControlFlowContext.prototype.popStatement = function () { - return this.statementStack.pop(); - }; - ControlFlowContext.prototype.returnStmt = function () { - this.current.addSuccessor(this.exit); - this.setUnreachable(); - }; - ControlFlowContext.prototype.setUnreachable = function () { - this.current = null; - this.noContinuation = true; - }; - ControlFlowContext.prototype.addUnreachable = function (ast) { - if(this.unreachable === null) { - this.unreachable = new Array(); - } - this.unreachable[this.unreachable.length] = ast; - }; - ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { - var targetBB = null; - for(var i = 0, len = this.statementStack.length; i < len; i++) { - var targetInfo = this.statementStack[i]; - if(targetInfo.stmt == target) { - if(isContinue) { - targetBB = targetInfo.continueBB; - } else { - targetBB = targetInfo.breakBB; - } - break; - } - } - if(targetBB) { - this.current.addSuccessor(targetBB); - } - this.setUnreachable(); - }; - ControlFlowContext.prototype.addContent = function (ast) { - if(this.current) { - this.current.content.append(ast); - } - }; - return ControlFlowContext; - })(); - TypeScript.ControlFlowContext = ControlFlowContext; - var ResolutionDataCache = (function () { - function ResolutionDataCache() { - this.cacheSize = 16; - this.rdCache = []; - this.nextUp = 0; - for(var i = 0; i < this.cacheSize; i++) { - this.rdCache[i] = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: i - }; - } - } - ResolutionDataCache.prototype.getResolutionData = function () { - var rd = null; - if(this.nextUp < this.cacheSize) { - rd = this.rdCache[this.nextUp]; - } - if(rd == null) { - this.cacheSize++; - rd = { - actuals: new Array(), - exactCandidates: new Array(), - conversionCandidates: new Array(), - id: this.cacheSize - }; - this.rdCache[this.cacheSize] = rd; - } - this.nextUp++; - return rd; - }; - ResolutionDataCache.prototype.returnResolutionData = function (rd) { - rd.actuals.length = 0; - rd.exactCandidates.length = 0; - rd.conversionCandidates.length = 0; - this.nextUp = rd.id; - }; - return ResolutionDataCache; - })(); - TypeScript.ResolutionDataCache = ResolutionDataCache; - var TypeFlow = (function () { - function TypeFlow(logger, initScope, parser, checker) { - this.logger = logger; - this.initScope = initScope; - this.parser = parser; - this.checker = checker; - this.thisFnc = null; - this.thisClassNode = null; - this.enclosingFncIsMethod = false; - this.arrayInterfaceType = null; - this.stringInterfaceType = null; - this.objectInterfaceType = null; - this.functionInterfaceType = null; - this.numberInterfaceType = null; - this.booleanInterfaceType = null; - this.iargumentsInterfaceType = null; - this.currentScript = null; - this.inImportTypeCheck = false; - this.inTypeRefTypeCheck = false; - this.inArrayElementTypeCheck = false; - this.resolutionDataCache = new ResolutionDataCache(); - this.nestingLevel = 0; - this.inSuperCall = false; - this.checker.typeFlow = this; - this.scope = this.initScope; - this.globalScope = this.initScope; - this.doubleType = this.checker.numberType; - this.booleanType = this.checker.booleanType; - this.stringType = this.checker.stringType; - this.anyType = this.checker.anyType; - this.regexType = this.anyType; - this.nullType = this.checker.nullType; - this.voidType = this.checker.voidType; - this.arrayAnyType = this.checker.makeArrayType(this.anyType); - } - TypeFlow.prototype.initLibs = function () { - var arraySym = this.globalScope.find("Array", false, true); - if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { - this.arrayInterfaceType = (arraySym).type; - } - var stringSym = this.globalScope.find("String", false, true); - if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { - this.stringInterfaceType = (stringSym).type; - } - var objectSym = this.globalScope.find("Object", false, true); - if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { - this.objectInterfaceType = (objectSym).type; - } - var fnSym = this.globalScope.find("Function", false, true); - if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { - this.functionInterfaceType = (fnSym).type; - } - var numberSym = this.globalScope.find("Number", false, true); - if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { - this.numberInterfaceType = (numberSym).type; - } - var booleanSym = this.globalScope.find("Boolean", false, true); - if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { - this.booleanInterfaceType = (booleanSym).type; - } - var regexSym = this.globalScope.find("RegExp", false, true); - if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { - this.regexType = (regexSym).type; - } - }; - TypeFlow.prototype.cast = function (ast, type) { - return this.castWithCoercion(ast, type, true, false); - }; - TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { - if(applyCoercion) { - if(type == null) { - ast.type = this.anyType; - } else if(type.isClass()) { - ast.type = type.instanceType; - } else { - ast.type = type; - } - } - return ast; - } else { - this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); - return ast; - } - }; - TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { - var prevScope = this.scope; - this.scope = enclosingScope; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var svThisClassNode = this.thisClassNode; - var svCurrentModDecl = this.checker.currentModDecl; - var prevMethodStatus = this.enclosingFncIsMethod; - var container = this.scope.container; - var fnc = null; - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - if(fnc == null) { - this.enclosingFncIsMethod = typeSym.isMethod; - fnc = container.declAST; - } - } - if(type.isClass()) { - this.thisType = type.instanceType; - if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { - this.thisClassNode = typeSym.declAST; - } - break; - } - if(type.isModuleType()) { - this.checker.currentModDecl = typeSym.declAST; - break; - } - } - container = container.container; - } - this.thisFnc = fnc; - var updated = this.typeCheck(ast); - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.thisClassNode = svThisClassNode; - this.checker.currentModDecl = svCurrentModDecl; - this.enclosingFncIsMethod = prevMethodStatus; - this.scope = prevScope; - return updated; - }; - TypeFlow.prototype.typeCheck = function (ast) { - if(ast) { - return ast.typeCheck(this); - } else { - return null; - } - }; - TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { - if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { - this.inScopeTypeCheckBoundDecl(ast); - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcDecl = ast; - if(funcDecl.isAccessor()) { - this.typeCheckFunction(funcDecl); - } - } - }; - TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { - var sym = varDecl.sym; - var svThisFnc = this.thisFnc; - var svThisType = this.thisType; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevLocationInfo = this.checker.locationInfo; - if(sym && sym.container) { - var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - this.thisFnc = sym.container.declAST; - } - if(instanceScope) { - var prevScope = this.scope; - this.scope = instanceScope; - var container = sym.container; - var svCurrentModDecl = this.checker.currentModDecl; - if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[sym.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - while(container) { - if(container.kind() == TypeScript.SymbolKind.Type) { - var typeSym = container; - var type = typeSym.type; - if(type.call) { - this.enclosingFncIsMethod = typeSym.isMethod; - } - if(type.isClass()) { - this.thisType = type.instanceType; - } - if(type.isModuleType()) { - this.checker.currentModDecl = container.declAST; - break; - } - } - container = container.container; - } - this.typeCheckBoundDecl(varDecl); - this.checker.currentModDecl = svCurrentModDecl; - this.scope = prevScope; - } - } - this.thisFnc = svThisFnc; - this.thisType = svThisType; - this.checker.locationInfo = prevLocationInfo; - this.enclosingFncIsMethod = prevMethodStatus; - }; - TypeFlow.prototype.resolveBoundDecl = function (varDecl) { - if(varDecl.typeExpr) { - if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { - this.typeCheck(varDecl.typeExpr); - } - varDecl.type = varDecl.typeExpr.type; - if(varDecl.sym) { - varDecl.sym.setType(varDecl.type); - } - } else if(varDecl.init == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - if(varDecl.sym) { - if(varDecl.sym.isType()) { - var tsym = varDecl.sym; - if(tsym.isMethod) { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); - return; - } else { - this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); - return; - } - } - varDecl.sym.setType(varDecl.type); - } - } - }; - TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { - var _this = this; - var infSym = varDecl.sym; - if(infSym == null) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = this.checker.widenType(varDecl.init.type); - } else { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - } - } else { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); - } - varDecl.type = this.anyType; - infSym.setType(this.anyType); - } else if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { - infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(infSym); - var resolved = false; - if(varDecl.type == null) { - if(varDecl.typeExpr) { - this.resolveBoundDecl(varDecl); - resolved = true; - varDecl.type = varDecl.typeExpr.type; - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } - } - if(varDecl.init) { - var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); - var prevScope = this.scope; - var applyTargetType = !varDecl.init.isParenthesized; - if(isLocalStatic) { - this.scope = varDecl.sym.container.getType().memberScope; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { - TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { - if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { - if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; - } - walker.options.goChildren = false; - } - return ast; - }); - } - this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); - this.scope = prevScope; - if(varDecl.type) { - var preserveScope = false; - var preservedContainedScope = null; - if(varDecl.init.type) { - preservedContainedScope = varDecl.init.type.containedScope; - preserveScope = true; - if(varDecl.init.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - } - } - varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && varDecl.init.type.containedScope == null) { - varDecl.init.type.containedScope = preservedContainedScope; - } - } else { - varDecl.type = this.checker.widenType(varDecl.init.type); - if(varDecl.type == this.voidType) { - this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); - varDecl.type = this.anyType; - } - } - infSym.setType(varDecl.type); - } else { - if(!resolved) { - this.resolveBoundDecl(varDecl); - } - } - infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { - if(varDecl.init) { - varDecl.init = this.typeCheck(varDecl.init); - varDecl.type = infSym.getType(); - varDecl.init = this.cast(varDecl.init, varDecl.type); - } - } - } - if(varDecl.id && varDecl.sym) { - varDecl.id.sym = varDecl.sym; - } - if(varDecl.sym && varDecl.sym.container) { - this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { - return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); - }); - } - return varDecl; - }; - TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { - this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); - } else { - this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); - } - } else { - this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); - } - }; - TypeFlow.prototype.typeCheckSuper = function (ast) { - if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { - ast.type = this.thisType.baseClass(); - } else { - if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - var enclosingFnc = this.thisFnc.enclosingFnc; - while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - enclosingFnc = enclosingFnc.enclosingFnc; - } - if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { - ast.type = this.thisType.baseClass(); - enclosingFnc.setHasSuperReferenceInFatArrowFunction(); - return ast; - } - } - ast.type = this.anyType; - this.checker.errorReporter.invalidSuperReference(ast); - } - return ast; - }; - TypeFlow.prototype.typeCheckThis = function (ast) { - ast.type = this.anyType; - var illegalThisRef = false; - if(this.thisFnc == null) { - if(this.thisType) { - if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { - illegalThisRef = true; - } else { - ast.type = this.thisType; - } - } else if(this.checker.currentModDecl) { - this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); - } - } else { - if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { - illegalThisRef = true; - } - if(this.thisFnc.isMethod() || this.thisFnc.isConstructor) { - if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - if(this.thisFnc.boundToProperty) { - var container = this.thisFnc.boundToProperty.sym.container; - if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - (container.declAST).setHasSelfReference(); - } - } else { - var encFnc = this.thisFnc.enclosingFnc; - var firstEncFnc = encFnc; - while(encFnc) { - if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { - illegalThisRef = true; - } - if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { - encFnc.setHasSelfReference(); - break; - } - encFnc = encFnc.enclosingFnc; - } - if(!encFnc && firstEncFnc) { - encFnc = firstEncFnc; - encFnc.setHasSelfReference(); - } else if(!encFnc) { - if(this.thisClassNode) { - (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; - } else if(this.checker.currentModDecl) { - this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; - } else { - this.checker.mustCaptureGlobalThis = true; - } - } - if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { - ast.type = this.thisType; - } - } - } - if(illegalThisRef) { - this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); - } - return ast; - }; - TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - infSym.declAST.type = this.anyType; - infSym.setType(this.anyType); - } else { - this.inScopeTypeCheckDecl(infSym.declAST); - } - } - if(!this.checker.styleSettings.innerScopeDeclEscape) { - if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { - if(this.nestingLevel < (infSym.declAST).nestingLevel) { - this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); - } - } - } - } - ast.type = symbol.getType(); - if(!symbol.writeable()) { - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } - } else if(symbol.isType()) { - ast.type = symbol.getType(); - ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); - } else { - ast.type = this.anyType; - this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); - } - }; - TypeFlow.prototype.typeCheckName = function (ast) { - var _this = this; - var identifier = ast; - if(this.checker.inWith) { - identifier.type = this.anyType; - } else { - var typespace = this.inTypeRefTypeCheck; - var idText = identifier.text; - var originalIdText = idText; - var isDynamicModuleName = TypeScript.isQuoted(identifier.text); - var symbol = this.scope.find(idText, false, typespace); - if(symbol == null && isDynamicModuleName) { - symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { - return _this.scope.find(id, false, typespace); - }); - } - if(!symbol) { - if(!identifier.isMissing()) { - this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); - } - identifier.type = this.anyType; - } else { - if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { - var symType = symbol.getType(); - if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { - var modDecl = symType.symbol.declAST; - if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; - } - } - } - if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - (symbol.declAST).signature.returnType.type = this.anyType; - } - this.setTypeFromSymbol(ast, symbol); - identifier.sym = symbol; - if(this.thisFnc) { - if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { - this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; - } - } - } - } - return ast; - }; - TypeFlow.prototype.typeCheckScript = function (script) { - this.checker.locationInfo = script.locationInfo; - this.scope = this.checker.globalScope; - if(!script.topLevelMod) { - this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); - } - this.currentScript = script; - script.bod = this.typeCheck(script.bod); - this.currentScript = null; - return script; - }; - TypeFlow.prototype.typeCheckBitNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return unex; - }; - TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.doubleType; - return ast; - }; - TypeFlow.prototype.typeCheckLogNot = function (ast) { - var unex = ast; - unex.operand = this.typeCheck(unex.operand); - unex.type = this.booleanType; - return unex; - }; - TypeFlow.prototype.astIsWriteable = function (ast) { - return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); - }; - TypeFlow.prototype.typeCheckIncOrDec = function (ast) { - var unex = ast; - var lval = unex.operand; - if(!this.astIsWriteable(unex)) { - this.checker.errorReporter.valueCannotBeModified(unex); - unex.type = this.doubleType; - } else { - unex = this.typeCheckUnaryNumberOperator(ast); - if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { - this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); - } - } - return unex; - }; - TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { - var binex = ast; - var resultType = null; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { - resultType = this.doubleType; - } else if((leftType == this.booleanType) && (rightType == this.booleanType)) { - resultType = this.booleanType; - } else if(leftType == this.anyType) { - if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { - resultType = this.anyType; - } - } else if(rightType == this.anyType) { - if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { - resultType = this.anyType; - } - } - if(resultType == null) { - resultType = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = resultType; - return binex; - }; - TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(assignment && (!this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { - this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); - } - var nodeType = binex.nodeType; - if(this.checker.isNullOrUndefinedType(leftType)) { - leftType = rightType; - } - if(this.checker.isNullOrUndefinedType(rightType)) { - rightType = leftType; - } - leftType = this.checker.widenType(leftType); - rightType = this.checker.widenType(rightType); - if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { - if(leftType == this.checker.stringType || rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } else { - if(leftType == this.checker.numberType && rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { - binex.type = this.checker.numberType; - } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - } - return binex; - }; - TypeFlow.prototype.typeCheckDotOperator = function (ast) { - var binex = ast; - var leftIsFnc = false; - binex.operand1 = this.typeCheck(binex.operand1); - var leftType = binex.operand1.type; - var leftScope = null; - if(leftType) { - if(leftType == this.anyType) { - binex.type = this.anyType; - return binex; - } else if(leftType == this.stringType) { - if(this.stringInterfaceType) { - leftScope = this.stringInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if(leftType == this.doubleType) { - if(this.numberInterfaceType) { - leftScope = this.numberInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if(leftType == this.booleanType) { - if(this.booleanInterfaceType) { - leftScope = this.booleanInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if((leftType.call || leftType.construct) && leftType.members == null) { - if(this.functionInterfaceType) { - leftScope = this.functionInterfaceType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else if(leftType.elementType) { - if(this.arrayInterfaceType) { - var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); - leftScope = arrInstType.memberScope; - } else { - binex.type = this.anyType; - return binex; - } - } else { - leftScope = leftType.memberScope; - } - } - if(leftScope == null) { - this.checker.errorReporter.expectedClassOrInterface(binex); - binex.type = this.anyType; - } else { - var propertyName = binex.operand2; - var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; - var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); - if(!symbol) { - if(this.objectInterfaceType && leftType) { - if(leftType.isReferenceType()) { - symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - if(!symbol) { - if(this.functionInterfaceType && (leftType.call || leftType.construct)) { - symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); - } - } - } - } - if(!symbol || (!symbol.visible(leftScope, this.checker))) { - binex.type = this.anyType; - if(symbol == null) { - this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); - } else if(!this.inTypeRefTypeCheck) { - this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); - } - } else { - if(symbol.isVariable()) { - if(symbol.isInferenceSymbol()) { - var infSym = symbol; - if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { - this.inScopeTypeCheckDecl(infSym.declAST); - } - } - } - propertyName.sym = symbol; - binex.type = symbol.getType(); - } - } - if(binex.type == null) { - binex.type = this.anyType; - } - return binex; - }; - TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { - this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckAsgOperator = function (ast) { - var binex = ast; - var applyTargetType = !binex.operand2.isParenthesized; - binex.operand1 = this.typeCheck(binex.operand1); - this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(!(this.astIsWriteable(binex.operand1))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - if(binex.operand1.nodeType == TypeScript.NodeType.Call) { - var callEx = binex.operand1; - } - var preserveScope = false; - var preservedContainedScope = null; - if(binex.operand2.type) { - preservedContainedScope = binex.operand2.type.containedScope; - preserveScope = true; - } - binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); - if(preserveScope && binex.operand2.type.containedScope == null) { - binex.operand2.type.containedScope = preservedContainedScope; - } - binex.type = rightType; - return binex; - }; - TypeFlow.prototype.typeCheckIndex = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!this.checker.styleSettings.literalSubscript) { - if(binex.operand2.nodeType == TypeScript.NodeType.QString) { - this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); - } - } - var objExprType = binex.operand1.type; - var indexExprType = binex.operand2.type; - if(objExprType.elementType) { - if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { - binex.type = objExprType.elementType; - } else if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } else if(objExprType.index) { - if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - var sig = this.resolveOverload(ast, objExprType.index); - if(sig) { - binex.type = sig.returnType.type; - } else { - binex.type = this.checker.anyType; - } - } else if(indexExprType == this.checker.stringType) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - } else if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { - binex.type = this.checker.anyType; - } else { - this.checker.errorReporter.simpleError(binex, "Illegal property access"); - binex.type = this.checker.anyType; - } - return binex; - }; - TypeFlow.prototype.typeCheckInOperator = function (binex) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { - this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckShift = function (binex, assignment) { - binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); - binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); - if(assignment && (!(this.astIsWriteable(binex.operand1)))) { - this.checker.errorReporter.valueCannotBeModified(binex); - } - binex.type = this.doubleType; - return binex; - }; - TypeFlow.prototype.typeCheckQMark = function (trinex) { - trinex.operand1 = this.typeCheck(trinex.operand1); - trinex.operand2 = this.typeCheck(trinex.operand2); - trinex.operand3 = this.typeCheck(trinex.operand3); - var leftType = trinex.operand2.type; - var rightType = trinex.operand3.type; - if(leftType == rightType) { - trinex.type = leftType; - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - trinex.type = rightType; - } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - trinex.type = leftType; - } else { - trinex.type = this.anyType; - this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); - } - } - return trinex; - }; - TypeFlow.prototype.addFormals = function (container, signature, table) { - var len = signature.parameters.length; - for(var i = 0; i < len; i++) { - var symbol = signature.parameters[i]; - symbol.container = container; - table.add(symbol.name, symbol); - } - }; - TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { - var len = vars.members.length; - var hasArgsDef = false; - for(var i = 0; i < len; i++) { - var local = vars.members[i]; - if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = null; - if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { - local.varFlags |= TypeScript.VarFlags.LocalStatic; - varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); - } else { - varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - } - varSym.transferVarFlags(local.varFlags); - localVar.symbol = varSym; - varSym.declAST = local; - localVar.typeLink.ast = local.typeExpr; - this.checker.resolveTypeLink(scope, localVar.typeLink, false); - if((local.type == null) && (local.init == null)) { - local.type = this.anyType; - } - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - if(local.id.text == "arguments") { - hasArgsDef = true; - } - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - if(!isModContainer) { - if(!hasArgsDef) { - var argLoc = new TypeScript.ValueLocation(); - argLoc.typeLink = new TypeScript.TypeLink(); - var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); - if(!this.iargumentsInterfaceType) { - var argumentsSym = scope.find("IArguments", false, true); - if(argumentsSym) { - argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; - this.iargumentsInterfaceType = argumentsSym.getType(); - } else { - this.iargumentsInterfaceType = this.anyType; - } - } - argLoc.typeLink.type = this.iargumentsInterfaceType; - table.add("arguments", theArgSym); - } - } - }; - TypeFlow.prototype.addConstructorLocalArgs = function (constructorDecl, table, isClass) { - var container = constructorDecl.type.symbol; - var args = constructorDecl.arguments; - if(args) { - var len = args.members.length; - for(var i = 0; i < len; i++) { - var local = args.members[i]; - if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { - var result = null; - if((result = table.lookup(local.id.text)) == null) { - this.resolveBoundDecl(local); - var localVar = new TypeScript.ValueLocation(); - localVar.typeLink = new TypeScript.TypeLink(); - var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); - varSym.funcDecl = constructorDecl; - varSym.declAST = local; - localVar.symbol = varSym; - localVar.typeLink.type = local.type; - localVar.symbol.container = container; - local.sym = localVar.symbol; - table.add(local.id.text, varSym); - } else { - local.type = result.getType(); - local.sym = result; - } - } - } - } - }; - TypeFlow.prototype.checkInitSelf = function (funcDecl) { - if(!funcDecl.isMethod()) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if(sym.isInstanceProperty()) { - return true; - } - } - } - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - for(var j = 0; j < fnsLen; j++) { - var fn = fns.members[j]; - if(this.checkInitSelf(fn)) { - return true; - } - } - return false; - }; - TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { - var freeVars = funcDecl.freeVariables; - for(var k = 0, len = freeVars.length; k < len; k++) { - var sym = freeVars[k]; - if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { - TypeScript.instanceFilter.reset(); - if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); - } - this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); - } - } - }; - TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { - var allReturnsAreVoid = true; - if(funcDecl.signature.returnType.type == null) { - var preFindReturnExpressionTypes = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: - go = false; - break; - case TypeScript.NodeType.Return: - var returnStmt = ast; - if(returnStmt.returnExpression) { - allReturnsAreVoid = false; - go = false; - } - default: - break; - } - walker.options.goChildren = go; - walker.options.goNextSibling = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); - } - return allReturnsAreVoid; - }; - TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { - var foundSuper = false; - var preFindSuperCall = function (ast, parent, walker) { - var go = true; - switch(ast.nodeType) { - case TypeScript.NodeType.FuncDecl: - go = false; - break; - case TypeScript.NodeType.Call: - var call = ast; - if(call.target.nodeType == TypeScript.NodeType.Super) { - go = false; - foundSuper = true; - break; - } - break; - default: - break; - } - walker.options.goChildren = go; - return ast; - }; - TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); - return foundSuper; - }; - TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { - var baseSymbol = bases.members[i].type.symbol; - var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var baseListTypeString = extendsList ? "extends" : "implements"; - var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module "; - baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; - } else { - baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; - } - this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); - }; - TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { - var _this = this; - if(bases) { - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { - continue; - } - this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { - return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); - }); - } - } - }; - TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { - var externalModuleSymbol = null; - var declSymbolPath = null; - if(typeSymbol.isExternallyVisible(this.checker)) { - var typeSymbolPath = typeSymbol.pathToRoot(); - declSymbolPath = declSymbol.pathToRoot(); - var typeSymbolLength = typeSymbolPath.length; - var declSymbolPathLength = declSymbolPath.length; - if(typeSymbolLength > 0) { - if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; - } else if(typeSymbolLength > 1) { - if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { - externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; - } - } - } - if(externalModuleSymbol == null) { - return; - } - } - var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); - if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { - return; - } - var checkVisibilitySymbol = declSymbol; - var varDecl = declSymbol.getVarDeclFromSymbol(); - if(varDecl) { - if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { - return; - } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { - checkVisibilitySymbol = declSymbol.container; - } - } - if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { - var privateSymbolName = typeSymbol.name; - if(externalModuleSymbol != null) { - var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); - if(prettyName != null) { - this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); - return; - } else { - privateSymbolName = externalModuleSymbol.prettyName; - } - } - errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); - } - }; - TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { - var _this = this; - if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { - return; - } - if(type.isArray()) { - return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); - } - if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { - return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); - } - if(type.members) { - type.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); - } - }, null); - } - this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); - this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); - }; - TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { - if(sgroup) { - var len = sgroup.signatures.length; - for(var i = 0; i < sgroup.signatures.length; i++) { - var signature = sgroup.signatures[i]; - if(len > 1 && signature == sgroup.definitionSignature) { - continue; - } - if(signature.returnType) { - this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); - } - var paramLen = signature.parameters.length; - for(var j = 0; j < paramLen; j++) { - var param = signature.parameters[j]; - this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); - } - } - } - }; - TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(funcDecl.isConstructor) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else if(isSetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); - } else if(!isGetter) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); - } else if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); - } else if(!funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); - } - } - }; - TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); - var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; - var typestring = ""; - if(isModuleName) { - var quotestring = ""; - if(!TypeScript.isQuoted(typeName)) { - quotestring = "'"; - } - typestring = " is using inaccessible module " + quotestring + typeName + quotestring; - } else { - typestring = " has or is using private type '" + typeName + "'"; - } - if(!isContainerInterface) { - if(isGetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); - } else if(!isSetter) { - this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); - } - } else { - if(funcDecl.isConstructMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); - } else if(funcDecl.isCallMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); - } else if(funcDecl.isIndexerMember()) { - this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); - } else { - this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); - } - } - }; - TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { - var reportOnFuncDecl = false; - if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); - } - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { - this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); - } else { - reportOnFuncDecl = true; - } - } - if(reportOnFuncDecl) { - this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); - } - }; - TypeFlow.prototype.typeCheckFunction = function (funcDecl) { - var _this = this; - this.nestingLevel = 0; - var fnType = funcDecl.type; - var fgSym = fnType.symbol; - var signature = funcDecl.signature; - if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { - return funcDecl; - } else if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { - signature.returnType.type = this.voidType; - return funcDecl; - } else { - if(funcDecl.returnTypeAnnotation == null) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; - } - return funcDecl; - } - } - signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(signature); - var prevScope = this.scope; - var prevFnc = this.thisFnc; - var prevMethodStatus = this.enclosingFncIsMethod; - var prevClassNode = this.thisClassNode; - this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; - this.thisFnc = funcDecl; - var container = funcDecl.type.symbol; - var prevThisType = this.thisType; - var prevLocationInfo = this.checker.locationInfo; - var funcTable = null; - var acceptedContextualType = false; - var targetParams = null; - var targetReturnType = null; - var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); - var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); - var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; - var prevModDecl = this.checker.currentModDecl; - if(funcDecl.isConstructor && !funcDecl.isOverload) { - if(fnType.instanceType == null) { - this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); - return funcDecl; - } - if(funcDecl.classDecl.type.construct == null) { - this.checker.errorReporter.simpleError(funcDecl, "Malformed constructor (is this a class named the same as an existing class?)"); - return funcDecl; - } - this.scope = fnType.instanceType.constructorScope; - var ssb = this.scope; - funcTable = ssb.valueMembers.allMembers; - } else if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { - funcTable = funcDecl.symbols; - if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { - this.scope = fnType.containedScope; - } - } else { - if(funcDecl.bod) { - this.scope = fnType.containedScope; - } - var ssb = this.scope; - if(ssb && ssb.valueMembers) { - funcTable = ssb.valueMembers.allMembers; - } - } - if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); - var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); - var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); - if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); - } else if(hasBaseType) { - if(superCallMustBeFirst) { - if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { - this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); - } - } else if(!this.classConstructorHasSuperCall(funcDecl)) { - this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); - } - } - } - if(funcDecl.isMethod() && funcDecl.type.enclosingType) { - var enclosingClassNode = null; - if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; - } else if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { - enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; - } - if(enclosingClassNode) { - this.thisClassNode = enclosingClassNode; - } - } - if(fnType.enclosingType) { - ; - var enclosingSym = fnType.symbol.container; - if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { - enclosingSym = enclosingSym.container; - } - if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { - this.checker.currentModDecl = enclosingSym.declAST; - } - } - if(funcDecl.unitIndex > 0) { - if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { - this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; - } else { - this.checker.locationInfo = TypeScript.unknownLocationInfo; - } - } - if(fnType.enclosingType) { - this.thisType = fnType.enclosingType; - } else { - this.thisType = prevThisType; - } - var paramLen = signature.parameters.length; - if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { - var tmpParamScope = this.scope; - var ssb = this.scope; - if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { - if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { - var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); - if(considerSym && considerSym.declAST && considerSym.declAST.type) { - this.checker.setContextualType(considerSym.declAST.type, false); - } - } - if(this.checker.hasTargetType()) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var candidateType = candidateTypeContext.contextualType; - if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { - var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; - candidateTypeContext.targetSig = candidateSigs.signatures[0]; - var candidateParams = candidateTypeContext.targetSig.parameters; - targetParams = candidateParams; - targetReturnType = candidateTypeContext.targetSig.returnType.type; - fgSym.type = candidateTypeContext.contextualType; - acceptedContextualType = true; - } else if(candidateType && funcDecl.isAccessor()) { - accessorType = candidateType; - candidateTypeContext.targetAccessorType = accessorType; - } else { - this.checker.killCurrentContextualType(); - } - } - } - var paramTable = ssb.valueMembers; - this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); - for(var p = 0; p < paramLen; p++) { - var symbol = signature.parameters[p]; - var ast = symbol.declAST; - if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { - var candidateTypeContext = this.checker.getTargetTypeContext(); - var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; - ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); - ast.sym.setType(ast.type); - (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - } else { - this.typeCheck(ast); - } - if(isSetter && accessorType) { - ast = this.cast(ast, accessorType); - } - symbol.container = container; - this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); - }); - paramTable.publicMembers.add(symbol.name, symbol); - } - this.scope = tmpParamScope; - } else { - this.typeCheck(funcDecl.arguments); - for(var p = 0; p < paramLen; p++) { - signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; - this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { - return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); - }); - if((funcDecl.arguments.members[p]).parameterPropertySym) { - (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); - } - } - if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { - if(!paramLen || paramLen > 1) { - this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); - } else if(funcDecl.arguments.members[0].type == this.checker.numberType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; - } else if(funcDecl.arguments.members[0].type == this.checker.stringType) { - fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; - } else { - this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); - } - } - } - if(funcDecl.bod && (!funcDecl.isSignature())) { - if(!(funcDecl.isConstructor)) { - this.addFormals(container, signature, funcTable); - } else { - this.addConstructorLocalArgs(funcDecl, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); - if(this.thisClassNode && this.thisClassNode.extendsList) { - var tmpScope = this.scope; - var funcMembers = new TypeScript.ScopedMembers(funcTable); - this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { - return sym.kind() == TypeScript.SymbolKind.Parameter; - }); - this.typeCheckBaseCalls(this.thisClassNode.extendsList); - this.scope = tmpScope; - } - } - var prevMod = this.checker.currentModDecl; - if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { - this.checker.currentModDecl = funcDecl.type.symbol.declModule; - } - if(acceptedContextualType) { - this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); - } - this.typeCheck(funcDecl.bod); - if(acceptedContextualType) { - this.checker.unsetContextualType(); - } - this.checker.currentModDecl = prevMod; - if(this.checker.checkControlFlow) { - var cfg = funcDecl.buildControlFlow(); - if(this.checker.printControlFlowGraph) { - cfg.print(this.checker.errorReporter.outfile); - } - cfg.reportUnreachable(this.checker.errorReporter); - if(this.checker.checkControlFlowUseDef) { - cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); - } - } - if(funcDecl.isConstructor) { - var fns = funcDecl.scopes; - var fnsLen = fns.members.length; - var freeVars; - var sym; - var j = 0; - for(; j < fnsLen; j++) { - var fn = fns.members[j]; - if(!fn.isSignature()) { - if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { - this.checkPromoteFreeVars(fn, funcDecl.type.symbol); - } - } - } - } - } - this.scope = prevScope; - this.thisFnc = prevFnc; - this.thisClassNode = prevClassNode; - this.enclosingFncIsMethod = prevMethodStatus; - this.thisType = prevThisType; - this.checker.locationInfo = prevLocationInfo; - this.checker.currentModDecl = prevModDecl; - signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - if(funcDecl.returnTypeAnnotation) { - this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); - if(signature.returnType.type == null) { - this.checker.resolveTypeLink(this.scope, signature.returnType, false); - } - } else if(targetReturnType) { - signature.returnType.type = targetReturnType; - } - if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { - var collection = { - getLength: function () { - return funcDecl.returnStatementsWithExpressions.length; - }, - setTypeAtIndex: function (index, type) { - funcDecl.returnStatementsWithExpressions[index].type = type; - }, - getTypeAtIndex: function (index) { - return funcDecl.returnStatementsWithExpressions[index].type; - } - }; - var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; - bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); - if(bestCommonReturnType) { - signature.returnType.type = this.checker.widenType(bestCommonReturnType); - } else { - for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { - this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); - } - signature.returnType.type = this.anyType; - } - } - var onlyHasThrow = false; - if(signature.returnType.type == null) { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - if(this.checker.styleSettings.implicitAny) { - this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); - } - signature.returnType.type = this.anyType; - } else { - signature.returnType.type = this.voidType; - } - } else if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { - signature.returnType.type = this.anyType; - } else if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { - if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { - onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); - if(!onlyHasThrow) { - this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); - } - } - this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { - return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); - }); - } - if(funcDecl.accessorSymbol) { - var accessorType = funcDecl.accessorSymbol.getType(); - if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { - this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); - } - if(accessorType) { - if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { - this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); - } - } else { - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - funcDecl.accessorSymbol.setType(signature.returnType.type); - } else { - if(funcDecl.arguments.members.length != 1) { - this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); - } else { - funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); - } - } - } - } - this.typeCheckOverloadSignatures(fnType, funcDecl); - return funcDecl; - }; - TypeFlow.prototype.typeCheckBases = function (type) { - var seenInterface = false; - var bases = type.extendsList; - var baseLinks = type.extendsTypeLinks; - if(bases) { - var len = bases.length; - if(len > 0) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseType; - } - for(var i = 0; i < len; i++) { - if(bases[i] == this.checker.anyType) { - baseLinks[i].type = null; - var oldErrors = this.checker.errorReporter.getCapturedErrors(); - TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); - this.checker.errorReporter.pushToErrorSink = true; - bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); - this.checker.errorReporter.pushToErrorSink = false; - this.checker.errorReporter.freeCapturedErrors(); - } - var base = bases[i]; - var baseRef = baseLinks[i].ast; - var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; - if(baseTypeOfObject) { - type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; - } - if(base.isClassInstance()) { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - if(seenInterface) { - this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); - } - } - } else if(base.isModuleType()) { - this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); - } else if(base.members) { - if(!seenInterface) { - seenInterface = true; - } - } else { - if(!(type.isClassInstance())) { - this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); - } else { - this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); - } - break; - } - } - } - }; - TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { - var instanceType = implementingType.getInstanceType(); - if(instanceType.implementsList) { - var len = instanceType.implementsList.length; - for(var i = 0; i < len; i++) { - var interfaceType = instanceType.implementsList[i]; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { - var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); - } else { - this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); - } - } - } - } - }; - TypeFlow.prototype.typeCheckBaseCalls = function (bases) { - if(bases == null) { - return; - } - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = null; - if(baseExpr.nodeType == TypeScript.NodeType.Call) { - this.typeCheckNew(baseExpr); - } - } - }; - TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { - var _this = this; - if(type) { - if(type.members) { - type.members.publicMembers.map(function (key, s, c) { - var sym = s; - var dup = names.lookup(sym.name); - if(dup) { - if(checkUnique) { - _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); - } - } else { - names.add(sym.name, sym); - } - }, null); - } - if(type.extendsList) { - var len = type.extendsList.length; - for(var i = 0; i < len; i++) { - if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { - this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); - } - } - } - } - }; - TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { - var _this = this; - var instanceType = derivedType.getInstanceType(); - if(instanceType.extendsList == null) { - return; - } - var len = instanceType.extendsList.length; - if(len > 0) { - var names = new TypeScript.StringHashTable(); - if(instanceType.isClassInstance()) { - for(var i = 0; i < len; i++) { - this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); - } - } - if(instanceType.members) { - instanceType.members.publicMembers.map(function (key, s, c) { - var sym = s; - for(var j = 0; j < len; j++) { - var base = instanceType.extendsList[j]; - if(base.memberScope == null) { - _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); - } else { - var bSym = base.memberScope.find(sym.name, false, false); - if(bSym) { - var aType = sym.getType(); - var bType = bSym.getType(); - if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); - } else if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { - _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); - } - } - } - } - }, null); - } - } - }; - TypeFlow.prototype.typeCheckClass = function (classDecl) { - var typeSymbol = classDecl.type.symbol; - if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { - return classDecl; - } else if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { - return classDecl; - } else { - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; - this.checker.addStartedPTO(typeSymbol); - } - var prevScope = this.scope; - var svClassNode = this.thisClassNode; - this.thisClassNode = classDecl; - var classType = classDecl.type; - this.typeCheckBases(classType.instanceType); - this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); - this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); - var prevThisType = this.thisType; - this.thisType = classType.instanceType; - this.scope = classType.instanceType.containedScope; - if(classDecl.constructorDecl) { - this.scope = classType.instanceType.constructorScope; - var ssb = this.scope; - var funcTable = ssb.valueMembers.allMembers; - this.addConstructorLocalArgs(classDecl.constructorDecl, funcTable, true); - } - this.typeCheck(classDecl.members); - typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - this.checkBaseTypeMemberInheritance(classType, classDecl); - this.checkMembersImplementInterfaces(classType); - this.typeCheckOverloadSignatures(classType, classDecl); - this.typeCheckOverloadSignatures(classType.instanceType, classDecl); - if(!classDecl.constructorDecl) { - if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { - TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); - } - } - this.thisType = prevThisType; - this.thisClassNode = svClassNode; - this.scope = prevScope; - return classDecl; - }; - TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { - if(type.call) { - type.call.typeCheck(this.checker, ast, type.construct != null); - } - if(type.construct) { - type.construct.typeCheck(this.checker, ast, false); - } - if(type.index) { - type.index.typeCheck(this.checker, ast, false); - } - }; - TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { - this.typeCheckBases(interfaceDecl.type); - this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); - this.typeCheck(interfaceDecl.members); - this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); - if(interfaceDecl.extendsList) { - for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { - if(interfaceDecl.extendsList.members[i].type.call) { - if(interfaceDecl.type.call) { - interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); - } else { - interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; - } - } - if(interfaceDecl.extendsList.members[i].type.construct) { - if(interfaceDecl.type.construct) { - interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); - } else { - interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; - } - } - if(interfaceDecl.extendsList.members[i].type.index) { - if(interfaceDecl.type.index) { - interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); - } else { - interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; - } - } - } - } - return interfaceDecl; - }; - TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { - var mod = importDecl.alias.type; - var sym = null; - var prevInImportTC = this.inImportTypeCheck; - this.inImportTypeCheck = true; - this.typeCheck(importDecl.alias); - mod = importDecl.alias.type; - if(mod == null) { - this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); - mod = this.checker.anyType; - (importDecl.id.sym).type = mod; - } - importDecl.id.type = mod; - sym = mod.symbol; - if(!mod.isModuleType()) { - this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); - } else { - sym.type = mod; - if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { - this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); - } - (importDecl.id.sym).type = mod; - if(mod.symbol && mod.symbol.declAST) { - (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; - } - } - this.inImportTypeCheck = prevInImportTC; - return importDecl; - }; - TypeFlow.prototype.typeCheckModule = function (moduleDecl) { - if(!moduleDecl.mod) { - return moduleDecl; - } - if(this.currentScript) { - this.currentScript.requiresGlobal = true; - } - var mod = moduleDecl.mod; - var sym = null; - var prevScope = this.scope; - var prevThisType = this.thisType; - var prevCurrentModDecl = this.checker.currentModDecl; - this.checker.currentModDecl = moduleDecl; - this.thisType = null; - this.scope = mod.containedScope; - this.typeCheck(moduleDecl.members); - sym = mod.symbol; - this.checker.currentModDecl = prevCurrentModDecl; - this.thisType = prevThisType; - this.scope = prevScope; - moduleDecl.type = mod; - if(sym) { - sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; - } - return moduleDecl; - }; - TypeFlow.prototype.typeCheckFor = function (forStmt) { - forStmt.init = this.typeCheck(forStmt.init); - this.nestingLevel++; - forStmt.cond = this.typeCheck(forStmt.cond); - this.typeCheckCondExpr(forStmt.cond); - forStmt.incr = this.typeCheck(forStmt.incr); - this.nestingLevel--; - forStmt.body = this.typeCheck(forStmt.body); - this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); - forStmt.type = this.voidType; - return forStmt; - }; - TypeFlow.prototype.typeCheckWith = function (withStmt) { - if(this.checker.errorsOnWith) { - this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); - } - withStmt.expr = this.typeCheck(withStmt.expr); - this.checker.inWith = true; - withStmt.body = this.typeCheck(withStmt.body); - this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); - this.checker.inWith = false; - return withStmt; - }; - TypeFlow.prototype.typeCheckForIn = function (forInStmt) { - forInStmt.obj = this.typeCheck(forInStmt.obj); - forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); - if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { - var varDecl = forInStmt.lval; - if(varDecl.typeExpr) { - this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); - } - if(varDecl.sym) { - varDecl.sym.setType(this.checker.stringType); - } - } - forInStmt.body = this.typeCheck(forInStmt.body); - this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); - return forInStmt; - }; - TypeFlow.prototype.typeCheckWhile = function (whileStmt) { - whileStmt.cond = this.typeCheck(whileStmt.cond); - this.typeCheckCondExpr(whileStmt.cond); - whileStmt.body = this.typeCheck(whileStmt.body); - this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); - whileStmt.type = this.voidType; - return whileStmt; - }; - TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { - doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); - this.typeCheckCondExpr(doWhileStmt.cond); - doWhileStmt.body = this.typeCheck(doWhileStmt.body); - this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); - doWhileStmt.type = this.voidType; - return doWhileStmt; - }; - TypeFlow.prototype.typeCheckCondExpr = function (cond) { - if(this.checker.styleSettings.assignmentInCond) { - if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { - this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); - } - } - }; - TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { - if(this.checker.styleSettings.blockInCompoundStmt && stmts) { - if(stmts.nodeType != TypeScript.NodeType.Block) { - this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); - } - } - }; - TypeFlow.prototype.typeCheckIf = function (ifStmt) { - ifStmt.cond = this.typeCheck(ifStmt.cond); - this.typeCheckCondExpr(ifStmt.cond); - ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); - ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); - this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); - this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); - ifStmt.type = this.voidType; - return ifStmt; - }; - TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { - if(!funcDecl.isAccessor()) { - return null; - } - if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { - return funcDecl.type.call.signatures[0].returnType.type; - } else { - return funcDecl.type.call.signatures[0].parameters[0].getType(); - } - }; - TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { - var resultType = new TypeScript.Type(); - resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); - resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); - var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); - aggScope.addParentScope(resultType.memberScope); - aggScope.addParentScope(this.scope); - resultType.containedScope = aggScope; - var memberDecls = objectLit.operand; - var prevThisType = this.thisType; - var acceptTargetType = false; - var targetType = null; - if(this.checker.hasTargetType()) { - targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { - if(targetType.symbol.declAST) { - this.typeCheck(targetType.symbol.declAST); - } - } - acceptTargetType = true; - } - if(memberDecls) { - for(var i = 0, len = memberDecls.members.length; i < len; i++) { - var binex = memberDecls.members[i]; - var id = binex.operand1; - var text; - var targetMember = null; - var fieldSymbol = null; - if(id.nodeType == TypeScript.NodeType.Name) { - text = (id).text; - } else if(id.nodeType == TypeScript.NodeType.QString) { - var idText = (id).text; - text = idText.substring(1, idText.length - 1); - } else { - this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); - resultType = this.anyType; - break; - } - if(acceptTargetType && targetType.memberScope) { - targetMember = targetType.memberScope.find(text, false, false); - } - if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { - var funcDecl = binex.operand2; - var accessorSym = resultType.members.publicMembers.lookup(text); - accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); - funcDecl.accessorSymbol = accessorSym; - fieldSymbol = accessorSym; - if(id.nodeType == TypeScript.NodeType.Name) { - (id).sym = accessorSym; - } - } - this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); - if(acceptTargetType && targetMember) { - if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { - binex.operand1.type = targetMember.getType(); - } - } else { - binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; - } - if(fieldSymbol == null) { - var memberType = binex.operand2.type; - var field = new TypeScript.ValueLocation(); - fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); - fieldSymbol.flags |= TypeScript.SymbolFlags.Property; - field.symbol = fieldSymbol; - fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); - field.typeLink = new TypeScript.TypeLink(); - field.typeLink.type = memberType; - resultType.members.publicMembers.add(text, fieldSymbol); - } - fieldSymbol.isObjectLitField = true; - } - } - this.thisType = prevThisType; - objectLit.type = resultType; - if(targetType) { - objectLit.targetType = targetType; - } - }; - TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { - var elements = arrayLit.operand; - var elementType = this.anyType; - var targetElementType = null; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - comparisonInfo.onlyCaptureFirstError = true; - if(this.checker.hasTargetType()) { - var targetType = this.checker.getTargetTypeContext().contextualType; - if(targetType.elementType) { - targetElementType = targetType.elementType; - } - } - if(elements) { - var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; - this.inArrayElementTypeCheck = true; - this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); - this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; - elementType = elements.members[0].type; - var collection = { - getLength: function () { - return elements.members.length; - }, - setTypeAtIndex: function (index, type) { - elements.members[index].type = type; - }, - getTypeAtIndex: function (index) { - return elements.members[index].type; - } - }; - elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); - if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { - elementType = this.anyType; - } - } - if(!elementType) { - var emsg = "Incompatible types in array literal expression"; - if(!comparisonInfo.message) { - this.checker.errorReporter.simpleError(arrayLit, emsg); - } else { - this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); - } - elementType = this.anyType; - } else if(targetElementType) { - if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { - elementType = targetElementType; - } - } - arrayLit.type = this.checker.makeArrayType(elementType); - }; - TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { - if(type && type.construct && type.construct.signatures.length > 0) { - for(var i = 0; i < type.construct.signatures.length; i++) { - if(type.construct.signatures[i].returnType.type == this.checker.voidType) { - this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); - break; - } - } - } - }; - TypeFlow.prototype.typeCheckReturn = function (returnStmt) { - if(this.thisFnc) { - var targetType = null; - if(this.checker.hasTargetType()) { - var tcContext = this.checker.getTargetTypeContext(); - var accessorType = tcContext.targetAccessorType; - if(accessorType) { - targetType = accessorType; - } else { - var targetSig = this.checker.getTargetTypeContext().targetSig; - if(targetSig && targetSig.returnType.type != this.voidType) { - targetType = targetSig.returnType.type; - } - } - } - if(returnStmt.returnExpression) { - this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; - if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { - targetType = this.thisFnc.returnTypeAnnotation.type; - } - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); - var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; - if(expectedReturnType) { - if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { - this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); - returnStmt.type = returnStmt.returnExpression.type; - } else { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); - returnStmt.type = expectedReturnType; - } - } else { - if(targetType) { - if(returnStmt.returnExpression.type != this.voidType) { - returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); - } else { - returnStmt.returnExpression.type = targetType; - } - } - returnStmt.type = returnStmt.returnExpression.type; - } - this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; - } else { - returnStmt.type = targetType == null ? this.checker.voidType : targetType; - } - } - return returnStmt; - }; - TypeFlow.prototype.typeCheckInstOf = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { - this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); - } - binex.type = this.booleanType; - return binex; - }; - TypeFlow.prototype.typeCheckCommaOperator = function (ast) { - var binex = ast; - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.typeCheckLogOr = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - var leftType = binex.operand1.type; - var rightType = binex.operand2.type; - if(leftType == this.checker.anyType || rightType == this.checker.anyType) { - binex.type = this.checker.anyType; - } else if(leftType == this.checker.booleanType) { - if(rightType == this.checker.booleanType) { - binex.type = this.checker.booleanType; - } else { - binex.type = this.checker.anyType; - } - } else if(leftType == this.checker.numberType) { - if(rightType == this.checker.numberType) { - binex.type = this.checker.numberType; - } else { - binex.type = this.checker.anyType; - } - } else if(leftType == this.checker.stringType) { - if(rightType == this.checker.stringType) { - binex.type = this.checker.stringType; - } else { - binex.type = this.checker.anyType; - } - } else { - if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { - binex.type = rightType; - } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { - binex.type = leftType; - } else { - binex.type = this.checker.anyType; - } - } - return binex; - }; - TypeFlow.prototype.typeCheckLogAnd = function (binex) { - binex.operand1 = this.typeCheck(binex.operand1); - binex.operand2 = this.typeCheck(binex.operand2); - binex.type = binex.operand2.type; - return binex; - }; - TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { - var lowerBound = signature.nonOptionalParameterCount; - var upperBound = signature.parameters.length; - var formalLen = lowerBound; - var acceptable = false; - if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { - formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); - acceptable = true; - } - var repeatType = null; - if(acceptable || signature.hasVariableArgList) { - if(signature.hasVariableArgList) { - formalLen -= 1; - repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; - repeatType = repeatType.elementType; - acceptable = actuals.length >= formalLen; - } - var len = actuals.length; - var exact = acceptable; - var convert = acceptable; - for(var i = 0; i < len; i++) { - var typeA; - if(i < formalLen) { - typeA = (signature.parameters[i]).parameter.typeLink.type; - } else { - typeA = repeatType; - } - var typeB = actuals[i]; - if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { - exact = false; - } - if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { - convert = false; - } - if(!(exact || convert)) { - break; - } - } - if(exact) { - exactCandidates[exactCandidates.length] = signature; - } else if(convert && (exactCandidates.length == 0)) { - conversionCandidates[conversionCandidates.length] = signature; - } - } - }; - TypeFlow.prototype.resolveOverload = function (application, group) { - var rd = this.resolutionDataCache.getResolutionData(); - var actuals = rd.actuals; - var exactCandidates = rd.exactCandidates; - var conversionCandidates = rd.conversionCandidates; - var candidate = null; - var hasOverloads = group.signatures.length > 1; - var comparisonInfo = new TypeScript.TypeComparisonInfo(); - var args = null; - var target = null; - if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { - var callEx = application; - args = callEx.arguments; - target = callEx.target; - if(callEx.arguments) { - var len = callEx.arguments.members.length; - for(var i = 0; i < len; i++) { - actuals[i] = callEx.arguments.members[i].type; - } - } - } else if(application.nodeType == TypeScript.NodeType.Index) { - var binExp = application; - target = binExp.operand1; - args = new TypeScript.ASTList(); - args.members[0] = binExp.operand2; - actuals[0] = binExp.operand2.type; - } - for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { - var signature = group.signatures[j]; - if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { - continue; - } - if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { - this.typeCheckFunction(signature.declAST); - } - this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); - } - var apparentTarget = target.nodeType == TypeScript.NodeType.Dot ? (target).operand2 : target; - if(exactCandidates.length == 0) { - var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); - if(applicableCandidates.length > 0) { - var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - var emsg = "Supplied parameters do not match any signature of call target"; - if(comparisonInfo.message) { - this.checker.errorReporter.simpleError(apparentTarget, emsg + ":\n\t" + comparisonInfo.message); - } else { - this.checker.errorReporter.simpleError(apparentTarget, emsg); - } - } - } else { - if(exactCandidates.length > 1) { - var applicableSigs = []; - for(var i = 0; i < exactCandidates.length; i++) { - applicableSigs[i] = { - signature: exactCandidates[i], - hadProvisionalErrors: false - }; - } - var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); - if(candidateInfo.ambiguous) { - this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); - } - candidate = candidateInfo.sig; - } else { - candidate = exactCandidates[0]; - } - } - this.resolutionDataCache.returnResolutionData(rd); - return candidate; - }; - TypeFlow.prototype.typeCheckNew = function (ast) { - var callEx = ast; - callEx.target = this.typeCheck(callEx.target); - var target = callEx.target; - if(target.type.construct || target.type.call) { - this.preTypeCheckCallArgs(callEx.arguments); - } else { - callEx.arguments = this.typeCheck(callEx.arguments); - } - if(target.type == this.anyType) { - callEx.type = this.anyType; - callEx.arguments = this.typeCheck(callEx.arguments); - } else { - if(target.type.construct) { - var signature = this.resolveOverload(callEx, target.type.construct); - if(signature == null) { - callEx.type = this.anyType; - } else if(signature.returnType.type == this.voidType) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else if(target.type.call) { - var signature = this.resolveOverload(callEx, target.type.call); - if(signature == null) { - callEx.type = this.anyType; - } else if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { - callEx.type = this.anyType; - callEx.signature = signature; - } else { - this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); - } - } else if(target.type.elementType) { - callEx.type = target.type; - } else { - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - callEx.type = this.anyType; - } - } - this.postTypeCheckCallArgs(callEx); - return callEx; - }; - TypeFlow.prototype.preTypeCheckCallArgs = function (args) { - if(!args) { - return; - } - for(var i = 0; i < args.members.length; i++) { - switch(args.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - continue; - default: - this.typeCheck(args.members[i]); - break; - } - } - }; - TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { - var acceptedTargetType = false; - var i = 0; - if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { - var sig = callEx.signature; - if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { - acceptedTargetType = true; - var targetType = null; - var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; - var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; - for(i = 0; i < nonVarArgActualParamLength; i++) { - targetType = sig.parameters[i].getType(); - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); - break; - } - } - if(sig.hasVariableArgList) { - var varArgParamIndex = sig.nonOptionalParameterCount - 1; - targetType = sig.parameters[varArgParamIndex].getType(); - if(targetType) { - targetType = targetType.elementType; - } - var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; - for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); - break; - } - } - } - } - } - if(!acceptedTargetType && callEx.arguments) { - this.checker.killCurrentContextualType(); - for(i = 0; i < callEx.arguments.members.length; i++) { - switch(callEx.arguments.members[i].nodeType) { - case TypeScript.NodeType.FuncDecl: - case TypeScript.NodeType.ObjectLit: - case TypeScript.NodeType.ArrayLit: - this.typeCheck(callEx.arguments.members[i]); - break; - default: - continue; - } - } - } - }; - TypeFlow.prototype.typeCheckCall = function (ast) { - var callEx = ast; - if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { - if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { - this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); - } - } else if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { - if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { - this.checker.errorReporter.styleError(callEx, "eval not permitted"); - } - } - if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { - (callEx.target).isInlineCallLiteral = true; - } - var prevInSuperCall = this.inSuperCall; - if(callEx.target.nodeType == TypeScript.NodeType.Super) { - this.inSuperCall = true; - } - callEx.target = this.typeCheck(callEx.target); - this.preTypeCheckCallArgs(callEx.arguments); - var target = callEx.target; - if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { - callEx.type = this.anyType; - } else { - var fnType = target.type; - if(fnType.call) { - var signature = this.resolveOverload(callEx, fnType.call); - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { - var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; - if(signature == null) { - callEx.type = this.anyType; - } else { - callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; - callEx.type = signature.returnType.type; - callEx.signature = signature; - } - } else { - callEx.type = this.anyType; - this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); - } - } - } - this.postTypeCheckCallArgs(callEx); - this.inSuperCall = prevInSuperCall; - return callEx; - }; - TypeFlow.prototype.assignScopes = function (ast) { - var script = ast; - this.checker.locationInfo = script.locationInfo; - var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); - var context = new TypeScript.AssignScopeContext(globalChain, this, [ - this.checker.currentModDecl - ]); - TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); - }; - TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { - var enclosingScope = enclosingScopeContext.getScope(); - var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); - var scriptFragment = enclosingScopeContext.getScriptFragment(); - var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); - memContext.scope = enclosingScope; - if(scriptFragment.nodeType == TypeScript.NodeType.Name) { - return scriptFragment.type.getMemberScope(this); - } else { - TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); - if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(memContext.type) { - return memContext.type.getMemberScope(this); - } else { - return null; - } - } - }; - TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { - return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); - }; - TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { - var matchFlag = TypeScript.ASTFlags.DotLHS; - var pos = enclosingScopeContext.pos; - var astResult = null; - var preFindMemberScopeFullAst = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { - astResult = ast; - walker.options.stopWalk(); - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { - if(TypeScript.isValidAstNode(ast)) { - if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { - astResult = ast; - } - walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); - } - return ast; - }; - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); - if(astResult == null) { - TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); - } - if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { - enclosingScopeContext.publicsOnly = false; - } - if(astResult && astResult.type) { - return astResult.type.getMemberScope(this); - } else { - return null; - } - }; - return TypeFlow; - })(); - TypeScript.TypeFlow = TypeFlow; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (Primitive) { - Primitive._map = []; - Primitive.None = 0; - Primitive.Void = 1; - Primitive.Double = 2; - Primitive.String = 4; - Primitive.Boolean = 8; - Primitive.Any = 16; - Primitive.Null = 32; - Primitive.Undefined = 64; - })(TypeScript.Primitive || (TypeScript.Primitive = {})); - var Primitive = TypeScript.Primitive; - var MemberName = (function () { - function MemberName() { - this.prefix = ""; - this.suffix = ""; - } - MemberName.prototype.isString = function () { - return false; - }; - MemberName.prototype.isArray = function () { - return false; - }; - MemberName.prototype.toString = function () { - return MemberName.memberNameToString(this); - }; - MemberName.memberNameToString = function memberNameToString(memberName) { - var result = memberName.prefix; - if(memberName.isString()) { - result += (memberName).text; - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - result += MemberName.memberNameToString(ar.entries[index]); - result += ar.delim; - } - } - result += memberName.suffix; - return result; - }; - MemberName.create = function create(arg1, arg2, arg3) { - if(typeof arg1 == "string") { - return new MemberNameString(arg1); - } else { - var result = new MemberNameArray(); - if(arg2) { - result.prefix = arg2; - } - if(arg3) { - result.suffix = arg3; - } - result.entries.push(arg1); - return result; - } - }; - return MemberName; - })(); - TypeScript.MemberName = MemberName; - var MemberNameString = (function (_super) { - __extends(MemberNameString, _super); - function MemberNameString(text) { - _super.call(this); - this.text = text; - } - MemberNameString.prototype.isString = function () { - return true; - }; - return MemberNameString; - })(MemberName); - TypeScript.MemberNameString = MemberNameString; - var MemberNameArray = (function (_super) { - __extends(MemberNameArray, _super); - function MemberNameArray() { - _super.apply(this, arguments); - - this.delim = ""; - this.entries = []; - } - MemberNameArray.prototype.isArray = function () { - return true; - }; - MemberNameArray.prototype.add = function (entry) { - this.entries.push(entry); - }; - MemberNameArray.prototype.addAll = function (entries) { - for(var i = 0; i < entries.length; i++) { - this.entries.push(entries[i]); - } - }; - return MemberNameArray; - })(MemberName); - TypeScript.MemberNameArray = MemberNameArray; - var currentTypeID = -1; - var Type = (function () { - function Type() { - this.typeID = currentTypeID++; - this.construct = null; - this.call = null; - this.index = null; - this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; - this.primitiveTypeClass = Primitive.None; - this.typeFlags = TypeScript.TypeFlags.None; - } - Type.prototype.baseClass = function () { - if(this.extendsList && (this.extendsList.length > 0)) { - return this.extendsList[0]; - } else { - return null; - } - }; - Type.prototype.getArrayBase = function (arrInstType, checker) { - return this.arrayCache.specialize(arrInstType, checker); - }; - Type.prototype.isClass = function () { - return this.instanceType != null; - }; - Type.prototype.isArray = function () { - return this.elementType != null; - }; - Type.prototype.isClassInstance = function () { - return this.symbol && !this.elementType && (this.symbol).type.isClass(); - }; - Type.prototype.getInstanceType = function () { - if(this.isClass()) { - return this.instanceType; - } else { - return this; - } - }; - Type.prototype.hasImplementation = function () { - return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); - }; - Type.prototype.setHasImplementation = function () { - this.typeFlags |= TypeScript.TypeFlags.HasImplementation; - }; - Type.prototype.isDouble = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); - }; - Type.prototype.isString = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); - }; - Type.prototype.isBoolean = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); - }; - Type.prototype.isNull = function () { - return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); - }; - Type.prototype.getTypeName = function () { - return this.getMemberTypeName("", true, false, null); - }; - Type.prototype.getScopedTypeName = function (scope, getPrettyTypeName) { - return this.getMemberTypeName("", true, false, scope, getPrettyTypeName); - }; - Type.prototype.getScopedTypeNameEx = function (scope, getPrettyTypeName) { - return this.getMemberTypeNameEx("", true, false, scope, getPrettyTypeName); - }; - Type.prototype.callCount = function () { - var total = 0; - if(this.call) { - total += this.call.signatures.length; - } - if(this.construct) { - total += this.construct.signatures.length; - } - if(this.index) { - total += this.index.signatures.length; - } - return total; - }; - Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { - var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope, getPrettyTypeName); - return memberName.toString(); - }; - Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { - if(this.elementType) { - return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); - } else if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { - var tn = this.symbol.scopeRelativeName(scope); - return MemberName.create(tn == "null" ? "any" : tn); - } else { - if(this.members || this.call || this.construct) { - if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { - return MemberName.create("this"); - } - this.typeFlags |= TypeScript.TypeFlags.BuildingName; - var builder = ""; - var allMemberNames = new MemberNameArray(); - var curlies = isElementType || this.index != null; - var memCount = 0; - var delim = "; "; - if(this.members) { - this.members.allMembers.map(function (key, s, unused) { - var sym = s; - if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { - var typeNameMember = sym.getTypeNameEx(scope); - if(typeNameMember.isArray() && (typeNameMember).delim == delim) { - allMemberNames.addAll((typeNameMember).entries); - } else { - allMemberNames.add(typeNameMember); - } - memCount++; - curlies = true; - } - }, null); - } - var signatureCount = this.callCount(); - var j; - var len = 0; - var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.call && this.call.signatures.length > 1 && !this.members && !this.construct; - var shortform = !curlies && (signatureCount == 1 || getPrettyFunctionOverload) && topLevel; - if(this.call) { - allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope, getPrettyFunctionOverload)); - } - if(this.construct) { - allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); - } - if(this.index) { - allMemberNames.addAll(this.index.toStrings("", shortform, scope)); - } - if((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { - allMemberNames.prefix = "{ "; - allMemberNames.suffix = "}"; - allMemberNames.delim = delim; - } else if(allMemberNames.entries.length > 1) { - allMemberNames.delim = delim; - } - this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); - if((signatureCount == 0) && (memCount == 0)) { - return MemberName.create("{}"); - } else { - return allMemberNames; - } - } else { - return MemberName.create("{}"); - } - } - }; - Type.prototype.checkDecl = function (checker) { - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST) { - checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); - } - } - }; - Type.prototype.getMemberScope = function (flow) { - if(this == flow.anyType) { - return null; - } else if(this.isDouble()) { - if(flow.numberInterfaceType) { - return flow.numberInterfaceType.memberScope; - } else { - return null; - } - } else if(this.isBoolean()) { - if(flow.booleanInterfaceType) { - return flow.booleanInterfaceType.memberScope; - } else { - return null; - } - } else if(this == flow.stringType) { - if(flow.stringInterfaceType) { - return flow.stringInterfaceType.memberScope; - } else { - return null; - } - } else if(this.elementType) { - if(flow.arrayInterfaceType) { - var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); - return arrInstType.memberScope; - } else { - return null; - } - } else { - return this.memberScope; - } - }; - Type.prototype.isReferenceType = function () { - return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; - }; - Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { - if(pattern == this) { - return replacement; - } - var result = this; - if(membersOnly) { - if(this.isReferenceType()) { - result = new Type(); - if(this.members) { - result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.members.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPublicMember(bSym.name, bSym); - }, null); - this.members.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.members.addPrivateMember(bSym.name, bSym); - }, null); - } - if(this.ambientMembers) { - result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); - this.ambientMembers.publicMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPublicMember(bSym.name, bSym); - }, null); - this.ambientMembers.privateMembers.map(function (key, s, unused) { - var sym = s; - var bSym = sym.specializeType(pattern, replacement, checker); - result.ambientMembers.addPrivateMember(bSym.name, bSym); - }, null); - } - result.containedScope = checker.scopeOf(result); - result.memberScope = result.containedScope; - } - } else { - if(this.elementType) { - if(this.elementType == pattern) { - result = checker.makeArrayType(replacement); - } else { - if(this.elementType.elementType == pattern) { - result = checker.makeArrayType(checker.makeArrayType(replacement)); - } - } - } else if(this.call) { - result = new Type(); - result.call = this.call.specializeType(pattern, replacement, checker); - } - } - return result; - }; - Type.prototype.hasBase = function (baseType) { - if(baseType == this) { - return true; - } else { - if(this.extendsList) { - for(var i = 0, len = this.extendsList.length; i < len; i++) { - if(this.extendsList[i].hasBase(baseType)) { - return true; - } - } - } - } - return false; - }; - Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { - if((this == checker.anyType) || (b == checker.anyType)) { - return checker.anyType; - } else if(this == b) { - return this; - } else if((b == checker.nullType) && this != checker.nullType) { - return this; - } else if((this == checker.nullType) && (b != checker.nullType)) { - return b; - } else if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { - return this; - } else if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { - return b; - } else if((b == checker.undefinedType) && this != checker.undefinedType) { - return this; - } else if((this == checker.undefinedType) && (b != checker.undefinedType)) { - return b; - } else if(this.elementType && b.elementType) { - if(this.elementType == b.elementType) { - return this; - } else { - var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); - if(mergedET == null) { - return checker.makeArrayType(checker.anyType); - } else { - return checker.makeArrayType(mergedET); - } - } - } else if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { - return b; - } else if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { - return this; - } else { - return null; - } - }; - Type.prototype.isModuleType = function () { - return false; - }; - Type.prototype.hasMembers = function () { - return this.members != null; - }; - Type.prototype.getAllEnclosedTypes = function () { - return null; - }; - Type.prototype.getAllAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getPublicEnclosedTypes = function () { - return null; - }; - Type.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - Type.prototype.getDocComments = function () { - if(this.elementType || !this.symbol) { - return []; - } - if(this.isClassInstance() || this.isClass()) { - if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { - return (this.symbol.declAST).classDecl.getDocComments(); - } else { - return this.symbol.getDocComments(); - } - } - if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { - return this.symbol.getDocComments(); - } - return []; - }; - return Type; - })(); - TypeScript.Type = Type; - var ModuleType = (function (_super) { - __extends(ModuleType, _super); - function ModuleType(enclosedTypes, ambientEnclosedTypes) { - _super.call(this); - this.enclosedTypes = enclosedTypes; - this.ambientEnclosedTypes = ambientEnclosedTypes; - this.importedModules = []; - } - ModuleType.prototype.isModuleType = function () { - return true; - }; - ModuleType.prototype.hasMembers = function () { - return this.members != null || this.enclosedTypes != null; - }; - ModuleType.prototype.getAllEnclosedTypes = function () { - return this.enclosedTypes; - }; - ModuleType.prototype.getAllAmbientEnclosedTypes = function () { - return this.ambientEnclosedTypes; - }; - ModuleType.prototype.getPublicEnclosedTypes = function () { - return null; - }; - ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { - return null; - }; - ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { - var moduleName = null; - members.map(function (key, s, c) { - if(moduleName == null && !TypeScript.isQuoted(key)) { - var symbol = s; - var type = symbol.getType(); - if(type == moduleType) { - moduleName = { - name: key, - symbol: symbol - }; - } - } - }, null); - return moduleName; - }; - ModuleType.prototype.findDynamicModuleName = function (moduleType) { - var moduleName = null; - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); - if(moduleName == null) { - moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); - } - return moduleName; - }; - return ModuleType; - })(Type); - TypeScript.ModuleType = ModuleType; - var TypeLink = (function () { - function TypeLink() { - this.type = null; - this.ast = null; - } - return TypeLink; - })(); - TypeScript.TypeLink = TypeLink; - function getTypeLink(ast, checker, autoVar) { - var result = new TypeLink(); - result.ast = ast; - if((ast == null) && (autoVar)) { - result.type = checker.anyType; - } else { - result.type = null; - } - return result; - } - TypeScript.getTypeLink = getTypeLink; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - function stripQuotes(str) { - return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); - } - TypeScript.stripQuotes = stripQuotes; - function isSingleQuoted(str) { - return str.indexOf("'") != -1; - } - TypeScript.isSingleQuoted = isSingleQuoted; - function isQuoted(str) { - return str.indexOf("\"") != -1 || isSingleQuoted(str); - } - TypeScript.isQuoted = isQuoted; - function quoteStr(str) { - return "\"" + str + "\""; - } - TypeScript.quoteStr = quoteStr; - function swapQuotes(str) { - if(str.indexOf("\"") != -1) { - str = str.replace("\"", "'"); - str = str.replace("\"", "'"); - } else { - str = str.replace("'", "\""); - str = str.replace("'", "\""); - } - return str; - } - TypeScript.swapQuotes = swapQuotes; - function changeToSingleQuote(str) { - if(str.indexOf("\"") != -1) { - str = str.replace("\"", "'"); - str = str.replace("\"", "'"); - } - return str; - } - TypeScript.changeToSingleQuote = changeToSingleQuote; - function switchToForwardSlashes(path) { - return path.replace(/\\/g, "/"); - } - TypeScript.switchToForwardSlashes = switchToForwardSlashes; - function trimModName(modName) { - if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { - return modName.substring(0, modName.length - 6); - } - if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { - return modName.substring(0, modName.length - 4); - } - if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { - return modName.substring(0, modName.length - 5); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { - return modName.substring(0, modName.length - 3); - } - if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { - return modName.substring(0, modName.length - 3); - } - return modName; - } - TypeScript.trimModName = trimModName; - function getDeclareFilePath(fname) { - return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); - } - TypeScript.getDeclareFilePath = getDeclareFilePath; - function isFileOfExtension(fname, ext) { - var invariantFname = fname.toLocaleUpperCase(); - var invariantExt = ext.toLocaleUpperCase(); - var extLength = invariantExt.length; - return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; - } - function isJSFile(fname) { - return isFileOfExtension(fname, ".js"); - } - TypeScript.isJSFile = isJSFile; - function isSTRFile(fname) { - return isFileOfExtension(fname, ".str"); - } - TypeScript.isSTRFile = isSTRFile; - function isTSFile(fname) { - return isFileOfExtension(fname, ".ts"); - } - TypeScript.isTSFile = isTSFile; - function isDSTRFile(fname) { - return isFileOfExtension(fname, ".d.str"); - } - TypeScript.isDSTRFile = isDSTRFile; - function isDTSFile(fname) { - return isFileOfExtension(fname, ".d.ts"); - } - TypeScript.isDTSFile = isDTSFile; - function getPrettyName(modPath, quote, treatAsFileName) { - if (typeof quote === "undefined") { quote = true; } - if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } - var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); - var components = this.getPathComponents(modName); - return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; - } - TypeScript.getPrettyName = getPrettyName; - function getPathComponents(path) { - return path.split("/"); - } - TypeScript.getPathComponents = getPathComponents; - function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { - absoluteModPath = switchToForwardSlashes(absoluteModPath); - var modComponents = this.getPathComponents(absoluteModPath); - var fixedModComponents = this.getPathComponents(fixedModFilePath); - var joinStartIndex = 0; - for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { - break; - } - } - if(joinStartIndex != 0) { - var relativePath = ""; - var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); - for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { - if(fixedModComponents[joinStartIndex] != "") { - relativePath = relativePath + "../"; - } - } - return relativePath + relativePathComponents.join("/"); - } - return absoluteModPath; - } - TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; - function quoteBaseName(modPath) { - var modName = trimModName(stripQuotes(modPath)); - var path = getRootFilePath(modName); - if(path == "") { - return modPath; - } else { - var components = modName.split(path); - var fileIndex = components.length > 1 ? 1 : 0; - return quoteStr(components[fileIndex]); - } - } - TypeScript.quoteBaseName = quoteBaseName; - function changePathToSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".str"; - } - TypeScript.changePathToSTR = changePathToSTR; - function changePathToDSTR(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.str"; - } - TypeScript.changePathToDSTR = changePathToDSTR; - function changePathToTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".ts"; - } - TypeScript.changePathToTS = changePathToTS; - function changePathToDTS(modPath) { - return trimModName(stripQuotes(modPath)) + ".d.ts"; - } - TypeScript.changePathToDTS = changePathToDTS; - function isRelative(path) { - return path.charAt(0) == "."; - } - TypeScript.isRelative = isRelative; - function isRooted(path) { - return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); - } - TypeScript.isRooted = isRooted; - function getRootFilePath(outFname) { - if(outFname == "") { - return outFname; - } else { - var isPath = outFname.indexOf("/") != -1; - return isPath ? filePath(outFname) : ""; - } - } - TypeScript.getRootFilePath = getRootFilePath; - function filePathComponents(fullPath) { - fullPath = switchToForwardSlashes(fullPath); - var components = getPathComponents(fullPath); - return components.slice(0, components.length - 1); - } - TypeScript.filePathComponents = filePathComponents; - function filePath(fullPath) { - var path = filePathComponents(fullPath); - return path.join("/") + "/"; - } - TypeScript.filePath = filePath; - function normalizeURL(url) { - var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; - var matches = hostDomainAndPortRegex.exec(url); - if(matches) { - var hostDomainAndPort = matches[1]; - var actualPath = matches[3]; - return hostDomainAndPort + normalizePath(actualPath); - } - return normalizePath(url); - } - TypeScript.normalizeURL = normalizeURL; - TypeScript.pathNormalizeRegExp = /\//g; - function normalizePath(path) { - path = switchToForwardSlashes(path); - var startedWithSep = path.charAt(0) === "/"; - var parts = this.getPathComponents(path); - for(var i = 0; i < parts.length; i++) { - if(parts[i] === "." || parts[i] === "") { - parts.splice(i, 1); - i--; - } - if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { - parts.splice(i - 1, 2); - i -= 2; - } - } - return (startedWithSep ? "/" : "") + parts.join("/"); - } - TypeScript.normalizePath = normalizePath; - function normalizeImportPath(path) { - return normalizePath(path); - } - TypeScript.normalizeImportPath = normalizeImportPath; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var SourceUnit = (function () { - function SourceUnit(path, content) { - this.path = path; - this.content = content; - this.referencedFiles = null; - } - SourceUnit.prototype.getText = function (start, end) { - return this.content.substring(start, end); - }; - SourceUnit.prototype.getLength = function () { - return this.content.length; - }; - return SourceUnit; - })(); - TypeScript.SourceUnit = SourceUnit; - var CompilationEnvironment = (function () { - function CompilationEnvironment(compilationSettings, ioHost) { - this.compilationSettings = compilationSettings; - this.ioHost = ioHost; - this.residentCode = []; - this.code = []; - this.inputOutputMap = []; - } - return CompilationEnvironment; - })(); - TypeScript.CompilationEnvironment = CompilationEnvironment; - var CodeResolver = (function () { - function CodeResolver(environment) { - this.environment = environment; - this.visited = { - }; - } - CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { - var resolvedFile = { - content: null, - path: referencePath - }; - var ioHost = this.environment.ioHost; - var isRelativePath = TypeScript.isRelative(referencePath); - var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); - var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); - if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { - normalizedPath += ".ts"; - } - normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); - var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); - if(!this.visited[absoluteModuleID]) { - if(isRelativePath || isRootedPath || !performSearch) { - try { - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - try { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - try { - resolvedFile.content = ioHost.readFile(normalizedPath); - } catch (err) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); - resolvedFile.content = ioHost.readFile(normalizedPath); - } - } - } - TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); - resolvedFile.path = normalizedPath; - this.visited[absoluteModuleID] = true; - } catch (err) { - TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); - return false; - } - } else { - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - if(TypeScript.isSTRFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToTS(normalizedPath); - } else if(TypeScript.isTSFile(normalizedPath)) { - normalizedPath = TypeScript.changePathToSTR(normalizedPath); - } - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDTS(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - if(!resolvedFile) { - normalizedPath = TypeScript.changePathToDSTR(normalizedPath); - resolvedFile = ioHost.findFile(parentPath, normalizedPath); - } - } - if(resolvedFile) { - resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); - TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); - resolvedFile.content = resolvedFile.content; - this.visited[absoluteModuleID] = true; - } else { - TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); - } - } - if(resolvedFile && resolvedFile.content != null) { - var rootDir = ioHost.dirName(resolvedFile.path); - var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); - var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); - var resolvedFilePath = ioHost.resolvePath(resolvedFile.path); - sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; - for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { - var fileReference = preProcessedFileInfo.referencedFiles[i]; - var normalizedPath = TypeScript.isRooted(fileReference.path) ? fileReference.path : rootDir + "/" + fileReference.path; - normalizedPath = ioHost.resolvePath(normalizedPath); - if(resolvedFilePath == normalizedPath) { - resolutionDispatcher.postResolutionError(normalizedPath, fileReference.startLine, fileReference.startCol, "Incorrect reference: File contains reference to itself."); - continue; - } - var resolutionResult = this.resolveCode(fileReference.path, rootDir, false, resolutionDispatcher); - if(!resolutionResult) { - resolutionDispatcher.postResolutionError(resolvedFilePath, fileReference.startLine, fileReference.startCol, "Incorrect reference: referenced file: \"" + fileReference.path + "\" cannot be resolved."); - } - } - for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { - var fileImport = preProcessedFileInfo.importedFiles[i]; - var resolutionResult = this.resolveCode(fileImport.path, rootDir, true, resolutionDispatcher); - if(!resolutionResult) { - resolutionDispatcher.postResolutionError(resolvedFilePath, fileImport.startLine, fileImport.startCol, "Incorrect reference: imported file: \"" + fileImport.path + "\" cannot be resolved."); - } - } - resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); - } - } - return true; - }; - return CodeResolver; - })(); - TypeScript.CodeResolver = CodeResolver; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var StyleSettings = (function () { - function StyleSettings() { - this.bitwise = false; - this.blockInCompoundStmt = false; - this.eqeqeq = false; - this.forin = false; - this.emptyBlocks = true; - this.newMustBeUsed = false; - this.requireSemi = false; - this.assignmentInCond = false; - this.eqnull = false; - this.evalOK = true; - this.innerScopeDeclEscape = true; - this.funcInLoop = true; - this.reDeclareLocal = true; - this.literalSubscript = true; - this.implicitAny = false; - } - StyleSettings.prototype.setOption = function (opt, val) { - var optExists = this[opt]; - if(optExists !== undefined) { - this[opt] = val; - return true; - } else { - return false; - } - }; - StyleSettings.prototype.parseOptions = function (str) { - var opts = str.split(";"); - for(var i = 0, len = opts.length; i < len; i++) { - var opt = opts[i]; - var val = true; - var colonIndex = opt.lastIndexOf(":"); - if(colonIndex >= 0) { - var valStr = opt.substring(colonIndex + 1); - opt = opt.substring(0, colonIndex); - if(valStr == "off") { - val = false; - } - } - if(!this.setOption(opt, val)) { - return false; - } - } - return true; - }; - return StyleSettings; - })(); - TypeScript.StyleSettings = StyleSettings; - var CompilationSettings = (function () { - function CompilationSettings() { - this.styleSettings = new StyleSettings(); - this.propagateConstants = false; - this.minWhitespace = false; - this.parseOnly = false; - this.errorRecovery = false; - this.emitComments = false; - this.watch = false; - this.exec = false; - this.resolve = true; - this.controlFlow = false; - this.printControlFlow = false; - this.controlFlowUseDef = false; - this.errorOnWith = true; - this.preprocess = true; - this.canCallDefinitionSignature = false; - this.inferPropertiesFromThisAssignment = false; - this.useDefaultLib = true; - this.codeGenTarget = TypeScript.CodeGenTarget.ES3; - this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; - this.outputOption = ""; - this.mapSourceFiles = false; - this.emitFullSourceMapPath = false; - this.generateDeclarationFiles = false; - this.useCaseSensitiveFileResolution = false; - } - CompilationSettings.prototype.setStyleOptions = function (str) { - this.styleSettings.parseOptions(str); - }; - return CompilationSettings; - })(); - TypeScript.CompilationSettings = CompilationSettings; - function getFileReferenceFromReferencePath(comment) { - var referencesRegEx = /^(\/\/\/\s*/gim; - var match = referencesRegEx.exec(comment); - if(match) { - var path = TypeScript.normalizePath(match[3]); - var adjustedPath = TypeScript.normalizePath(path); - var isResident = match.length >= 7 && match[6] == "true"; - if(isResident) { - TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); - } - return { - minChar: 0, - limChar: 0, - startLine: 0, - startCol: 0, - path: TypeScript.switchToForwardSlashes(adjustedPath), - isResident: isResident - }; - } else { - return null; - } - } - function getAdditionalDependencyPath(comment) { - var amdDependencyRegEx = /^(\/\/\/\s*/gim; - var match = amdDependencyRegEx.exec(comment); - if(match) { - var path = match[3]; - return path; - } else { - return null; - } - } - TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; - function getImplicitImport(comment) { - var implicitImportRegEx = /^(\/\/\/\s*/gim; - var match = implicitImportRegEx.exec(comment); - if(match) { - return true; - } - return false; - } - TypeScript.getImplicitImport = getImplicitImport; - function getStyleSettings(comment, styleSettings) { - var styleRegEx = /^(\/\/\/\s*/gim; - var settings = styleRegEx.exec(comment); - if(settings) { - var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/gim; - settings = settingsRegEx.exec(settings[2]); - if(settings) { - for(var i = 0; i < settings.length; i++) { - var setting = (settings[i]).split("="); - var on = "\"on\""; - switch(setting[0]) { - case "blockInCompoundStmt": - styleSettings.blockInCompoundStmt = setting[1] == on; - break; - case "eqeqeq": - styleSettings.eqeqeq = setting[1] == on; - break; - case "forin": - styleSettings.forin = setting[1] == on; - break; - case "emptyBlocks": - styleSettings.emptyBlocks = setting[1] == on; - break; - case "newMustBeUsed": - styleSettings.newMustBeUsed = setting[1] == on; - break; - case "requireSemi": - styleSettings.requireSemi = setting[1] == on; - break; - case "assignmentInCond": - styleSettings.assignmentInCond = setting[1] == on; - break; - case "eqnull": - styleSettings.eqnull = setting[1] == on; - break; - case "evalOK": - styleSettings.evalOK = setting[1] == on; - break; - case "innerScopeDeclEscape": - styleSettings.innerScopeDeclEscape = setting[1] == on; - break; - case "funcInLoop": - styleSettings.funcInLoop = setting[1] == on; - break; - case "reDeclareLocal": - styleSettings.reDeclareLocal = setting[1] == on; - break; - case "literalSubscript": - styleSettings.literalSubscript = setting[1] == on; - break; - case "implicitAny": - styleSettings.implicitAny = setting[1] == on; - break; - } - } - } - } - } - TypeScript.getStyleSettings = getStyleSettings; - function getReferencedFiles(sourceText) { - var preProcessInfo = preProcessFile(sourceText, null, false); - return preProcessInfo.referencedFiles; - } - TypeScript.getReferencedFiles = getReferencedFiles; - function preProcessFile(sourceText, options, readImportFiles) { - if (typeof options === "undefined") { options = new CompilationSettings(); } - if (typeof readImportFiles === "undefined") { readImportFiles = true; } - var scanner = new TypeScript.Scanner(); - scanner.resetComments(); - scanner.setSourceText(sourceText, TypeScript.LexMode.File); - var tok = scanner.scan(); - var comments = []; - var comment = null; - var leftCurlies = []; - var settings = options; - var referencedFiles = []; - var importedFiles = []; - var isLibFile = false; - while(tok.tokenId != TypeScript.TokenID.EndOfFile) { - if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Equals) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.Module) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.OpenParen) { - tok = scanner.scan(); - if(tok.tokenId == TypeScript.TokenID.StringLiteral) { - var ref = { - minChar: scanner.startPos, - limChar: scanner.pos, - startLine: scanner.line, - startCol: scanner.col, - path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), - isResident: false - }; - importedFiles.push(ref); - } - } - } - } - } - } - if(tok.tokenId == TypeScript.TokenID.OpenBrace) { - leftCurlies.push(tok); - } - if(tok.tokenId == TypeScript.TokenID.CloseBrace) { - leftCurlies.pop(); - } - tok = scanner.scan(); - } - comments = scanner.getComments(); - for(var iComment = 0; iComment < comments.length; iComment++) { - comment = comments[iComment]; - if(!comment.isBlock) { - var referencedCode = getFileReferenceFromReferencePath(comment.getText()); - if(referencedCode) { - referencedCode.minChar = comment.startPos; - referencedCode.limChar = referencedCode.minChar + comment.value.length; - var result = { - line: -1, - col: -1 - }; - TypeScript.getSourceLineColFromMap(result, comment.startPos, scanner.lineMap); - if(result.col >= 0) { - result.col++; - } - referencedCode.startLine = result.line; - referencedCode.startCol = result.col; - referencedFiles.push(referencedCode); - } - if(settings) { - getStyleSettings(comment.getText(), settings.styleSettings); - var isNoLibRegex = /^(\/\/\/\s*/gim; - var isNoLibMatch = isNoLibRegex.exec(comment.getText()); - if(isNoLibMatch) { - isLibFile = (isNoLibMatch[3] == "true"); - } - } - } - } - return { - settings: settings, - referencedFiles: referencedFiles, - importedFiles: importedFiles, - isLibFile: isLibFile - }; - } - TypeScript.preProcessFile = preProcessFile; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var IncrementalParser = (function () { - function IncrementalParser(logger) { - this.logger = logger; - this.astLogger = new TypeScript.AstLogger(this.logger); - } - IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - if(editRange.isUnknown()) { - this.logger.log(" Bailing out because edit range is unknown"); - return null; - } - var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); - var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); - if(scope1 == null || scope2 == null) { - this.logger.log(" Bailing out because containing scopes cannot be determined"); - return null; - } - if(scope1.scopeStartAST !== scope2.scopeStartAST) { - this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength <= 0) { - this.logger.log(" Bailing out because scope has been entirely removed from new source text"); - return null; - } - return scope1; - }; - IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { - this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); - if(editRange === null) { - throw new Error("editRange should be valid"); - } - var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); - if(scope1 === null) { - return null; - } - var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; - if(newScopeLength >= newSourceText.getLength() / 2) { - this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); - return null; - } - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); - if(quickParseResult.endLexState != TypeScript.LexState.Start) { - this.logger.log(" Bailing out because scope contains unterminated comment"); - return null; - } - var scriptFragment = quickParseResult.Script; - if(scriptFragment.vars.members.length !== 0) { - this.logger.log(" Bailing out because new source text defines variables"); - return null; - } - if(scriptFragment.bod.members.length !== 1) { - this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); - return null; - } - var oldScope = scope1.scopeStartAST; - var newScope = scriptFragment.bod.members[0]; - if(oldScope.nodeType != newScope.nodeType) { - this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); - return null; - } - if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { - this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); - return null; - } - if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); - return null; - } - if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { - this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); - return null; - } - if(newScope.minChar !== 0) { - this.logger.log(" Bailing out because new function declaration does not start at position 0"); - return null; - } - if(newScope.limChar !== newScopeLength) { - this.logger.log(" Bailing out because new function declaration does not end at the new end position"); - return null; - } - return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); - }; - IncrementalParser.prototype.mergeTrees = function (updateResult) { - var _this = this; - TypeScript.timeFunction(this.logger, "mergeTrees()", function () { - var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); - _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); - _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); - _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); - _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); - }); - }; - IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { - var _this = this; - var pre = function (cur, parent, walker) { - if(cur === oldAst) { - newAst.preComments = cur.preComments; - newAst.postComments = cur.postComments; - _this.logger.log("replaced old AST node with new one in script AST"); - walker.options.stopWalk(); - return newAst; - } - if(TypeScript.isValidAstNode(cur)) { - if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - }; - IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { - var lineMap1 = script.locationInfo.lineMap; - var lineMap2 = partial.locationInfo.lineMap; - if(this.logger.information()) { - this.logger.log("lineMap1 (before):"); - this.astLogger.logLinemap(lineMap1); - this.logger.log("lineMap2 (quick parse):"); - this.astLogger.logLinemap(lineMap2); - this.logger.log("EditRange=" + editRange); - } - var i1 = 2; - var i2 = 2; - var len1 = lineMap1.length; - var len2 = lineMap2.length; - while(i1 < len1) { - if(lineMap1[i1] <= editRange.minChar) { - i1++; - } else if(lineMap1[i1] >= editRange.limChar) { - lineMap1[i1] += editRange.delta; - i1++; - } else { - if(i2 < len2) { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } else { - lineMap1.splice(i1, 1); - len1--; - } - } - } - if(i2 < len2) { - if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { - i1 = 2; - while(i1 < len1 && i2 < len2) { - if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { - i1++; - } else { - lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); - i1++; - len1++; - i2++; - } - } - } - for(; i2 < len2; i2++) { - lineMap1.push(lineMap2[i2] + editRange.minChar); - } - } - if(this.logger.information()) { - this.logger.log("lineMap1 (after merge):"); - this.astLogger.logLinemap(lineMap1); - } - }; - IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { - var applyDelta = function (ast) { - if(ast.minChar !== -1 && ast.minChar >= start) { - ast.minChar += delta; - } - if(ast.limChar !== -1 && ast.limChar >= start) { - ast.limChar += delta; - } - }; - var applyDeltaToComments = function (comments) { - if(comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++) { - applyDelta(comments[i]); - } - } - }; - var pre = function (cur, parent, walker) { - if(cur.limChar !== -1 && cur.limChar < start) { - walker.options.goChildren = false; - } - applyDelta(cur); - applyDeltaToComments(cur.preComments); - applyDeltaToComments(cur.postComments); - return cur; - }; - TypeScript.getAstWalkerFactory().walk(ast, pre); - }; - return IncrementalParser; - })(); - TypeScript.IncrementalParser = IncrementalParser; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - var DeclFileWriter = (function () { - function DeclFileWriter(declFile) { - this.declFile = declFile; - this.onNewLine = true; - } - DeclFileWriter.prototype.Write = function (s) { - this.declFile.Write(s); - this.onNewLine = false; - }; - DeclFileWriter.prototype.WriteLine = function (s) { - this.declFile.WriteLine(s); - this.onNewLine = true; - }; - DeclFileWriter.prototype.Close = function () { - this.declFile.Close(); - }; - return DeclFileWriter; - })(); - TypeScript.DeclFileWriter = DeclFileWriter; - var DeclarationEmitter = (function () { - function DeclarationEmitter(checker, emitOptions, errorReporter) { - this.checker = checker; - this.emitOptions = emitOptions; - this.errorReporter = errorReporter; - this.declFile = null; - this.indenter = new TypeScript.Indenter(); - this.declarationContainerStack = []; - this.isDottedModuleName = []; - this.ignoreCallbackAst = null; - this.singleDeclFile = null; - this.varListCount = 0; - } - DeclarationEmitter.prototype.getAstDeclarationContainer = function () { - return this.declarationContainerStack[this.declarationContainerStack.length - 1]; - }; - DeclarationEmitter.prototype.emitDottedModuleName = function () { - return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; - }; - DeclarationEmitter.prototype.setDeclarationFile = function (file) { - this.declFile = new DeclFileWriter(file); - }; - DeclarationEmitter.prototype.Close = function () { - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - DeclarationEmitter.prototype.emitDeclarations = function (script) { - TypeScript.AstWalkerWithDetailCallback.walk(script, this); - }; - DeclarationEmitter.prototype.getIndentString = function (declIndent) { - if (typeof declIndent === "undefined") { declIndent = false; } - if(this.emitOptions.minWhitespace) { - return ""; - } else { - return this.indenter.getIndent(); - } - }; - DeclarationEmitter.prototype.emitIndent = function () { - this.declFile.Write(this.getIndentString()); - }; - DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { - if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } - if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } - var container; - if(useDeclarationContainerTop) { - container = this.getAstDeclarationContainer(); - } else { - container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; - } - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - return false; - } - if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { - return false; - } - return true; - }; - DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { - if(this.ignoreCallbackAst) { - TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); - this.ignoreCallbackAst = null; - return false; - } else if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { - this.ignoreCallbackAst = astWithPrePostCallback; - return false; - } - return true; - }; - DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { - var result = this.getIndentString(); - var accessorString = ""; - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { - accessorString = "get "; - } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { - accessorString = "set "; - } - var container = this.getAstDeclarationContainer(); - if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { - result += "export "; - } - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { - result += "private "; - } - result += "static " + accessorString; - } else { - if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { - result += "private " + accessorString; - } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { - result += "public " + accessorString; - } else { - if(accessorString == "") { - result += typeString + " "; - } else { - result += accessorString; - } - } - } - return result; - }; - DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { - this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); - }; - DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { - if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } - return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); - }; - DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { - this.declarationContainerStack.push(ast); - }; - DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { - TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); - this.declarationContainerStack.pop(); - }; - DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { - if (typeof emitIndent === "undefined") { emitIndent = false; } - if(memberName.prefix == "{ ") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.WriteLine("{"); - this.indenter.increaseIndent(); - emitIndent = true; - } else if(memberName.prefix != "") { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write(memberName.prefix); - emitIndent = false; - } - if(memberName.isString()) { - if(emitIndent) { - this.emitIndent(); - } - this.declFile.Write((memberName).text); - } else { - var ar = memberName; - for(var index = 0; index < ar.entries.length; index++) { - this.emitTypeNamesMember(ar.entries[index], emitIndent); - if(ar.delim == "; ") { - this.declFile.WriteLine(";"); - } - } - } - if(memberName.suffix == "}") { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.Write(memberName.suffix); - } else { - this.declFile.Write(memberName.suffix); - } - }; - DeclarationEmitter.prototype.emitTypeSignature = function (type) { - var containingScope = null; - var declarationContainerAst = this.getAstDeclarationContainer(); - switch(declarationContainerAst.nodeType) { - case TypeScript.NodeType.ModuleDeclaration: - case TypeScript.NodeType.InterfaceDeclaration: - case TypeScript.NodeType.FuncDecl: - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.containedScope; - } - break; - case TypeScript.NodeType.Script: - var script = declarationContainerAst; - if(script.bod) { - containingScope = script.bod.enclosingScope; - } - break; - case TypeScript.NodeType.ClassDeclaration: - if(declarationContainerAst.type) { - containingScope = declarationContainerAst.type.instanceType.containedScope; - } - break; - default: - TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); - } - var typeNameMembers = type.getScopedTypeNameEx(containingScope); - this.emitTypeNamesMember(typeNameMembers); - }; - DeclarationEmitter.prototype.emitComment = function (comment) { - var text = comment.getText(); - if(this.declFile.onNewLine) { - this.emitIndent(); - } else if(!comment.isBlockComment) { - this.declFile.WriteLine(""); - this.emitIndent(); - } - this.declFile.Write(text[0]); - for(var i = 1; i < text.length; i++) { - this.declFile.WriteLine(""); - this.emitIndent(); - this.declFile.Write(text[i]); - } - if(comment.endsLine || !comment.isBlockComment) { - this.declFile.WriteLine(""); - } else { - this.declFile.Write(" "); - } - }; - DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { - if (typeof endLine === "undefined") { endLine = true; } - if(!this.emitOptions.emitComments) { - return; - } - var declComments = astOrSymbol.getDocComments(); - if(declComments.length > 0) { - for(var i = 0; i < declComments.length; i++) { - this.emitComment(declComments[i]); - } - if(endLine) { - if(!this.declFile.onNewLine) { - this.declFile.WriteLine(""); - } - } else { - if(this.declFile.onNewLine) { - this.emitIndent(); - } - } - } - }; - DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { - if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { - var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - this.emitDeclarationComments(varDecl); - if(!interfaceMember) { - if(this.varListCount >= 0) { - this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); - this.varListCount = -this.varListCount; - } - this.declFile.Write(varDecl.id.text); - } else { - this.emitIndent(); - this.declFile.Write(varDecl.id.text); - if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("?"); - } - } - var type = null; - if(varDecl.typeExpr && varDecl.typeExpr.type) { - type = varDecl.typeExpr.type; - } else if(varDecl.sym) { - type = (varDecl.sym).getType(); - if(type == this.checker.anyType) { - type = null; - } - } - if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(type); - } - if(this.varListCount > 0) { - this.varListCount--; - } else if(this.varListCount < 0) { - this.varListCount++; - } - if(this.varListCount < 0) { - this.declFile.Write(", "); - } else { - this.declFile.WriteLine(";"); - } - } - return false; - }; - DeclarationEmitter.prototype.BlockCallback = function (pre, block) { - if(!block.isStatementBlock) { - if(pre) { - this.varListCount = block.statements.members.length; - } else { - this.varListCount = 0; - } - return true; - } - return false; - }; - DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { - this.emitDeclarationComments(argDecl, false); - this.declFile.Write(argDecl.id.text); - if(argDecl.isOptionalArg()) { - this.declFile.Write("?"); - } - if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - }; - DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { - if(!pre) { - return false; - } - if(funcDecl.isAccessor()) { - return this.emitPropertyAccessorSignature(funcDecl); - } - var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); - if(funcDecl.bod) { - if(funcDecl.isConstructor) { - if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { - return false; - } - } else { - if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - return false; - } - } - } else if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { - var signatures = funcDecl.type.call.signatures; - var firstSignature = signatures[0].declAST; - if(firstSignature.bod) { - firstSignature = signatures[1].declAST; - } - if(firstSignature != funcDecl) { - return false; - } - } - if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { - return false; - } - this.emitDeclarationComments(funcDecl); - if(funcDecl.isConstructor) { - this.emitIndent(); - this.declFile.Write("constructor"); - } else { - var id = funcDecl.getNameText(); - if(!isInterfaceMember) { - this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); - if(id != "__missing" || !funcDecl.name || !funcDecl.name.isMissing()) { - this.declFile.Write(id); - } else if(funcDecl.isConstructMember()) { - this.declFile.Write("new"); - } - } else { - this.emitIndent(); - if(funcDecl.isConstructMember()) { - this.declFile.Write("new"); - } else if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { - this.declFile.Write(id); - if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { - this.declFile.Write("? "); - } - } - } - } - if(!funcDecl.isIndexerMember()) { - this.declFile.Write("("); - } else { - this.declFile.Write("["); - } - this.indenter.increaseIndent(); - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - this.emitArgDecl(argDecl, funcDecl); - if(i < (argsLen - 1)) { - this.declFile.Write(", "); - } - } - } - if(funcDecl.variableArgList) { - var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; - if(funcDecl.arguments.members.length > 1) { - this.declFile.Write(", ..."); - } else { - this.declFile.Write("..."); - } - this.emitArgDecl(lastArg, funcDecl); - } - this.indenter.decreaseIndent(); - if(!funcDecl.isIndexerMember()) { - this.declFile.Write(")"); - } else { - this.declFile.Write("]"); - } - if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(funcDecl.signature.returnType.type); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { - if(bases && (bases.members.length > 0)) { - this.declFile.Write(" " + qual + " "); - var basesLen = bases.members.length; - for(var i = 0; i < basesLen; i++) { - var baseExpr = bases.members[i]; - var baseSymbol = baseExpr.type.symbol; - var baseType = baseExpr.type; - if(i > 0) { - this.declFile.Write(", "); - } - this.emitTypeSignature(baseType); - } - } - }; - DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { - var accessorSymbol = funcDecl.accessorSymbol; - if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { - return false; - } - this.emitDeclarationComments(accessorSymbol); - this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); - this.declFile.Write(funcDecl.name.text); - var propertyType = accessorSymbol.getType(); - if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { - this.declFile.Write(" : "); - this.emitTypeSignature(propertyType); - } - this.declFile.WriteLine(";"); - return false; - }; - DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { - if(funcDecl.arguments) { - var argsLen = funcDecl.arguments.members.length; - if(funcDecl.variableArgList) { - argsLen--; - } - for(var i = 0; i < argsLen; i++) { - var argDecl = funcDecl.arguments.members[i]; - if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { - this.emitDeclarationComments(argDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); - this.declFile.Write(argDecl.id.text); - if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { - this.declFile.Write(": "); - this.emitTypeSignature(argDecl.type); - } - this.declFile.WriteLine(";"); - } - } - } - }; - DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { - return false; - } - if(pre) { - var className = classDecl.name.text; - this.emitDeclarationComments(classDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); - this.declFile.Write(className); - this.emitBaseList(classDecl.extendsList, "extends"); - this.emitBaseList(classDecl.implementsList, "implements"); - this.declFile.WriteLine(" {"); - this.pushDeclarationContainer(classDecl); - this.indenter.increaseIndent(); - if(classDecl.constructorDecl) { - this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); - } - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(classDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { - return false; - } - if(pre) { - var interfaceName = interfaceDecl.name.text; - this.emitDeclarationComments(interfaceDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); - this.declFile.Write(interfaceName); - this.emitBaseList(interfaceDecl.extendsList, "extends"); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - this.pushDeclarationContainer(interfaceDecl); - } else { - this.indenter.decreaseIndent(); - this.popDeclarationContainer(interfaceDecl); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - return true; - }; - DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { - if(pre) { - if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { - this.emitDeclarationComments(importDecl); - this.emitIndent(); - this.declFile.Write("import "); - this.declFile.Write(importDecl.id.text + " = "); - if(importDecl.isDynamicImport) { - this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); - } else { - this.declFile.WriteLine(importDecl.getAliasName() + ";"); - } - } - } - return false; - }; - DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { - if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { - return false; - } - this.emitDeclarationComments(moduleDecl); - this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); - this.declFile.WriteLine(moduleDecl.name.text + " {"); - this.indenter.increaseIndent(); - var membersLen = moduleDecl.members.members.length; - for(var j = 1; j < membersLen; j++) { - var memberDecl = moduleDecl.members.members[j]; - if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { - this.emitDeclarationComments(memberDecl); - this.emitIndent(); - this.declFile.WriteLine((memberDecl).id.text + ","); - } else { - TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); - } - } - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - return false; - }; - DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { - if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { - if(pre) { - if(!this.emitOptions.outputMany) { - this.singleDeclFile = this.declFile; - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); - var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); - try { - this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - } - this.pushDeclarationContainer(moduleDecl); - } else { - if(!this.emitOptions.outputMany) { - TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); - TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); - try { - this.declFile.Close(); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - this.declFile = this.singleDeclFile; - } - this.popDeclarationContainer(moduleDecl); - } - } - return true; - } - if(moduleDecl.isEnum()) { - if(pre) { - this.emitEnumSignature(moduleDecl); - } - return false; - } - if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { - return false; - } - if(pre) { - if(this.emitDottedModuleName()) { - this.dottedModuleEmit += "."; - } else { - this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); - } - this.dottedModuleEmit += moduleDecl.name.text; - var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); - var moduleDeclComments = moduleDecl.getDocComments(); - isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); - this.isDottedModuleName.push(isCurrentModuleDotted); - this.pushDeclarationContainer(moduleDecl); - if(!isCurrentModuleDotted) { - this.emitDeclarationComments(moduleDecl); - this.declFile.Write(this.dottedModuleEmit); - this.declFile.WriteLine(" {"); - this.indenter.increaseIndent(); - } - } else { - if(!this.emitDottedModuleName()) { - this.indenter.decreaseIndent(); - this.emitIndent(); - this.declFile.WriteLine("}"); - } - this.popDeclarationContainer(moduleDecl); - this.isDottedModuleName.pop(); - } - return true; - }; - DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { - if(pre) { - if(this.emitOptions.outputMany) { - for(var i = 0; i < script.referencedFiles.length; i++) { - var referencePath = script.referencedFiles[i].path; - var declareFileName; - if(TypeScript.isRooted(referencePath)) { - declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); - } else { - declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); - } - this.declFile.WriteLine('/// '); - } - } - this.pushDeclarationContainer(script); - } else { - this.popDeclarationContainer(script); - } - return true; - }; - DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { - return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); - }; - return DeclarationEmitter; - })(); - TypeScript.DeclarationEmitter = DeclarationEmitter; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (UpdateUnitKind) { - UpdateUnitKind._map = []; - UpdateUnitKind._map[0] = "Unknown"; - UpdateUnitKind.Unknown = 0; - UpdateUnitKind._map[1] = "NoEdits"; - UpdateUnitKind.NoEdits = 1; - UpdateUnitKind._map[2] = "EditsInsideSingleScope"; - UpdateUnitKind.EditsInsideSingleScope = 2; - })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); - var UpdateUnitKind = TypeScript.UpdateUnitKind; - var ScriptEditRange = (function () { - function ScriptEditRange(minChar, limChar, delta) { - this.minChar = minChar; - this.limChar = limChar; - this.delta = delta; - } - ScriptEditRange.unknown = function unknown() { - return new ScriptEditRange(-1, -1, -1); - }; - ScriptEditRange.prototype.isUnknown = function () { - return this.minChar === -1 && this.limChar === -1 && this.delta === -1; - }; - ScriptEditRange.prototype.containsPosition = function (pos) { - return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); - }; - ScriptEditRange.prototype.toString = function () { - return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; - }; - return ScriptEditRange; - })(); - TypeScript.ScriptEditRange = ScriptEditRange; - var UpdateUnitResult = (function () { - function UpdateUnitResult(kind, unitIndex, script1, script2) { - this.kind = kind; - this.unitIndex = unitIndex; - this.script1 = script1; - this.script2 = script2; - this.scope1 = null; - this.scope2 = null; - this.editRange = null; - this.parseErrors = []; - } - UpdateUnitResult.noEdits = function noEdits(unitIndex) { - return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); - }; - UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); - result.parseErrors = parseErrors; - return result; - }; - UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { - var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); - result.scope1 = scope1; - result.scope2 = scope2; - result.editRange = editRange; - result.parseErrors = parseErrors; - return result; - }; - return UpdateUnitResult; - })(); - TypeScript.UpdateUnitResult = UpdateUnitResult; - var ErrorEntry = (function () { - function ErrorEntry(unitIndex, minChar, limChar, message) { - this.unitIndex = unitIndex; - this.minChar = minChar; - this.limChar = limChar; - this.message = message; - } - return ErrorEntry; - })(); - TypeScript.ErrorEntry = ErrorEntry; - TypeScript.defaultSettings = new TypeScript.CompilationSettings(); - var TypeScriptCompiler = (function () { - function TypeScriptCompiler(errorOutput, logger, settings) { - if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } - if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } - this.errorOutput = errorOutput; - this.logger = logger; - this.settings = settings; - this.parser = new TypeScript.Parser(); - this.typeFlow = null; - this.scripts = new TypeScript.ASTList(); - this.units = new Array(); - this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); - this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); - this.errorReporter.parser = this.parser; - this.initTypeChecker(this.errorOutput); - this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; - this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; - this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; - this.emitSettings = new TypeScript.EmitOptions(this.settings); - TypeScript.codeGenTarget = settings.codeGenTarget; - } - TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { - return TypeScript.timeFunction(this.logger, funcDescription, func); - }; - TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { - this.persistentTypeState.refreshPersistentState(); - this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); - this.typeChecker.errorReporter = this.errorReporter; - this.typeChecker.checkControlFlow = this.settings.controlFlow; - this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; - this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; - this.typeChecker.errorsOnWith = this.settings.errorOnWith; - this.typeChecker.styleSettings = this.settings.styleSettings; - this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; - this.errorReporter.checker = this.typeChecker; - this.setErrorOutput(this.errorOutput); - }; - TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { - this.errorOutput = outerr; - this.errorReporter.setErrOut(outerr); - this.parser.outfile = outerr; - }; - TypeScriptCompiler.prototype.emitCommentsToOutput = function () { - this.emitSettings = new TypeScript.EmitOptions(this.settings); - }; - TypeScriptCompiler.prototype.setErrorCallback = function (fn) { - this.parser.errorCallback = fn; - }; - TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { - return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); - }; - TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("updateSourceUnit(" + filename + ")", function () { - var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); - return _this.applyUpdateResult(updateResult); - }); - }; - TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { - switch(updateResult.kind) { - case UpdateUnitKind.NoEdits: - return false; - case UpdateUnitKind.Unknown: - this.scripts.members[updateResult.unitIndex] = updateResult.script2; - this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; - for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { - var e = updateResult.parseErrors[i]; - if(this.parser.errorCallback) { - this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); - } - } - return true; - case UpdateUnitKind.EditsInsideSingleScope: - new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); - return true; - } - }; - TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { - var _this = this; - return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { - for(var i = 0, len = _this.units.length; i < len; i++) { - if(_this.units[i].filename == filename) { - if((_this.scripts.members[i]).isResident) { - return UpdateUnitResult.noEdits(i); - } - if(setRecovery) { - _this.parser.setErrorRecovery(null); - } - var updateResult; - var parseErrors = []; - var errorCapture = function (minChar, charLen, message, unitIndex) { - parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); - }; - var svErrorCallback = _this.parser.errorCallback; - if(svErrorCallback) { - _this.parser.errorCallback = errorCapture; - } - var oldScript = _this.scripts.members[i]; - var newScript = _this.parser.parse(sourceText, filename, i); - if(svErrorCallback) { - _this.parser.errorCallback = svErrorCallback; - } - updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); - return updateResult; - } - } - throw new Error("Unknown file \"" + filename + "\""); - }); - }; - TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { - if (typeof keepResident === "undefined") { keepResident = false; } - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); - }; - TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { - if (typeof referencedFiles === "undefined") { referencedFiles = []; } - var _this = this; - return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { - var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); - script.referencedFiles = referencedFiles; - script.isResident = keepResident; - _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); - var index = _this.units.length; - _this.units[index] = script.locationInfo; - _this.typeChecker.collectTypes(script); - _this.scripts.append(script); - return script; - }); - }; - TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { - return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); - }; - TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { - this.parser.setErrorRecovery(this.errorOutput); - var script = this.parser.parse(sourceText, filename, 0); - var index = this.units.length; - this.units[index] = script.locationInfo; - this.typeChecker.collectTypes(script); - this.scripts.append(script); - }; - TypeScriptCompiler.prototype.typeCheck = function () { - var _this = this; - return this.timeFunction("typeCheck()", function () { - var binder = new TypeScript.Binder(_this.typeChecker); - _this.typeChecker.units = _this.units; - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); - binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); - _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); - var i = 0; - var script = null; - var len = _this.scripts.members.length; - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(!script.isResident || script.hasBeenTypeChecked) { - continue; - } - _this.typeFlow.typeCheck(script); - script.hasBeenTypeChecked = true; - } - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - len = _this.scripts.members.length; - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.assignScopes(script); - _this.typeFlow.initLibs(); - } - for(i = 0; i < len; i++) { - script = _this.scripts.members[i]; - if(script.isResident) { - continue; - } - _this.typeFlow.typeCheck(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { - function cleanASTType(ast, parent) { - ast.type = null; - if(ast.nodeType == TypeScript.NodeType.VarDecl) { - var vardecl = ast; - vardecl.sym = null; - } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { - var argdecl = ast; - argdecl.sym = null; - } else if(ast.nodeType == TypeScript.NodeType.Name) { - var name = ast; - name.sym = null; - } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { - var funcdecl = ast; - funcdecl.signature = null; - funcdecl.freeVariables = new Array(); - funcdecl.symbols = null; - funcdecl.accessorSymbol = null; - funcdecl.scopeType = null; - } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { - var modDecl = ast; - modDecl.mod = null; - } else if(ast.nodeType == TypeScript.NodeType.With) { - (ast).withSym = null; - } else if(ast.nodeType == TypeScript.NodeType.Catch) { - (ast).containedScope = null; - } else if(ast.nodeType === TypeScript.NodeType.Script) { - (ast).externallyVisibleImportedSymbols = []; - } - return ast; - } - TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); - }; - TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { - var _this = this; - return this.timeFunction("cleanTypesForReTypeCheck()", function () { - for(var i = 0, len = _this.scripts.members.length; i < len; i++) { - var script = _this.scripts.members[i]; - if((script).isResident) { - continue; - } - _this.cleanASTTypesForReTypeCheck(script); - _this.typeChecker.collectTypes(script); - } - return null; - }); - }; - TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { - return this.timeFunction("attemptIncrementalTypeCheck()", function () { - return false; - }); - }; - TypeScriptCompiler.prototype.reTypeCheck = function () { - var _this = this; - return this.timeFunction("reTypeCheck()", function () { - TypeScript.CompilerDiagnostics.analysisPass++; - _this.initTypeChecker(_this.errorOutput); - _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); - _this.cleanTypesForReTypeCheck(); - return _this.typeCheck(); - }); - }; - TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(!script.isDeclareFile && script.topLevelMod != null) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { - var commonComponents = []; - var commonComponentsLength = -1; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(script.emitRequired(this.emitSettings)) { - var fileName = script.locationInfo.filename; - var fileComponents = TypeScript.filePathComponents(fileName); - if(commonComponentsLength == -1) { - commonComponents = fileComponents; - commonComponentsLength = commonComponents.length; - } else { - var updatedPath = false; - for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { - if(commonComponents[j] != fileComponents[j]) { - commonComponentsLength = j; - updatedPath = true; - if(j == 0) { - this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); - return; - } - break; - } - } - if(!updatedPath && fileComponents.length < commonComponentsLength) { - commonComponentsLength = fileComponents.length; - } - } - } - } - this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; - if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { - this.emitSettings.outputOption += "/"; - } - }; - TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { - this.emitSettings.ioHost = ioHost; - if(this.emitSettings.outputOption == "") { - this.emitSettings.outputMany = true; - this.emitSettings.commonDirectoryPath = ""; - return; - } - this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); - if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = true; - } else if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { - this.emitSettings.outputMany = false; - } else { - this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); - } - if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { - this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); - } - if(this.emitSettings.outputMany) { - this.updateCommonDirectoryPath(); - } - }; - TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { - if(this.emitSettings.outputMany) { - return this.outputScriptToUTF8(script); - } else { - return this.outputScriptsToUTF8((this.scripts.members)); - } - }; - TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { - return TypeScript.getDeclareFilePath(fileName); - }; - TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { - if(!this.settings.generateDeclarationFiles) { - return false; - } - if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { - return false; - } - return true; - }; - TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { - if(!this.canEmitDeclarations(script)) { - return null; - } - if(!declarationEmitter) { - var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); - var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); - declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); - declarationEmitter.setDeclarationFile(declareFile); - } - declarationEmitter.emitDeclarations(script); - if(!reuseEmitter) { - declarationEmitter.Close(); - return null; - } else { - return declarationEmitter; - } - }; - TypeScriptCompiler.prototype.emitDeclarations = function () { - if(!this.canEmitDeclarations()) { - return; - } - if(this.errorReporter.hasErrors) { - return; - } - if(this.scripts.members.length == 0) { - return; - } - var declarationEmitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || declarationEmitter == null) { - declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); - } else { - this.emitDeclarationsUnit(script, true, declarationEmitter); - } - } - if(declarationEmitter) { - declarationEmitter.Close(); - } - }; - TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { - if(wholeFileNameReplaced) { - return fileName; - } else { - var splitFname = fileName.split("."); - splitFname.pop(); - return splitFname.join(".") + extension; - } - }; - TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); - }; - TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter, inputOutputMapper) { - if(!script.emitRequired(this.emitSettings)) { - return null; - } - var fname = script.locationInfo.filename; - if(!emitter) { - var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); - var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); - if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter, this.settings.emitFullSourceMapPath)); - } - if(inputOutputMapper) { - inputOutputMapper(script.locationInfo.unitIndex, outFname); - } - } else if(this.settings.mapSourceFiles) { - emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter, this.settings.emitFullSourceMapPath)); - } - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - if(!reuseEmitter) { - emitter.Close(); - return null; - } else { - return emitter; - } - }; - TypeScriptCompiler.prototype.emit = function (ioHost, inputOutputMapper) { - this.parseEmitOption(ioHost); - var emitter = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || emitter == null) { - emitter = this.emitUnit(script, !this.emitSettings.outputMany, null, inputOutputMapper); - } else { - this.emitUnit(script, true, emitter); - } - } - if(emitter) { - emitter.Close(); - } - }; - TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { - if(this.settings.mapSourceFiles) { - throw Error("Cannot generate source map"); - } - if(this.settings.generateDeclarationFiles) { - throw Error("Cannot generate declaration files"); - } - if(this.settings.outputOption != "") { - throw Error("Cannot parse output option"); - } - var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); - ; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - this.typeChecker.locationInfo = script.locationInfo; - emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); - } - }; - TypeScriptCompiler.prototype.emitAST = function (ioHost) { - this.parseEmitOption(ioHost); - var outFile = null; - var context = null; - for(var i = 0, len = this.scripts.members.length; i < len; i++) { - var script = this.scripts.members[i]; - if(this.emitSettings.outputMany || context == null) { - var fname = this.units[i].filename; - var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { - return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); - }; - var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); - outFile = this.createFile(outFname, this.useUTF8ForFile(script)); - context = new TypeScript.PrintContext(outFile, this.parser); - } - TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); - if(this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - } - if(!this.emitSettings.outputMany) { - try { - outFile.Close(); - } catch (e) { - this.errorReporter.emitterError(null, e.message); - } - } - }; - TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { - return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); - }; - TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { - for(var i = 0, len = scripts.length; i < len; i++) { - var script = scripts[i]; - if(this.outputScriptToUTF8(script)) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { - try { - return this.emitSettings.ioHost.createFile(fileName, useUTF8); - } catch (ex) { - this.errorReporter.emitterError(null, ex.message); - } - }; - return TypeScriptCompiler; - })(); - TypeScript.TypeScriptCompiler = TypeScriptCompiler; - var ScopeEntry = (function () { - function ScopeEntry(name, type, sym) { - this.name = name; - this.type = type; - this.sym = sym; - } - return ScopeEntry; - })(); - TypeScript.ScopeEntry = ScopeEntry; - var ScopeTraversal = (function () { - function ScopeTraversal(compiler) { - this.compiler = compiler; - } - ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { - if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { - return enclosingScopeContext.getObjectLiteralScope(); - } else if(enclosingScopeContext.isMemberCompletion) { - if(enclosingScopeContext.useFullAst) { - return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); - } else { - return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); - } - } else { - return enclosingScopeContext.getScope(); - } - }; - ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext, getPrettyTypeName) { - var scope = this.getScope(enclosingScopeContext); - if(scope == null) { - return []; - } - var inScopeNames = new TypeScript.StringHashTable(); - var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); - for(var i = 0; i < allSymbolNames.length; i++) { - var name = allSymbolNames[i]; - if(name == TypeScript.globalId || name == "_Core" || name == "_element") { - continue; - } - inScopeNames.add(name, ""); - } - var svModuleDecl = this.compiler.typeChecker.currentModDecl; - this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; - var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope, getPrettyTypeName); - this.compiler.typeChecker.currentModDecl = svModuleDecl; - return result; - }; - ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope, getPrettyTypeName) { - var result = []; - var enclosingScope = enclosingScopeContext.getScope(); - for(var i = 0; i < allNames.length; i++) { - var name = allNames[i]; - var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; - var symbol = scope.find(name, publicsOnly, false); - if(symbol == null) { - symbol = scope.find(name, publicsOnly, true); - } - var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; - if(symbol) { - if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { - var getPrettyOverload = getPrettyTypeName && symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl; - var type = symbol.getType(); - var typeName = type ? type.getScopedTypeName(enclosingScope, getPrettyOverload) : ""; - result.push(new ScopeEntry(name, typeName, symbol)); - } - } else { - if(name == "true" || name == "false") { - result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); - } - } - } - return result; - }; - return ScopeTraversal; - })(); - TypeScript.ScopeTraversal = ScopeTraversal; -})(TypeScript || (TypeScript = {})); -var TypeScript; -(function (TypeScript) { - (function (CompilerDiagnostics) { - CompilerDiagnostics.debug = false; - CompilerDiagnostics.diagnosticWriter = null; - CompilerDiagnostics.analysisPass = 0; - function Alert(output) { - if(CompilerDiagnostics.diagnosticWriter) { - CompilerDiagnostics.diagnosticWriter.Alert(output); - } - } - CompilerDiagnostics.Alert = Alert; - function debugPrint(s) { - if(CompilerDiagnostics.debug) { - Alert(s); - } - } - CompilerDiagnostics.debugPrint = debugPrint; - function assert(condition, s) { - if(CompilerDiagnostics.debug) { - if(!condition) { - Alert(s); - } - } - } - CompilerDiagnostics.assert = assert; - })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); - var CompilerDiagnostics = TypeScript.CompilerDiagnostics; - var NullLogger = (function () { - function NullLogger() { } - NullLogger.prototype.information = function () { - return false; - }; - NullLogger.prototype.debug = function () { - return false; - }; - NullLogger.prototype.warning = function () { - return false; - }; - NullLogger.prototype.error = function () { - return false; - }; - NullLogger.prototype.fatal = function () { - return false; - }; - NullLogger.prototype.log = function (s) { - }; - return NullLogger; - })(); - TypeScript.NullLogger = NullLogger; - var LoggerAdapter = (function () { - function LoggerAdapter(logger) { - this.logger = logger; - this._information = this.logger.information(); - this._debug = this.logger.debug(); - this._warning = this.logger.warning(); - this._error = this.logger.error(); - this._fatal = this.logger.fatal(); - } - LoggerAdapter.prototype.information = function () { - return this._information; - }; - LoggerAdapter.prototype.debug = function () { - return this._debug; - }; - LoggerAdapter.prototype.warning = function () { - return this._warning; - }; - LoggerAdapter.prototype.error = function () { - return this._error; - }; - LoggerAdapter.prototype.fatal = function () { - return this._fatal; - }; - LoggerAdapter.prototype.log = function (s) { - this.logger.log(s); - }; - return LoggerAdapter; - })(); - TypeScript.LoggerAdapter = LoggerAdapter; - var BufferedLogger = (function () { - function BufferedLogger() { - this.logContents = []; - } - BufferedLogger.prototype.information = function () { - return false; - }; - BufferedLogger.prototype.debug = function () { - return false; - }; - BufferedLogger.prototype.warning = function () { - return false; - }; - BufferedLogger.prototype.error = function () { - return false; - }; - BufferedLogger.prototype.fatal = function () { - return false; - }; - BufferedLogger.prototype.log = function (s) { - this.logContents.push(s); - }; - return BufferedLogger; - })(); - TypeScript.BufferedLogger = BufferedLogger; - function timeFunction(logger, funcDescription, func) { - var start = +new Date(); - var result = func(); - var end = +new Date(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); - return result; - } - TypeScript.timeFunction = timeFunction; - function stringToLiteral(value, length) { - var result = ""; - var addChar = function (index) { - var ch = value.charCodeAt(index); - switch(ch) { - case 0x09: - result += "\\t"; - break; - case 0x0a: - result += "\\n"; - break; - case 0x0b: - result += "\\v"; - break; - case 0x0c: - result += "\\f"; - break; - case 0x0d: - result += "\\r"; - break; - case 0x22: - result += "\\\""; - break; - case 0x27: - result += "\\\'"; - break; - case 0x5c: - result += "\\"; - break; - default: - result += value.charAt(index); - } - }; - var tooLong = (value.length > length); - if(tooLong) { - var mid = length >> 1; - for(var i = 0; i < mid; i++) { - addChar(i); - } - result += "(...)"; - for(var i = value.length - mid; i < value.length; i++) { - addChar(i); - } - } else { - length = value.length; - for(var i = 0; i < length; i++) { - addChar(i); - } - } - return result; - } - TypeScript.stringToLiteral = stringToLiteral; -})(TypeScript || (TypeScript = {}));